a752f00ff9eda20569cb86f992503d222b2d1870
[WebKit-https.git] / Source / JavaScriptCore / dfg / DFGObjectAllocationSinkingPhase.cpp
1 /*
2  * Copyright (C) 2015 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "DFGObjectAllocationSinkingPhase.h"
28
29 #if ENABLE(DFG_JIT)
30
31 #include "DFGBlockMapInlines.h"
32 #include "DFGClobbersExitState.h"
33 #include "DFGCombinedLiveness.h"
34 #include "DFGGraph.h"
35 #include "DFGInsertionSet.h"
36 #include "DFGLazyNode.h"
37 #include "DFGLivenessAnalysisPhase.h"
38 #include "DFGOSRAvailabilityAnalysisPhase.h"
39 #include "DFGPhase.h"
40 #include "DFGPromotedHeapLocation.h"
41 #include "DFGSSACalculator.h"
42 #include "DFGValidate.h"
43 #include "JSCInlines.h"
44
45 #include <list>
46
47 namespace JSC { namespace DFG {
48
49 namespace {
50
51 bool verbose = false;
52
53 // In order to sink object cycles, we use a points-to analysis coupled
54 // with an escape analysis. This analysis is actually similar to an
55 // abstract interpreter focused on local allocations and ignoring
56 // everything else.
57 //
58 // We represent the local heap using two mappings:
59 //
60 // - A set of the local allocations present in the function, where
61 //   each of those have a further mapping from
62 //   PromotedLocationDescriptor to local allocations they must point
63 //   to.
64 //
65 // - A "pointer" mapping from nodes to local allocations, if they must
66 //   be equal to said local allocation and are currently live. This
67 //   can be because the node is the actual node that created the
68 //   allocation, or any other node that must currently point to it -
69 //   we don't make a difference.
70 //
71 // The following graph is a motivation for why we separate allocations
72 // from pointers:
73 //
74 // Block #0
75 //  0: NewObject({})
76 //  1: NewObject({})
77 //  -: PutByOffset(@0, @1, x)
78 //  -: PutStructure(@0, {x:0})
79 //  2: GetByOffset(@0, x)
80 //  -: Jump(#1)
81 //
82 // Block #1
83 //  -: Return(@2)
84 //
85 // Here, we need to remember in block #1 that @2 points to a local
86 // allocation with appropriate fields and structures information
87 // (because we should be able to place a materialization on top of
88 // block #1 here), even though @1 is dead. We *could* just keep @1
89 // artificially alive here, but there is no real reason to do it:
90 // after all, by the end of block #0, @1 and @2 should be completely
91 // interchangeable, and there is no reason for us to artificially make
92 // @1 more important.
93 //
94 // An important point to consider to understand this separation is
95 // that we should think of the local heap as follow: we have a
96 // bunch of nodes that are pointers to "allocations" that live
97 // someplace on the heap, and those allocations can have pointers in
98 // between themselves as well. We shouldn't care about whatever
99 // names we give to the allocations ; what matters when
100 // comparing/merging two heaps is the isomorphism/comparison between
101 // the allocation graphs as seen by the nodes.
102 //
103 // For instance, in the following graph:
104 //
105 // Block #0
106 //  0: NewObject({})
107 //  -: Branch(#1, #2)
108 //
109 // Block #1
110 //  1: NewObject({})
111 //  -: PutByOffset(@0, @1, x)
112 //  -: PutStructure(@0, {x:0})
113 //  -: Jump(#3)
114 //
115 // Block #2
116 //  2: NewObject({})
117 //  -: PutByOffset(@2, undefined, x)
118 //  -: PutStructure(@2, {x:0})
119 //  -: PutByOffset(@0, @2, x)
120 //  -: PutStructure(@0, {x:0})
121 //  -: Jump(#3)
122 //
123 // Block #3
124 //  -: Return(@0)
125 //
126 // we should think of the heaps at tail of blocks #1 and #2 as being
127 // exactly the same, even though one has @0.x pointing to @1 and the
128 // other has @0.x pointing to @2, because in essence this should not
129 // be different from the graph where we hoisted @1 and @2 into a
130 // single allocation in block #0. We currently will not handle this
131 // case, because we merge allocations based on the node they are
132 // coming from, but this is only a technicality for the sake of
133 // simplicity that shouldn't hide the deeper idea outlined here.
134
135 class Allocation {
136 public:
137     // We use Escaped as a special allocation kind because when we
138     // decide to sink an allocation, we still need to keep track of it
139     // once it is escaped if it still has pointers to it in order to
140     // replace any use of those pointers by the corresponding
141     // materialization
142     enum class Kind { Escaped, Object, Activation, Function, GeneratorFunction, AsyncFunction };
143
144     explicit Allocation(Node* identifier = nullptr, Kind kind = Kind::Escaped)
145         : m_identifier(identifier)
146         , m_kind(kind)
147     {
148     }
149
150
151     const HashMap<PromotedLocationDescriptor, Node*>& fields() const
152     {
153         return m_fields;
154     }
155
156     Node* get(PromotedLocationDescriptor descriptor)
157     {
158         return m_fields.get(descriptor);
159     }
160
161     Allocation& set(PromotedLocationDescriptor descriptor, Node* value)
162     {
163         // Pointing to anything else than an unescaped local
164         // allocation is represented by simply not having the
165         // field
166         if (value)
167             m_fields.set(descriptor, value);
168         else
169             m_fields.remove(descriptor);
170         return *this;
171     }
172
173     void remove(PromotedLocationDescriptor descriptor)
174     {
175         set(descriptor, nullptr);
176     }
177
178     bool hasStructures() const
179     {
180         switch (kind()) {
181         case Kind::Object:
182             return true;
183
184         default:
185             return false;
186         }
187     }
188
189     Allocation& setStructures(const StructureSet& structures)
190     {
191         ASSERT(hasStructures() && !structures.isEmpty());
192         m_structures = structures;
193         return *this;
194     }
195
196     Allocation& mergeStructures(const StructureSet& structures)
197     {
198         ASSERT(hasStructures() || structures.isEmpty());
199         m_structures.merge(structures);
200         return *this;
201     }
202
203     Allocation& filterStructures(const StructureSet& structures)
204     {
205         ASSERT(hasStructures());
206         m_structures.filter(structures);
207         return *this;
208     }
209
210     const StructureSet& structures() const
211     {
212         return m_structures;
213     }
214
215     Node* identifier() const { return m_identifier; }
216
217     Kind kind() const { return m_kind; }
218
219     bool isEscapedAllocation() const
220     {
221         return kind() == Kind::Escaped;
222     }
223
224     bool isObjectAllocation() const
225     {
226         return m_kind == Kind::Object;
227     }
228
229     bool isActivationAllocation() const
230     {
231         return m_kind == Kind::Activation;
232     }
233
234     bool isFunctionAllocation() const
235     {
236         return m_kind == Kind::Function || m_kind == Kind::GeneratorFunction || m_kind == Kind::AsyncFunction;
237     }
238
239     bool operator==(const Allocation& other) const
240     {
241         return m_identifier == other.m_identifier
242             && m_kind == other.m_kind
243             && m_fields == other.m_fields
244             && m_structures == other.m_structures;
245     }
246
247     bool operator!=(const Allocation& other) const
248     {
249         return !(*this == other);
250     }
251
252     void dump(PrintStream& out) const
253     {
254         dumpInContext(out, nullptr);
255     }
256
257     void dumpInContext(PrintStream& out, DumpContext* context) const
258     {
259         switch (m_kind) {
260         case Kind::Escaped:
261             out.print("Escaped");
262             break;
263
264         case Kind::Object:
265             out.print("Object");
266             break;
267
268         case Kind::Function:
269             out.print("Function");
270             break;
271
272         case Kind::GeneratorFunction:
273             out.print("GeneratorFunction");
274             break;
275
276         case Kind::AsyncFunction:
277             out.print("AsyncFunction");
278             break;
279
280         case Kind::Activation:
281             out.print("Activation");
282             break;
283         }
284         out.print("Allocation(");
285         if (!m_structures.isEmpty())
286             out.print(inContext(m_structures, context));
287         if (!m_fields.isEmpty()) {
288             if (!m_structures.isEmpty())
289                 out.print(", ");
290             out.print(mapDump(m_fields, " => #", ", "));
291         }
292         out.print(")");
293     }
294
295 private:
296     Node* m_identifier; // This is the actual node that created the allocation
297     Kind m_kind;
298     HashMap<PromotedLocationDescriptor, Node*> m_fields;
299     StructureSet m_structures;
300 };
301
302 class LocalHeap {
303 public:
304     Allocation& newAllocation(Node* node, Allocation::Kind kind)
305     {
306         ASSERT(!m_pointers.contains(node) && !isAllocation(node));
307         m_pointers.add(node, node);
308         return m_allocations.set(node, Allocation(node, kind)).iterator->value;
309     }
310
311     bool isAllocation(Node* identifier) const
312     {
313         return m_allocations.contains(identifier);
314     }
315
316     // Note that this is fundamentally different from
317     // onlyLocalAllocation() below. getAllocation() takes as argument
318     // a node-as-identifier, that is, an allocation node. This
319     // allocation node doesn't have to be alive; it may only be
320     // pointed to by other nodes or allocation fields.
321     // For instance, in the following graph:
322     //
323     // Block #0
324     //  0: NewObject({})
325     //  1: NewObject({})
326     //  -: PutByOffset(@0, @1, x)
327     //  -: PutStructure(@0, {x:0})
328     //  2: GetByOffset(@0, x)
329     //  -: Jump(#1)
330     //
331     // Block #1
332     //  -: Return(@2)
333     //
334     // At head of block #1, the only reachable allocation is #@1,
335     // which can be reached through node @2. Thus, getAllocation(#@1)
336     // contains the appropriate metadata for this allocation, but
337     // onlyLocalAllocation(@1) is null, as @1 is no longer a pointer
338     // to #@1 (since it is dead). Conversely, onlyLocalAllocation(@2)
339     // is the same as getAllocation(#@1), while getAllocation(#@2)
340     // does not make sense since @2 is not an allocation node.
341     //
342     // This is meant to be used when the node is already known to be
343     // an identifier (i.e. an allocation) - probably because it was
344     // found as value of a field or pointer in the current heap, or
345     // was the result of a call to follow(). In any other cases (such
346     // as when doing anything while traversing the graph), the
347     // appropriate function to call is probably onlyLocalAllocation.
348     Allocation& getAllocation(Node* identifier)
349     {
350         auto iter = m_allocations.find(identifier);
351         ASSERT(iter != m_allocations.end());
352         return iter->value;
353     }
354
355     void newPointer(Node* node, Node* identifier)
356     {
357         ASSERT(!m_allocations.contains(node) && !m_pointers.contains(node));
358         ASSERT(isAllocation(identifier));
359         m_pointers.add(node, identifier);
360     }
361
362     // follow solves the points-to problem. Given a live node, which
363     // may be either an allocation itself or a heap read (e.g. a
364     // GetByOffset node), it returns the corresponding allocation
365     // node, if there is one. If the argument node is neither an
366     // allocation or a heap read, or may point to different nodes,
367     // nullptr will be returned. Note that a node that points to
368     // different nodes can never point to an unescaped local
369     // allocation.
370     Node* follow(Node* node) const
371     {
372         auto iter = m_pointers.find(node);
373         ASSERT(iter == m_pointers.end() || m_allocations.contains(iter->value));
374         return iter == m_pointers.end() ? nullptr : iter->value;
375     }
376
377     Node* follow(PromotedHeapLocation location) const
378     {
379         const Allocation& base = m_allocations.find(location.base())->value;
380         auto iter = base.fields().find(location.descriptor());
381
382         if (iter == base.fields().end())
383             return nullptr;
384
385         return iter->value;
386     }
387
388     // onlyLocalAllocation find the corresponding allocation metadata
389     // for any live node. onlyLocalAllocation(node) is essentially
390     // getAllocation(follow(node)), with appropriate null handling.
391     Allocation* onlyLocalAllocation(Node* node)
392     {
393         Node* identifier = follow(node);
394         if (!identifier)
395             return nullptr;
396
397         return &getAllocation(identifier);
398     }
399
400     Allocation* onlyLocalAllocation(PromotedHeapLocation location)
401     {
402         Node* identifier = follow(location);
403         if (!identifier)
404             return nullptr;
405
406         return &getAllocation(identifier);
407     }
408
409     // This allows us to store the escapees only when necessary. If
410     // set, the current escapees can be retrieved at any time using
411     // takeEscapees(), which will clear the cached set of escapees;
412     // otherwise the heap won't remember escaping allocations.
413     void setWantEscapees()
414     {
415         m_wantEscapees = true;
416     }
417
418     HashMap<Node*, Allocation> takeEscapees()
419     {
420         return WTFMove(m_escapees);
421     }
422
423     void escape(Node* node)
424     {
425         Node* identifier = follow(node);
426         if (!identifier)
427             return;
428
429         escapeAllocation(identifier);
430     }
431
432     void merge(const LocalHeap& other)
433     {
434         assertIsValid();
435         other.assertIsValid();
436         ASSERT(!m_wantEscapees);
437
438         if (!reached()) {
439             ASSERT(other.reached());
440             *this = other;
441             return;
442         }
443
444         HashSet<Node*> toEscape;
445
446         for (auto& allocationEntry : other.m_allocations)
447             m_allocations.add(allocationEntry.key, allocationEntry.value);
448         for (auto& allocationEntry : m_allocations) {
449             auto allocationIter = other.m_allocations.find(allocationEntry.key);
450
451             // If we have it and they don't, it died for them but we
452             // are keeping it alive from another field somewhere.
453             // There is nothing to do - we will be escaped
454             // automatically when we handle that other field.
455             // This will also happen for allocation that we have and
456             // they don't, and all of those will get pruned.
457             if (allocationIter == other.m_allocations.end())
458                 continue;
459
460             if (allocationEntry.value.kind() != allocationIter->value.kind()) {
461                 toEscape.add(allocationEntry.key);
462                 for (const auto& fieldEntry : allocationIter->value.fields())
463                     toEscape.add(fieldEntry.value);
464             } else {
465                 mergePointerSets(
466                     allocationEntry.value.fields(), allocationIter->value.fields(),
467                     [&] (Node* identifier) {
468                         toEscape.add(identifier);
469                     },
470                     [&] (PromotedLocationDescriptor field) {
471                         allocationEntry.value.remove(field);
472                     });
473                 allocationEntry.value.mergeStructures(allocationIter->value.structures());
474             }
475         }
476
477         mergePointerSets(m_pointers, other.m_pointers,
478             [&] (Node* identifier) {
479                 toEscape.add(identifier);
480             },
481             [&] (Node* field) {
482                 m_pointers.remove(field);
483             });
484
485         for (Node* identifier : toEscape)
486             escapeAllocation(identifier);
487
488         if (!ASSERT_DISABLED) {
489             for (const auto& entry : m_allocations)
490                 ASSERT_UNUSED(entry, entry.value.isEscapedAllocation() || other.m_allocations.contains(entry.key));
491         }
492
493         // If there is no remaining pointer to an allocation, we can
494         // remove it. This should only happen for escaped allocations,
495         // because we only merge liveness-pruned heaps in the first
496         // place.
497         prune();
498
499         assertIsValid();
500     }
501
502     void pruneByLiveness(const HashSet<Node*>& live)
503     {
504         Vector<Node*> toRemove;
505         for (const auto& entry : m_pointers) {
506             if (!live.contains(entry.key))
507                 toRemove.append(entry.key);
508         }
509         for (Node* node : toRemove)
510             m_pointers.remove(node);
511
512         prune();
513     }
514
515     void assertIsValid() const
516     {
517         if (ASSERT_DISABLED)
518             return;
519
520         // Pointers should point to an actual allocation
521         for (const auto& entry : m_pointers) {
522             ASSERT_UNUSED(entry, entry.value);
523             ASSERT(m_allocations.contains(entry.value));
524         }
525
526         for (const auto& allocationEntry : m_allocations) {
527             // Fields should point to an actual allocation
528             for (const auto& fieldEntry : allocationEntry.value.fields()) {
529                 ASSERT_UNUSED(fieldEntry, fieldEntry.value);
530                 ASSERT(m_allocations.contains(fieldEntry.value));
531             }
532         }
533     }
534
535     bool operator==(const LocalHeap& other) const
536     {
537         assertIsValid();
538         other.assertIsValid();
539         return m_allocations == other.m_allocations
540             && m_pointers == other.m_pointers;
541     }
542
543     bool operator!=(const LocalHeap& other) const
544     {
545         return !(*this == other);
546     }
547
548     const HashMap<Node*, Allocation>& allocations() const
549     {
550         return m_allocations;
551     }
552
553     const HashMap<Node*, Node*>& pointers() const
554     {
555         return m_pointers;
556     }
557
558     void dump(PrintStream& out) const
559     {
560         out.print("  Allocations:\n");
561         for (const auto& entry : m_allocations)
562             out.print("    #", entry.key, ": ", entry.value, "\n");
563         out.print("  Pointers:\n");
564         for (const auto& entry : m_pointers)
565             out.print("    ", entry.key, " => #", entry.value, "\n");
566     }
567
568     bool reached() const
569     {
570         return m_reached;
571     }
572
573     void setReached()
574     {
575         m_reached = true;
576     }
577
578 private:
579     // When we merge two heaps, we escape all fields of allocations,
580     // unless they point to the same thing in both heaps.
581     // The reason for this is that it allows us not to do extra work
582     // for diamond graphs where we would otherwise have to check
583     // whether we have a single definition or not, which would be
584     // cumbersome.
585     //
586     // Note that we should try to unify nodes even when they are not
587     // from the same allocation; for instance we should be able to
588     // completely eliminate all allocations from the following graph:
589     //
590     // Block #0
591     //  0: NewObject({})
592     //  -: Branch(#1, #2)
593     //
594     // Block #1
595     //  1: NewObject({})
596     //  -: PutByOffset(@1, "left", val)
597     //  -: PutStructure(@1, {val:0})
598     //  -: PutByOffset(@0, @1, x)
599     //  -: PutStructure(@0, {x:0})
600     //  -: Jump(#3)
601     //
602     // Block #2
603     //  2: NewObject({})
604     //  -: PutByOffset(@2, "right", val)
605     //  -: PutStructure(@2, {val:0})
606     //  -: PutByOffset(@0, @2, x)
607     //  -: PutStructure(@0, {x:0})
608     //  -: Jump(#3)
609     //
610     // Block #3:
611     //  3: GetByOffset(@0, x)
612     //  4: GetByOffset(@3, val)
613     //  -: Return(@4)
614     template<typename Key, typename EscapeFunctor, typename RemoveFunctor>
615     void mergePointerSets(
616         const HashMap<Key, Node*>& my, const HashMap<Key, Node*>& their,
617         const EscapeFunctor& escape, const RemoveFunctor& remove)
618     {
619         Vector<Key> toRemove;
620         for (const auto& entry : my) {
621             auto iter = their.find(entry.key);
622             if (iter == their.end()) {
623                 toRemove.append(entry.key);
624                 escape(entry.value);
625             } else if (iter->value != entry.value) {
626                 toRemove.append(entry.key);
627                 escape(entry.value);
628                 escape(iter->value);
629             }
630         }
631         for (const auto& entry : their) {
632             if (my.contains(entry.key))
633                 continue;
634             escape(entry.value);
635         }
636         for (Key key : toRemove)
637             remove(key);
638     }
639
640     void escapeAllocation(Node* identifier)
641     {
642         Allocation& allocation = getAllocation(identifier);
643         if (allocation.isEscapedAllocation())
644             return;
645
646         Allocation unescaped = WTFMove(allocation);
647         allocation = Allocation(unescaped.identifier(), Allocation::Kind::Escaped);
648
649         for (const auto& entry : unescaped.fields())
650             escapeAllocation(entry.value);
651
652         if (m_wantEscapees)
653             m_escapees.add(unescaped.identifier(), WTFMove(unescaped));
654     }
655
656     void prune()
657     {
658         HashSet<Node*> reachable;
659         for (const auto& entry : m_pointers)
660             reachable.add(entry.value);
661
662         // Repeatedly mark as reachable allocations in fields of other
663         // reachable allocations
664         {
665             Vector<Node*> worklist;
666             worklist.appendRange(reachable.begin(), reachable.end());
667
668             while (!worklist.isEmpty()) {
669                 Node* identifier = worklist.takeLast();
670                 Allocation& allocation = m_allocations.find(identifier)->value;
671                 for (const auto& entry : allocation.fields()) {
672                     if (reachable.add(entry.value).isNewEntry)
673                         worklist.append(entry.value);
674                 }
675             }
676         }
677
678         // Remove unreachable allocations
679         {
680             Vector<Node*> toRemove;
681             for (const auto& entry : m_allocations) {
682                 if (!reachable.contains(entry.key))
683                     toRemove.append(entry.key);
684             }
685             for (Node* identifier : toRemove)
686                 m_allocations.remove(identifier);
687         }
688     }
689
690     bool m_reached = false;
691     HashMap<Node*, Node*> m_pointers;
692     HashMap<Node*, Allocation> m_allocations;
693
694     bool m_wantEscapees = false;
695     HashMap<Node*, Allocation> m_escapees;
696 };
697
698 class ObjectAllocationSinkingPhase : public Phase {
699 public:
700     ObjectAllocationSinkingPhase(Graph& graph)
701         : Phase(graph, "object allocation elimination")
702         , m_pointerSSA(graph)
703         , m_allocationSSA(graph)
704         , m_insertionSet(graph)
705     {
706     }
707
708     bool run()
709     {
710         ASSERT(m_graph.m_form == SSA);
711         ASSERT(m_graph.m_fixpointState == FixpointNotConverged);
712
713         if (!performSinking())
714             return false;
715
716         if (verbose) {
717             dataLog("Graph after elimination:\n");
718             m_graph.dump();
719         }
720
721         return true;
722     }
723
724 private:
725     bool performSinking()
726     {
727         m_graph.computeRefCounts();
728         m_graph.initializeNodeOwners();
729         m_graph.ensureDominators();
730         performLivenessAnalysis(m_graph);
731         performOSRAvailabilityAnalysis(m_graph);
732         m_combinedLiveness = CombinedLiveness(m_graph);
733
734         CString graphBeforeSinking;
735         if (Options::verboseValidationFailure() && Options::validateGraphAtEachPhase()) {
736             StringPrintStream out;
737             m_graph.dump(out);
738             graphBeforeSinking = out.toCString();
739         }
740
741         if (verbose) {
742             dataLog("Graph before elimination:\n");
743             m_graph.dump();
744         }
745
746         performAnalysis();
747
748         if (!determineSinkCandidates())
749             return false;
750
751         if (verbose) {
752             for (BasicBlock* block : m_graph.blocksInNaturalOrder()) {
753                 dataLog("Heap at head of ", *block, ": \n", m_heapAtHead[block]);
754                 dataLog("Heap at tail of ", *block, ": \n", m_heapAtTail[block]);
755             }
756         }
757
758         promoteLocalHeap();
759
760         if (Options::validateGraphAtEachPhase())
761             DFG::validate(m_graph, DumpGraph, graphBeforeSinking);
762         return true;
763     }
764
765     void performAnalysis()
766     {
767         m_heapAtHead = BlockMap<LocalHeap>(m_graph);
768         m_heapAtTail = BlockMap<LocalHeap>(m_graph);
769
770         bool changed;
771         do {
772             if (verbose)
773                 dataLog("Doing iteration of escape analysis.\n");
774             changed = false;
775
776             for (BasicBlock* block : m_graph.blocksInPreOrder()) {
777                 m_heapAtHead[block].setReached();
778                 m_heap = m_heapAtHead[block];
779
780                 for (Node* node : *block) {
781                     handleNode(
782                         node,
783                         [] (PromotedHeapLocation, LazyNode) { },
784                         [&] (PromotedHeapLocation) -> Node* {
785                             return nullptr;
786                         });
787                 }
788
789                 if (m_heap == m_heapAtTail[block])
790                     continue;
791
792                 m_heapAtTail[block] = m_heap;
793                 changed = true;
794
795                 m_heap.assertIsValid();
796
797                 // We keep only pointers that are live, and only
798                 // allocations that are either live, pointed to by a
799                 // live pointer, or (recursively) stored in a field of
800                 // a live allocation.
801                 //
802                 // This means we can accidentaly leak non-dominating
803                 // nodes into the successor. However, due to the
804                 // non-dominance property, we are guaranteed that the
805                 // successor has at least one predecessor that is not
806                 // dominated either: this means any reference to a
807                 // non-dominating allocation in the successor will
808                 // trigger an escape and get pruned during the merge.
809                 m_heap.pruneByLiveness(m_combinedLiveness.liveAtTail[block]);
810
811                 for (BasicBlock* successorBlock : block->successors())
812                     m_heapAtHead[successorBlock].merge(m_heap);
813             }
814         } while (changed);
815     }
816
817     template<typename WriteFunctor, typename ResolveFunctor>
818     void handleNode(
819         Node* node,
820         const WriteFunctor& heapWrite,
821         const ResolveFunctor& heapResolve)
822     {
823         m_heap.assertIsValid();
824         ASSERT(m_heap.takeEscapees().isEmpty());
825
826         Allocation* target = nullptr;
827         HashMap<PromotedLocationDescriptor, LazyNode> writes;
828         PromotedLocationDescriptor exactRead;
829
830         switch (node->op()) {
831         case NewObject:
832             target = &m_heap.newAllocation(node, Allocation::Kind::Object);
833             target->setStructures(node->structure());
834             writes.add(
835                 StructurePLoc, LazyNode(m_graph.freeze(node->structure())));
836             break;
837
838         case NewFunction:
839         case NewGeneratorFunction:
840         case NewAsyncFunction: {
841             if (isStillValid(node->castOperand<FunctionExecutable*>()->singletonFunction())) {
842                 m_heap.escape(node->child1().node());
843                 break;
844             }
845
846             if (node->op() == NewGeneratorFunction)
847                 target = &m_heap.newAllocation(node, Allocation::Kind::GeneratorFunction);
848             else if (node->op() == NewAsyncFunction)
849                 target = &m_heap.newAllocation(node, Allocation::Kind::AsyncFunction);
850             else
851                 target = &m_heap.newAllocation(node, Allocation::Kind::Function);
852
853             writes.add(FunctionExecutablePLoc, LazyNode(node->cellOperand()));
854             writes.add(FunctionActivationPLoc, LazyNode(node->child1().node()));
855             break;
856         }
857
858         case CreateActivation: {
859             if (isStillValid(node->castOperand<SymbolTable*>()->singletonScope())) {
860                 m_heap.escape(node->child1().node());
861                 break;
862             }
863             target = &m_heap.newAllocation(node, Allocation::Kind::Activation);
864             writes.add(ActivationSymbolTablePLoc, LazyNode(node->cellOperand()));
865             writes.add(ActivationScopePLoc, LazyNode(node->child1().node()));
866             {
867                 SymbolTable* symbolTable = node->castOperand<SymbolTable*>();
868                 ConcurrentJSLocker locker(symbolTable->m_lock);
869                 LazyNode initialValue(m_graph.freeze(node->initializationValueForActivation()));
870                 for (auto iter = symbolTable->begin(locker), end = symbolTable->end(locker); iter != end; ++iter) {
871                     writes.add(
872                         PromotedLocationDescriptor(ClosureVarPLoc, iter->value.scopeOffset().offset()),
873                         initialValue);
874                 }
875             }
876             break;
877         }
878
879         case PutStructure:
880             target = m_heap.onlyLocalAllocation(node->child1().node());
881             if (target && target->isObjectAllocation()) {
882                 writes.add(StructurePLoc, LazyNode(m_graph.freeze(JSValue(node->transition()->next))));
883                 target->setStructures(node->transition()->next);
884             } else
885                 m_heap.escape(node->child1().node());
886             break;
887
888         case CheckStructure: {
889             Allocation* allocation = m_heap.onlyLocalAllocation(node->child1().node());
890             if (allocation && allocation->isObjectAllocation()) {
891                 allocation->filterStructures(node->structureSet());
892                 if (Node* value = heapResolve(PromotedHeapLocation(allocation->identifier(), StructurePLoc)))
893                     node->convertToCheckStructureImmediate(value);
894             } else
895                 m_heap.escape(node->child1().node());
896             break;
897         }
898
899         case GetByOffset:
900         case GetGetterSetterByOffset:
901             target = m_heap.onlyLocalAllocation(node->child2().node());
902             if (target && target->isObjectAllocation()) {
903                 unsigned identifierNumber = node->storageAccessData().identifierNumber;
904                 exactRead = PromotedLocationDescriptor(NamedPropertyPLoc, identifierNumber);
905             } else {
906                 m_heap.escape(node->child1().node());
907                 m_heap.escape(node->child2().node());
908             }
909             break;
910
911         case MultiGetByOffset: {
912             Allocation* allocation = m_heap.onlyLocalAllocation(node->child1().node());
913             if (allocation && allocation->isObjectAllocation()) {
914                 MultiGetByOffsetData& data = node->multiGetByOffsetData();
915                 StructureSet validStructures;
916                 bool hasInvalidStructures = false;
917                 for (const auto& multiGetByOffsetCase : data.cases) {
918                     if (!allocation->structures().overlaps(multiGetByOffsetCase.set()))
919                         continue;
920
921                     switch (multiGetByOffsetCase.method().kind()) {
922                     case GetByOffsetMethod::LoadFromPrototype: // We need to escape those
923                     case GetByOffsetMethod::Constant: // We don't really have a way of expressing this
924                         hasInvalidStructures = true;
925                         break;
926
927                     case GetByOffsetMethod::Load: // We're good
928                         validStructures.merge(multiGetByOffsetCase.set());
929                         break;
930
931                     default:
932                         RELEASE_ASSERT_NOT_REACHED();
933                     }
934                 }
935                 if (hasInvalidStructures) {
936                     m_heap.escape(node->child1().node());
937                     break;
938                 }
939                 unsigned identifierNumber = data.identifierNumber;
940                 PromotedHeapLocation location(NamedPropertyPLoc, allocation->identifier(), identifierNumber);
941                 if (Node* value = heapResolve(location)) {
942                     if (allocation->structures().isSubsetOf(validStructures))
943                         node->replaceWith(value);
944                     else {
945                         Node* structure = heapResolve(PromotedHeapLocation(allocation->identifier(), StructurePLoc));
946                         ASSERT(structure);
947                         allocation->filterStructures(validStructures);
948                         node->convertToCheckStructure(m_graph.addStructureSet(allocation->structures()));
949                         node->convertToCheckStructureImmediate(structure);
950                         node->setReplacement(value);
951                     }
952                 } else if (!allocation->structures().isSubsetOf(validStructures)) {
953                     // Even though we don't need the result here, we still need
954                     // to make the call to tell our caller that we could need
955                     // the StructurePLoc.
956                     // The reason for this is that when we decide not to sink a
957                     // node, we will still lower any read to its fields before
958                     // it escapes (which are usually reads across a function
959                     // call that DFGClobberize can't handle) - but we only do
960                     // this for PromotedHeapLocations that we have seen read
961                     // during the analysis!
962                     heapResolve(PromotedHeapLocation(allocation->identifier(), StructurePLoc));
963                     allocation->filterStructures(validStructures);
964                 }
965                 Node* identifier = allocation->get(location.descriptor());
966                 if (identifier)
967                     m_heap.newPointer(node, identifier);
968             } else
969                 m_heap.escape(node->child1().node());
970             break;
971         }
972
973         case PutByOffset:
974             target = m_heap.onlyLocalAllocation(node->child2().node());
975             if (target && target->isObjectAllocation()) {
976                 unsigned identifierNumber = node->storageAccessData().identifierNumber;
977                 writes.add(
978                     PromotedLocationDescriptor(NamedPropertyPLoc, identifierNumber),
979                     LazyNode(node->child3().node()));
980             } else {
981                 m_heap.escape(node->child1().node());
982                 m_heap.escape(node->child2().node());
983                 m_heap.escape(node->child3().node());
984             }
985             break;
986
987         case GetClosureVar:
988             target = m_heap.onlyLocalAllocation(node->child1().node());
989             if (target && target->isActivationAllocation()) {
990                 exactRead =
991                     PromotedLocationDescriptor(ClosureVarPLoc, node->scopeOffset().offset());
992             } else
993                 m_heap.escape(node->child1().node());
994             break;
995
996         case PutClosureVar:
997             target = m_heap.onlyLocalAllocation(node->child1().node());
998             if (target && target->isActivationAllocation()) {
999                 writes.add(
1000                     PromotedLocationDescriptor(ClosureVarPLoc, node->scopeOffset().offset()),
1001                     LazyNode(node->child2().node()));
1002             } else {
1003                 m_heap.escape(node->child1().node());
1004                 m_heap.escape(node->child2().node());
1005             }
1006             break;
1007
1008         case SkipScope:
1009             target = m_heap.onlyLocalAllocation(node->child1().node());
1010             if (target && target->isActivationAllocation())
1011                 exactRead = ActivationScopePLoc;
1012             else
1013                 m_heap.escape(node->child1().node());
1014             break;
1015
1016         case GetExecutable:
1017             target = m_heap.onlyLocalAllocation(node->child1().node());
1018             if (target && target->isFunctionAllocation())
1019                 exactRead = FunctionExecutablePLoc;
1020             else
1021                 m_heap.escape(node->child1().node());
1022             break;
1023
1024         case GetScope:
1025             target = m_heap.onlyLocalAllocation(node->child1().node());
1026             if (target && target->isFunctionAllocation())
1027                 exactRead = FunctionActivationPLoc;
1028             else
1029                 m_heap.escape(node->child1().node());
1030             break;
1031
1032         case Check:
1033             m_graph.doToChildren(
1034                 node,
1035                 [&] (Edge edge) {
1036                     if (edge.willNotHaveCheck())
1037                         return;
1038
1039                     if (alreadyChecked(edge.useKind(), SpecObject))
1040                         return;
1041
1042                     m_heap.escape(edge.node());
1043                 });
1044             break;
1045
1046         case MovHint:
1047         case PutHint:
1048             // Handled by OSR availability analysis
1049             break;
1050
1051         default:
1052             m_graph.doToChildren(
1053                 node,
1054                 [&] (Edge edge) {
1055                     m_heap.escape(edge.node());
1056                 });
1057             break;
1058         }
1059
1060         if (exactRead) {
1061             ASSERT(target);
1062             ASSERT(writes.isEmpty());
1063             if (Node* value = heapResolve(PromotedHeapLocation(target->identifier(), exactRead))) {
1064                 ASSERT(!value->replacement());
1065                 node->replaceWith(value);
1066             }
1067             Node* identifier = target->get(exactRead);
1068             if (identifier)
1069                 m_heap.newPointer(node, identifier);
1070         }
1071
1072         for (auto entry : writes) {
1073             ASSERT(target);
1074             if (entry.value.isNode())
1075                 target->set(entry.key, m_heap.follow(entry.value.asNode()));
1076             else
1077                 target->remove(entry.key);
1078             heapWrite(PromotedHeapLocation(target->identifier(), entry.key), entry.value);
1079         }
1080
1081         m_heap.assertIsValid();
1082     }
1083
1084     bool determineSinkCandidates()
1085     {
1086         m_sinkCandidates.clear();
1087         m_materializationToEscapee.clear();
1088         m_materializationSiteToMaterializations.clear();
1089         m_materializationSiteToRecoveries.clear();
1090
1091         // Logically we wish to consider every allocation and sink
1092         // it. However, it is probably not profitable to sink an
1093         // allocation that will always escape. So, we only sink an
1094         // allocation if one of the following is true:
1095         //
1096         // 1) There exists a basic block with only backwards outgoing
1097         //    edges (or no outgoing edges) in which the node wasn't
1098         //    materialized. This is meant to catch
1099         //    effectively-infinite loops in which we don't need to
1100         //    have allocated the object.
1101         //
1102         // 2) There exists a basic block at the tail of which the node
1103         //    is dead and not materialized.
1104         //
1105         // 3) The sum of execution counts of the materializations is
1106         //    less than the sum of execution counts of the original
1107         //    node.
1108         //
1109         // We currently implement only rule #2.
1110         // FIXME: Implement the two other rules.
1111         // https://bugs.webkit.org/show_bug.cgi?id=137073 (rule #1)
1112         // https://bugs.webkit.org/show_bug.cgi?id=137074 (rule #3)
1113         //
1114         // However, these rules allow for a sunk object to be put into
1115         // a non-sunk one, which we don't support. We could solve this
1116         // by supporting PutHints on local allocations, making these
1117         // objects only partially correct, and we would need to adapt
1118         // the OSR availability analysis and OSR exit to handle
1119         // this. This would be totally doable, but would create a
1120         // super rare, and thus bug-prone, code path.
1121         // So, instead, we need to implement one of the following
1122         // closure rules:
1123         //
1124         // 1) If we put a sink candidate into a local allocation that
1125         //    is not a sink candidate, change our minds and don't
1126         //    actually sink the sink candidate.
1127         //
1128         // 2) If we put a sink candidate into a local allocation, that
1129         //    allocation becomes a sink candidate as well.
1130         //
1131         // We currently choose to implement closure rule #2.
1132         HashMap<Node*, Vector<Node*>> dependencies;
1133         bool hasUnescapedReads = false;
1134         for (BasicBlock* block : m_graph.blocksInPreOrder()) {
1135             m_heap = m_heapAtHead[block];
1136
1137             for (Node* node : *block) {
1138                 handleNode(
1139                     node,
1140                     [&] (PromotedHeapLocation location, LazyNode value) {
1141                         if (!value.isNode())
1142                             return;
1143
1144                         Allocation* allocation = m_heap.onlyLocalAllocation(value.asNode());
1145                         if (allocation && !allocation->isEscapedAllocation())
1146                             dependencies.add(allocation->identifier(), Vector<Node*>()).iterator->value.append(location.base());
1147                     },
1148                     [&] (PromotedHeapLocation) -> Node* {
1149                         hasUnescapedReads = true;
1150                         return nullptr;
1151                     });
1152             }
1153
1154             // The sink candidates are initially the unescaped
1155             // allocations dying at tail of blocks
1156             HashSet<Node*> allocations;
1157             for (const auto& entry : m_heap.allocations()) {
1158                 if (!entry.value.isEscapedAllocation())
1159                     allocations.add(entry.key);
1160             }
1161
1162             m_heap.pruneByLiveness(m_combinedLiveness.liveAtTail[block]);
1163
1164             for (Node* identifier : allocations) {
1165                 if (!m_heap.isAllocation(identifier))
1166                     m_sinkCandidates.add(identifier);
1167             }
1168         }
1169
1170         // Ensure that the set of sink candidates is closed for put operations
1171         Vector<Node*> worklist;
1172         worklist.appendRange(m_sinkCandidates.begin(), m_sinkCandidates.end());
1173
1174         while (!worklist.isEmpty()) {
1175             for (Node* identifier : dependencies.get(worklist.takeLast())) {
1176                 if (m_sinkCandidates.add(identifier).isNewEntry)
1177                     worklist.append(identifier);
1178             }
1179         }
1180
1181         if (m_sinkCandidates.isEmpty())
1182             return hasUnescapedReads;
1183
1184         if (verbose)
1185             dataLog("Candidates: ", listDump(m_sinkCandidates), "\n");
1186
1187         // Create the materialization nodes
1188         for (BasicBlock* block : m_graph.blocksInNaturalOrder()) {
1189             m_heap = m_heapAtHead[block];
1190             m_heap.setWantEscapees();
1191
1192             for (Node* node : *block) {
1193                 handleNode(
1194                     node,
1195                     [] (PromotedHeapLocation, LazyNode) { },
1196                     [] (PromotedHeapLocation) -> Node* {
1197                         return nullptr;
1198                     });
1199                 auto escapees = m_heap.takeEscapees();
1200                 if (!escapees.isEmpty())
1201                     placeMaterializations(escapees, node);
1202             }
1203
1204             m_heap.pruneByLiveness(m_combinedLiveness.liveAtTail[block]);
1205
1206             {
1207                 HashMap<Node*, Allocation> escapingOnEdge;
1208                 for (const auto& entry : m_heap.allocations()) {
1209                     if (entry.value.isEscapedAllocation())
1210                         continue;
1211
1212                     bool mustEscape = false;
1213                     for (BasicBlock* successorBlock : block->successors()) {
1214                         if (!m_heapAtHead[successorBlock].isAllocation(entry.key)
1215                             || m_heapAtHead[successorBlock].getAllocation(entry.key).isEscapedAllocation())
1216                             mustEscape = true;
1217                     }
1218
1219                     if (mustEscape)
1220                         escapingOnEdge.add(entry.key, entry.value);
1221                 }
1222                 placeMaterializations(WTFMove(escapingOnEdge), block->terminal());
1223             }
1224         }
1225
1226         return hasUnescapedReads || !m_sinkCandidates.isEmpty();
1227     }
1228
1229     void placeMaterializations(HashMap<Node*, Allocation> escapees, Node* where)
1230     {
1231         // We don't create materializations if the escapee is not a
1232         // sink candidate
1233         Vector<Node*> toRemove;
1234         for (const auto& entry : escapees) {
1235             if (!m_sinkCandidates.contains(entry.key))
1236                 toRemove.append(entry.key);
1237         }
1238         for (Node* identifier : toRemove)
1239             escapees.remove(identifier);
1240
1241         if (escapees.isEmpty())
1242             return;
1243
1244         // First collect the hints that will be needed when the node
1245         // we materialize is still stored into other unescaped sink candidates
1246         Vector<PromotedHeapLocation> hints;
1247         for (const auto& entry : m_heap.allocations()) {
1248             if (escapees.contains(entry.key))
1249                 continue;
1250
1251             for (const auto& field : entry.value.fields()) {
1252                 ASSERT(m_sinkCandidates.contains(entry.key) || !escapees.contains(field.value));
1253                 if (escapees.contains(field.value))
1254                     hints.append(PromotedHeapLocation(entry.key, field.key));
1255             }
1256         }
1257
1258         // Now we need to order the materialization. Any order is
1259         // valid (as long as we materialize a node first if it is
1260         // needed for the materialization of another node, e.g. a
1261         // function's activation must be materialized before the
1262         // function itself), but we want to try minimizing the number
1263         // of times we have to place Puts to close cycles after a
1264         // materialization. In other words, we are trying to find the
1265         // minimum number of materializations to remove from the
1266         // materialization graph to make it a DAG, known as the
1267         // (vertex) feedback set problem. Unfortunately, this is a
1268         // NP-hard problem, which we don't want to solve exactly.
1269         //
1270         // Instead, we use a simple greedy procedure, that procedes as
1271         // follow:
1272         //  - While there is at least one node with no outgoing edge
1273         //    amongst the remaining materializations, materialize it
1274         //    first
1275         //
1276         //  - Similarily, while there is at least one node with no
1277         //    incoming edge amongst the remaining materializations,
1278         //    materialize it last.
1279         //
1280         //  - When both previous conditions are false, we have an
1281         //    actual cycle, and we need to pick a node to
1282         //    materialize. We try greedily to remove the "pressure" on
1283         //    the remaining nodes by choosing the node with maximum
1284         //    |incoming edges| * |outgoing edges| as a measure of how
1285         //    "central" to the graph it is. We materialize it first,
1286         //    so that all the recoveries will be Puts of things into
1287         //    it (rather than Puts of the materialization into other
1288         //    objects), which means we will have a single
1289         //    StoreBarrier.
1290
1291
1292         // Compute dependencies between materializations
1293         HashMap<Node*, HashSet<Node*>> dependencies;
1294         HashMap<Node*, HashSet<Node*>> reverseDependencies;
1295         HashMap<Node*, HashSet<Node*>> forMaterialization;
1296         for (const auto& entry : escapees) {
1297             auto& myDependencies = dependencies.add(entry.key, HashSet<Node*>()).iterator->value;
1298             auto& myDependenciesForMaterialization = forMaterialization.add(entry.key, HashSet<Node*>()).iterator->value;
1299             reverseDependencies.add(entry.key, HashSet<Node*>());
1300             for (const auto& field : entry.value.fields()) {
1301                 if (escapees.contains(field.value) && field.value != entry.key) {
1302                     myDependencies.add(field.value);
1303                     reverseDependencies.add(field.value, HashSet<Node*>()).iterator->value.add(entry.key);
1304                     if (field.key.neededForMaterialization())
1305                         myDependenciesForMaterialization.add(field.value);
1306                 }
1307             }
1308         }
1309
1310         // Helper function to update the materialized set and the
1311         // dependencies
1312         HashSet<Node*> materialized;
1313         auto materialize = [&] (Node* identifier) {
1314             materialized.add(identifier);
1315             for (Node* dep : dependencies.get(identifier))
1316                 reverseDependencies.find(dep)->value.remove(identifier);
1317             for (Node* rdep : reverseDependencies.get(identifier)) {
1318                 dependencies.find(rdep)->value.remove(identifier);
1319                 forMaterialization.find(rdep)->value.remove(identifier);
1320             }
1321             dependencies.remove(identifier);
1322             reverseDependencies.remove(identifier);
1323             forMaterialization.remove(identifier);
1324         };
1325
1326         // Nodes without remaining unmaterialized fields will be
1327         // materialized first - amongst the remaining unmaterialized
1328         // nodes
1329         std::list<Allocation> toMaterialize;
1330         auto firstPos = toMaterialize.begin();
1331         auto materializeFirst = [&] (Allocation&& allocation) {
1332             materialize(allocation.identifier());
1333             // We need to insert *after* the current position
1334             if (firstPos != toMaterialize.end())
1335                 ++firstPos;
1336             firstPos = toMaterialize.insert(firstPos, WTFMove(allocation));
1337         };
1338
1339         // Nodes that no other unmaterialized node points to will be
1340         // materialized last - amongst the remaining unmaterialized
1341         // nodes
1342         auto lastPos = toMaterialize.end();
1343         auto materializeLast = [&] (Allocation&& allocation) {
1344             materialize(allocation.identifier());
1345             lastPos = toMaterialize.insert(lastPos, WTFMove(allocation));
1346         };
1347
1348         // These are the promoted locations that contains some of the
1349         // allocations we are currently escaping. If they are a location on
1350         // some other allocation we are currently materializing, we will need
1351         // to "recover" their value with a real put once the corresponding
1352         // allocation is materialized; if they are a location on some other
1353         // not-yet-materialized allocation, we will need a PutHint.
1354         Vector<PromotedHeapLocation> toRecover;
1355
1356         // This loop does the actual cycle breaking
1357         while (!escapees.isEmpty()) {
1358             materialized.clear();
1359
1360             // Materialize nodes that won't require recoveries if we can
1361             for (auto& entry : escapees) {
1362                 if (!forMaterialization.find(entry.key)->value.isEmpty())
1363                     continue;
1364
1365                 if (dependencies.find(entry.key)->value.isEmpty()) {
1366                     materializeFirst(WTFMove(entry.value));
1367                     continue;
1368                 }
1369
1370                 if (reverseDependencies.find(entry.key)->value.isEmpty()) {
1371                     materializeLast(WTFMove(entry.value));
1372                     continue;
1373                 }
1374             }
1375
1376             // We reach this only if there is an actual cycle that needs
1377             // breaking. Because we do not want to solve a NP-hard problem
1378             // here, we just heuristically pick a node and materialize it
1379             // first.
1380             if (materialized.isEmpty()) {
1381                 uint64_t maxEvaluation = 0;
1382                 Allocation* bestAllocation = nullptr;
1383                 for (auto& entry : escapees) {
1384                     if (!forMaterialization.find(entry.key)->value.isEmpty())
1385                         continue;
1386
1387                     uint64_t evaluation =
1388                         static_cast<uint64_t>(dependencies.get(entry.key).size()) * reverseDependencies.get(entry.key).size();
1389                     if (evaluation > maxEvaluation) {
1390                         maxEvaluation = evaluation;
1391                         bestAllocation = &entry.value;
1392                     }
1393                 }
1394                 RELEASE_ASSERT(maxEvaluation > 0);
1395
1396                 materializeFirst(WTFMove(*bestAllocation));
1397             }
1398             RELEASE_ASSERT(!materialized.isEmpty());
1399
1400             for (Node* identifier : materialized)
1401                 escapees.remove(identifier);
1402         }
1403
1404         materialized.clear();
1405
1406         HashSet<Node*> escaped;
1407         for (const Allocation& allocation : toMaterialize)
1408             escaped.add(allocation.identifier());
1409         for (const Allocation& allocation : toMaterialize) {
1410             for (const auto& field : allocation.fields()) {
1411                 if (escaped.contains(field.value) && !materialized.contains(field.value))
1412                     toRecover.append(PromotedHeapLocation(allocation.identifier(), field.key));
1413             }
1414             materialized.add(allocation.identifier());
1415         }
1416
1417         Vector<Node*>& materializations = m_materializationSiteToMaterializations.add(
1418             where, Vector<Node*>()).iterator->value;
1419
1420         for (const Allocation& allocation : toMaterialize) {
1421             Node* materialization = createMaterialization(allocation, where);
1422             materializations.append(materialization);
1423             m_materializationToEscapee.add(materialization, allocation.identifier());
1424         }
1425
1426         if (!toRecover.isEmpty()) {
1427             m_materializationSiteToRecoveries.add(
1428                 where, Vector<PromotedHeapLocation>()).iterator->value.appendVector(toRecover);
1429         }
1430
1431         // The hints need to be after the "real" recoveries so that we
1432         // don't hint not-yet-complete objects
1433         if (!hints.isEmpty()) {
1434             m_materializationSiteToRecoveries.add(
1435                 where, Vector<PromotedHeapLocation>()).iterator->value.appendVector(hints);
1436         }
1437     }
1438
1439     Node* createMaterialization(const Allocation& allocation, Node* where)
1440     {
1441         // FIXME: This is the only place where we actually use the
1442         // fact that an allocation's identifier is indeed the node
1443         // that created the allocation.
1444         switch (allocation.kind()) {
1445         case Allocation::Kind::Object: {
1446             ObjectMaterializationData* data = m_graph.m_objectMaterializationData.add();
1447             StructureSet* set = m_graph.addStructureSet(allocation.structures());
1448
1449             return m_graph.addNode(
1450                 allocation.identifier()->prediction(), Node::VarArg, MaterializeNewObject,
1451                 where->origin.withSemantic(allocation.identifier()->origin.semantic),
1452                 OpInfo(set), OpInfo(data), 0, 0);
1453         }
1454
1455         case Allocation::Kind::AsyncFunction:
1456         case Allocation::Kind::GeneratorFunction:
1457         case Allocation::Kind::Function: {
1458             FrozenValue* executable = allocation.identifier()->cellOperand();
1459             
1460             NodeType nodeType =
1461                 allocation.kind() == Allocation::Kind::GeneratorFunction ? NewGeneratorFunction :
1462                 allocation.kind() == Allocation::Kind::AsyncFunction ? NewAsyncFunction : NewFunction;
1463             
1464             return m_graph.addNode(
1465                 allocation.identifier()->prediction(), nodeType,
1466                 where->origin.withSemantic(
1467                     allocation.identifier()->origin.semantic),
1468                 OpInfo(executable));
1469             break;
1470         }
1471
1472         case Allocation::Kind::Activation: {
1473             ObjectMaterializationData* data = m_graph.m_objectMaterializationData.add();
1474             FrozenValue* symbolTable = allocation.identifier()->cellOperand();
1475
1476             return m_graph.addNode(
1477                 allocation.identifier()->prediction(), Node::VarArg, MaterializeCreateActivation,
1478                 where->origin.withSemantic(
1479                     allocation.identifier()->origin.semantic),
1480                 OpInfo(symbolTable), OpInfo(data), 0, 0);
1481         }
1482
1483         default:
1484             DFG_CRASH(m_graph, allocation.identifier(), "Bad allocation kind");
1485         }
1486     }
1487
1488     void promoteLocalHeap()
1489     {
1490         // Collect the set of heap locations that we will be operating
1491         // over.
1492         HashSet<PromotedHeapLocation> locations;
1493         for (BasicBlock* block : m_graph.blocksInNaturalOrder()) {
1494             m_heap = m_heapAtHead[block];
1495
1496             for (Node* node : *block) {
1497                 handleNode(
1498                     node,
1499                     [&] (PromotedHeapLocation location, LazyNode) {
1500                         // If the location is not on a sink candidate,
1501                         // we only sink it if it is read
1502                         if (m_sinkCandidates.contains(location.base()))
1503                             locations.add(location);
1504                     },
1505                     [&] (PromotedHeapLocation location) -> Node* {
1506                         locations.add(location);
1507                         return nullptr;
1508                     });
1509             }
1510         }
1511
1512         // Figure out which locations belong to which allocations.
1513         m_locationsForAllocation.clear();
1514         for (PromotedHeapLocation location : locations) {
1515             auto result = m_locationsForAllocation.add(
1516                 location.base(),
1517                 Vector<PromotedHeapLocation>());
1518             ASSERT(!result.iterator->value.contains(location));
1519             result.iterator->value.append(location);
1520         }
1521
1522         m_pointerSSA.reset();
1523         m_allocationSSA.reset();
1524
1525         // Collect the set of "variables" that we will be sinking.
1526         m_locationToVariable.clear();
1527         m_nodeToVariable.clear();
1528         Vector<Node*> indexToNode;
1529         Vector<PromotedHeapLocation> indexToLocation;
1530
1531         for (Node* index : m_sinkCandidates) {
1532             SSACalculator::Variable* variable = m_allocationSSA.newVariable();
1533             m_nodeToVariable.add(index, variable);
1534             ASSERT(indexToNode.size() == variable->index());
1535             indexToNode.append(index);
1536         }
1537
1538         for (PromotedHeapLocation location : locations) {
1539             SSACalculator::Variable* variable = m_pointerSSA.newVariable();
1540             m_locationToVariable.add(location, variable);
1541             ASSERT(indexToLocation.size() == variable->index());
1542             indexToLocation.append(location);
1543         }
1544
1545         // We insert all required constants at top of block 0 so that
1546         // they are inserted only once and we don't clutter the graph
1547         // with useless constants everywhere
1548         HashMap<FrozenValue*, Node*> lazyMapping;
1549         if (!m_bottom)
1550             m_bottom = m_insertionSet.insertConstant(0, m_graph.block(0)->at(0)->origin, jsNumber(1927));
1551         for (BasicBlock* block : m_graph.blocksInNaturalOrder()) {
1552             m_heap = m_heapAtHead[block];
1553
1554             for (unsigned nodeIndex = 0; nodeIndex < block->size(); ++nodeIndex) {
1555                 Node* node = block->at(nodeIndex);
1556
1557                 // Some named properties can be added conditionally,
1558                 // and that would necessitate bottoms
1559                 for (PromotedHeapLocation location : m_locationsForAllocation.get(node)) {
1560                     if (location.kind() != NamedPropertyPLoc)
1561                         continue;
1562
1563                     SSACalculator::Variable* variable = m_locationToVariable.get(location);
1564                     m_pointerSSA.newDef(variable, block, m_bottom);
1565                 }
1566
1567                 for (Node* materialization : m_materializationSiteToMaterializations.get(node)) {
1568                     Node* escapee = m_materializationToEscapee.get(materialization);
1569                     m_allocationSSA.newDef(m_nodeToVariable.get(escapee), block, materialization);
1570                 }
1571
1572                 if (m_sinkCandidates.contains(node))
1573                     m_allocationSSA.newDef(m_nodeToVariable.get(node), block, node);
1574
1575                 handleNode(
1576                     node,
1577                     [&] (PromotedHeapLocation location, LazyNode value) {
1578                         if (!locations.contains(location))
1579                             return;
1580
1581                         Node* nodeValue;
1582                         if (value.isNode())
1583                             nodeValue = value.asNode();
1584                         else {
1585                             auto iter = lazyMapping.find(value.asValue());
1586                             if (iter != lazyMapping.end())
1587                                 nodeValue = iter->value;
1588                             else {
1589                                 nodeValue = value.ensureIsNode(
1590                                     m_insertionSet, m_graph.block(0), 0);
1591                                 lazyMapping.add(value.asValue(), nodeValue);
1592                             }
1593                         }
1594
1595                         SSACalculator::Variable* variable = m_locationToVariable.get(location);
1596                         m_pointerSSA.newDef(variable, block, nodeValue);
1597                     },
1598                     [] (PromotedHeapLocation) -> Node* {
1599                         return nullptr;
1600                     });
1601             }
1602         }
1603         m_insertionSet.execute(m_graph.block(0));
1604
1605         // Run the SSA calculators to create Phis
1606         m_pointerSSA.computePhis(
1607             [&] (SSACalculator::Variable* variable, BasicBlock* block) -> Node* {
1608                 PromotedHeapLocation location = indexToLocation[variable->index()];
1609
1610                 // Don't create Phi nodes for fields of dead allocations
1611                 if (!m_heapAtHead[block].isAllocation(location.base()))
1612                     return nullptr;
1613
1614                 // Don't create Phi nodes once we are escaped
1615                 if (m_heapAtHead[block].getAllocation(location.base()).isEscapedAllocation())
1616                     return nullptr;
1617
1618                 // If we point to a single allocation, we will
1619                 // directly use its materialization
1620                 if (m_heapAtHead[block].follow(location))
1621                     return nullptr;
1622
1623                 Node* phiNode = m_graph.addNode(SpecHeapTop, Phi, block->at(0)->origin.withInvalidExit());
1624                 phiNode->mergeFlags(NodeResultJS);
1625                 return phiNode;
1626             });
1627
1628         m_allocationSSA.computePhis(
1629             [&] (SSACalculator::Variable* variable, BasicBlock* block) -> Node* {
1630                 Node* identifier = indexToNode[variable->index()];
1631
1632                 // Don't create Phi nodes for dead allocations
1633                 if (!m_heapAtHead[block].isAllocation(identifier))
1634                     return nullptr;
1635
1636                 // Don't create Phi nodes until we are escaped
1637                 if (!m_heapAtHead[block].getAllocation(identifier).isEscapedAllocation())
1638                     return nullptr;
1639
1640                 Node* phiNode = m_graph.addNode(SpecHeapTop, Phi, block->at(0)->origin.withInvalidExit());
1641                 phiNode->mergeFlags(NodeResultJS);
1642                 return phiNode;
1643             });
1644
1645         // Place Phis in the right places, replace all uses of any load with the appropriate
1646         // value, and create the materialization nodes.
1647         LocalOSRAvailabilityCalculator availabilityCalculator;
1648         m_graph.clearReplacements();
1649         for (BasicBlock* block : m_graph.blocksInPreOrder()) {
1650             m_heap = m_heapAtHead[block];
1651             availabilityCalculator.beginBlock(block);
1652
1653             // These mapping tables are intended to be lazy. If
1654             // something is omitted from the table, it means that
1655             // there haven't been any local stores to the promoted
1656             // heap location (or any local materialization).
1657             m_localMapping.clear();
1658             m_escapeeToMaterialization.clear();
1659
1660             // Insert the Phi functions that we had previously
1661             // created.
1662             for (SSACalculator::Def* phiDef : m_pointerSSA.phisForBlock(block)) {
1663                 SSACalculator::Variable* variable = phiDef->variable();
1664                 m_insertionSet.insert(0, phiDef->value());
1665
1666                 PromotedHeapLocation location = indexToLocation[variable->index()];
1667                 m_localMapping.set(location, phiDef->value());
1668
1669                 if (m_sinkCandidates.contains(location.base())) {
1670                     m_insertionSet.insert(
1671                         0,
1672                         location.createHint(
1673                             m_graph, block->at(0)->origin.withInvalidExit(), phiDef->value()));
1674                 }
1675             }
1676
1677             for (SSACalculator::Def* phiDef : m_allocationSSA.phisForBlock(block)) {
1678                 SSACalculator::Variable* variable = phiDef->variable();
1679                 m_insertionSet.insert(0, phiDef->value());
1680
1681                 Node* identifier = indexToNode[variable->index()];
1682                 m_escapeeToMaterialization.add(identifier, phiDef->value());
1683                 bool canExit = false;
1684                 insertOSRHintsForUpdate(
1685                     0, block->at(0)->origin, canExit,
1686                     availabilityCalculator.m_availability, identifier, phiDef->value());
1687             }
1688
1689             if (verbose) {
1690                 dataLog("Local mapping at ", pointerDump(block), ": ", mapDump(m_localMapping), "\n");
1691                 dataLog("Local materializations at ", pointerDump(block), ": ", mapDump(m_escapeeToMaterialization), "\n");
1692             }
1693
1694             for (unsigned nodeIndex = 0; nodeIndex < block->size(); ++nodeIndex) {
1695                 Node* node = block->at(nodeIndex);
1696                 bool canExit = true;
1697                 bool nextCanExit = node->origin.exitOK;
1698                 for (PromotedHeapLocation location : m_locationsForAllocation.get(node)) {
1699                     if (location.kind() != NamedPropertyPLoc)
1700                         continue;
1701
1702                     m_localMapping.set(location, m_bottom);
1703
1704                     if (m_sinkCandidates.contains(node)) {
1705                         if (verbose)
1706                             dataLog("For sink candidate ", node, " found location ", location, "\n");
1707                         m_insertionSet.insert(
1708                             nodeIndex + 1,
1709                             location.createHint(
1710                                 m_graph, node->origin.takeValidExit(nextCanExit), m_bottom));
1711                     }
1712                 }
1713
1714                 for (Node* materialization : m_materializationSiteToMaterializations.get(node)) {
1715                     materialization->origin.exitOK &= canExit;
1716                     Node* escapee = m_materializationToEscapee.get(materialization);
1717                     populateMaterialization(block, materialization, escapee);
1718                     m_escapeeToMaterialization.set(escapee, materialization);
1719                     m_insertionSet.insert(nodeIndex, materialization);
1720                     if (verbose)
1721                         dataLog("Materializing ", escapee, " => ", materialization, " at ", node, "\n");
1722                 }
1723
1724                 for (PromotedHeapLocation location : m_materializationSiteToRecoveries.get(node))
1725                     m_insertionSet.insert(nodeIndex, createRecovery(block, location, node, canExit));
1726
1727                 // We need to put the OSR hints after the recoveries,
1728                 // because we only want the hints once the object is
1729                 // complete
1730                 for (Node* materialization : m_materializationSiteToMaterializations.get(node)) {
1731                     Node* escapee = m_materializationToEscapee.get(materialization);
1732                     insertOSRHintsForUpdate(
1733                         nodeIndex, node->origin, canExit,
1734                         availabilityCalculator.m_availability, escapee, materialization);
1735                 }
1736
1737                 if (node->origin.exitOK && !canExit) {
1738                     // We indicate that the exit state is fine now. It is OK because we updated the
1739                     // state above. We need to indicate this manually because the validation doesn't
1740                     // have enough information to infer that the exit state is fine.
1741                     m_insertionSet.insertNode(nodeIndex, SpecNone, ExitOK, node->origin);
1742                 }
1743
1744                 if (m_sinkCandidates.contains(node))
1745                     m_escapeeToMaterialization.set(node, node);
1746
1747                 availabilityCalculator.executeNode(node);
1748
1749                 bool desiredNextExitOK = node->origin.exitOK && !clobbersExitState(m_graph, node);
1750
1751                 bool doLower = false;
1752                 handleNode(
1753                     node,
1754                     [&] (PromotedHeapLocation location, LazyNode value) {
1755                         if (!locations.contains(location))
1756                             return;
1757
1758                         Node* nodeValue;
1759                         if (value.isNode())
1760                             nodeValue = value.asNode();
1761                         else
1762                             nodeValue = lazyMapping.get(value.asValue());
1763
1764                         nodeValue = resolve(block, nodeValue);
1765
1766                         m_localMapping.set(location, nodeValue);
1767
1768                         if (!m_sinkCandidates.contains(location.base()))
1769                             return;
1770
1771                         doLower = true;
1772
1773                         if (verbose)
1774                             dataLog("Creating hint with value ", nodeValue, " before ", node, "\n");
1775                         m_insertionSet.insert(
1776                             nodeIndex + 1,
1777                             location.createHint(
1778                                 m_graph, node->origin.takeValidExit(nextCanExit), nodeValue));
1779                     },
1780                     [&] (PromotedHeapLocation location) -> Node* {
1781                         return resolve(block, location);
1782                     });
1783
1784                 if (!nextCanExit && desiredNextExitOK) {
1785                     // We indicate that the exit state is fine now. We need to do this because we
1786                     // emitted hints that appear to invalidate the exit state.
1787                     m_insertionSet.insertNode(nodeIndex + 1, SpecNone, ExitOK, node->origin);
1788                 }
1789
1790                 if (m_sinkCandidates.contains(node) || doLower) {
1791                     switch (node->op()) {
1792                     case NewObject:
1793                         node->convertToPhantomNewObject();
1794                         break;
1795
1796                     case NewFunction:
1797                         node->convertToPhantomNewFunction();
1798                         break;
1799
1800                     case NewGeneratorFunction:
1801                         node->convertToPhantomNewGeneratorFunction();
1802                         break;
1803
1804                     case NewAsyncFunction:
1805                         node->convertToPhantomNewAsyncFunction();
1806                         break;
1807
1808                     case CreateActivation:
1809                         node->convertToPhantomCreateActivation();
1810                         break;
1811
1812                     default:
1813                         node->remove();
1814                         break;
1815                     }
1816                 }
1817
1818                 m_graph.doToChildren(
1819                     node,
1820                     [&] (Edge& edge) {
1821                         edge.setNode(resolve(block, edge.node()));
1822                     });
1823             }
1824
1825             // Gotta drop some Upsilons.
1826             NodeAndIndex terminal = block->findTerminal();
1827             size_t upsilonInsertionPoint = terminal.index;
1828             NodeOrigin upsilonOrigin = terminal.node->origin;
1829             for (BasicBlock* successorBlock : block->successors()) {
1830                 for (SSACalculator::Def* phiDef : m_pointerSSA.phisForBlock(successorBlock)) {
1831                     Node* phiNode = phiDef->value();
1832                     SSACalculator::Variable* variable = phiDef->variable();
1833                     PromotedHeapLocation location = indexToLocation[variable->index()];
1834                     Node* incoming = resolve(block, location);
1835
1836                     m_insertionSet.insertNode(
1837                         upsilonInsertionPoint, SpecNone, Upsilon, upsilonOrigin,
1838                         OpInfo(phiNode), incoming->defaultEdge());
1839                 }
1840
1841                 for (SSACalculator::Def* phiDef : m_allocationSSA.phisForBlock(successorBlock)) {
1842                     Node* phiNode = phiDef->value();
1843                     SSACalculator::Variable* variable = phiDef->variable();
1844                     Node* incoming = getMaterialization(block, indexToNode[variable->index()]);
1845
1846                     m_insertionSet.insertNode(
1847                         upsilonInsertionPoint, SpecNone, Upsilon, upsilonOrigin,
1848                         OpInfo(phiNode), incoming->defaultEdge());
1849                 }
1850             }
1851
1852             m_insertionSet.execute(block);
1853         }
1854     }
1855
1856     Node* resolve(BasicBlock* block, PromotedHeapLocation location)
1857     {
1858         // If we are currently pointing to a single local allocation,
1859         // simply return the associated materialization.
1860         if (Node* identifier = m_heap.follow(location))
1861             return getMaterialization(block, identifier);
1862
1863         if (Node* result = m_localMapping.get(location))
1864             return result;
1865
1866         // This implies that there is no local mapping. Find a non-local mapping.
1867         SSACalculator::Def* def = m_pointerSSA.nonLocalReachingDef(
1868             block, m_locationToVariable.get(location));
1869         ASSERT(def);
1870         ASSERT(def->value());
1871
1872         Node* result = def->value();
1873         if (result->replacement())
1874             result = result->replacement();
1875         ASSERT(!result->replacement());
1876
1877         m_localMapping.add(location, result);
1878         return result;
1879     }
1880
1881     Node* resolve(BasicBlock* block, Node* node)
1882     {
1883         // If we are currently pointing to a single local allocation,
1884         // simply return the associated materialization.
1885         if (Node* identifier = m_heap.follow(node))
1886             return getMaterialization(block, identifier);
1887
1888         if (node->replacement())
1889             node = node->replacement();
1890         ASSERT(!node->replacement());
1891
1892         return node;
1893     }
1894
1895     Node* getMaterialization(BasicBlock* block, Node* identifier)
1896     {
1897         ASSERT(m_heap.isAllocation(identifier));
1898         if (!m_sinkCandidates.contains(identifier))
1899             return identifier;
1900
1901         if (Node* materialization = m_escapeeToMaterialization.get(identifier))
1902             return materialization;
1903
1904         SSACalculator::Def* def = m_allocationSSA.nonLocalReachingDef(
1905             block, m_nodeToVariable.get(identifier));
1906         ASSERT(def && def->value());
1907         m_escapeeToMaterialization.add(identifier, def->value());
1908         ASSERT(!def->value()->replacement());
1909         return def->value();
1910     }
1911
1912     void insertOSRHintsForUpdate(unsigned nodeIndex, NodeOrigin origin, bool& canExit, AvailabilityMap& availability, Node* escapee, Node* materialization)
1913     {
1914         if (verbose) {
1915             dataLog("Inserting OSR hints at ", origin, ":\n");
1916             dataLog("    Escapee: ", escapee, "\n");
1917             dataLog("    Materialization: ", materialization, "\n");
1918             dataLog("    Availability: ", availability, "\n");
1919         }
1920         
1921         // We need to follow() the value in the heap.
1922         // Consider the following graph:
1923         //
1924         // Block #0
1925         //   0: NewObject({})
1926         //   1: NewObject({})
1927         //   -: PutByOffset(@0, @1, x:0)
1928         //   -: PutStructure(@0, {x:0})
1929         //   2: GetByOffset(@0, x:0)
1930         //   -: MovHint(@2, loc1)
1931         //   -: Branch(#1, #2)
1932         //
1933         // Block #1
1934         //   3: Call(f, @1)
1935         //   4: Return(@0)
1936         //
1937         // Block #2
1938         //   -: Return(undefined)
1939         //
1940         // We need to materialize @1 at @3, and when doing so we need
1941         // to insert a MovHint for the materialization into loc1 as
1942         // well.
1943         // In order to do this, we say that we need to insert an
1944         // update hint for any availability whose node resolve()s to
1945         // the materialization.
1946         for (auto entry : availability.m_heap) {
1947             if (!entry.value.hasNode())
1948                 continue;
1949             if (m_heap.follow(entry.value.node()) != escapee)
1950                 continue;
1951
1952             m_insertionSet.insert(
1953                 nodeIndex,
1954                 entry.key.createHint(m_graph, origin.takeValidExit(canExit), materialization));
1955         }
1956
1957         for (unsigned i = availability.m_locals.size(); i--;) {
1958             if (!availability.m_locals[i].hasNode())
1959                 continue;
1960             if (m_heap.follow(availability.m_locals[i].node()) != escapee)
1961                 continue;
1962
1963             int operand = availability.m_locals.operandForIndex(i);
1964             m_insertionSet.insertNode(
1965                 nodeIndex, SpecNone, MovHint, origin.takeValidExit(canExit), OpInfo(operand),
1966                 materialization->defaultEdge());
1967         }
1968     }
1969
1970     void populateMaterialization(BasicBlock* block, Node* node, Node* escapee)
1971     {
1972         Allocation& allocation = m_heap.getAllocation(escapee);
1973         switch (node->op()) {
1974         case MaterializeNewObject: {
1975             ObjectMaterializationData& data = node->objectMaterializationData();
1976             unsigned firstChild = m_graph.m_varArgChildren.size();
1977
1978             Vector<PromotedHeapLocation> locations = m_locationsForAllocation.get(escapee);
1979
1980             PromotedHeapLocation structure(StructurePLoc, allocation.identifier());
1981             ASSERT(locations.contains(structure));
1982
1983             m_graph.m_varArgChildren.append(Edge(resolve(block, structure), KnownCellUse));
1984
1985             for (PromotedHeapLocation location : locations) {
1986                 switch (location.kind()) {
1987                 case StructurePLoc:
1988                     ASSERT(location == structure);
1989                     break;
1990
1991                 case NamedPropertyPLoc: {
1992                     ASSERT(location.base() == allocation.identifier());
1993                     data.m_properties.append(location.descriptor());
1994                     Node* value = resolve(block, location);
1995                     if (m_sinkCandidates.contains(value))
1996                         m_graph.m_varArgChildren.append(m_bottom);
1997                     else
1998                         m_graph.m_varArgChildren.append(value);
1999                     break;
2000                 }
2001
2002                 default:
2003                     DFG_CRASH(m_graph, node, "Bad location kind");
2004                 }
2005             }
2006
2007             node->children = AdjacencyList(
2008                 AdjacencyList::Variable,
2009                 firstChild, m_graph.m_varArgChildren.size() - firstChild);
2010             break;
2011         }
2012
2013         case MaterializeCreateActivation: {
2014             ObjectMaterializationData& data = node->objectMaterializationData();
2015
2016             unsigned firstChild = m_graph.m_varArgChildren.size();
2017
2018             Vector<PromotedHeapLocation> locations = m_locationsForAllocation.get(escapee);
2019
2020             PromotedHeapLocation symbolTable(ActivationSymbolTablePLoc, allocation.identifier());
2021             ASSERT(locations.contains(symbolTable));
2022             ASSERT(node->cellOperand() == resolve(block, symbolTable)->constant());
2023             m_graph.m_varArgChildren.append(Edge(resolve(block, symbolTable), KnownCellUse));
2024
2025             PromotedHeapLocation scope(ActivationScopePLoc, allocation.identifier());
2026             ASSERT(locations.contains(scope));
2027             m_graph.m_varArgChildren.append(Edge(resolve(block, scope), KnownCellUse));
2028
2029             for (PromotedHeapLocation location : locations) {
2030                 switch (location.kind()) {
2031                 case ActivationScopePLoc: {
2032                     ASSERT(location == scope);
2033                     break;
2034                 }
2035
2036                 case ActivationSymbolTablePLoc: {
2037                     ASSERT(location == symbolTable);
2038                     break;
2039                 }
2040
2041                 case ClosureVarPLoc: {
2042                     ASSERT(location.base() == allocation.identifier());
2043                     data.m_properties.append(location.descriptor());
2044                     Node* value = resolve(block, location);
2045                     if (m_sinkCandidates.contains(value))
2046                         m_graph.m_varArgChildren.append(m_bottom);
2047                     else
2048                         m_graph.m_varArgChildren.append(value);
2049                     break;
2050                 }
2051
2052                 default:
2053                     DFG_CRASH(m_graph, node, "Bad location kind");
2054                 }
2055             }
2056
2057             node->children = AdjacencyList(
2058                 AdjacencyList::Variable,
2059                 firstChild, m_graph.m_varArgChildren.size() - firstChild);
2060             break;
2061         }
2062         
2063         case NewFunction:
2064         case NewGeneratorFunction:
2065         case NewAsyncFunction: {
2066             Vector<PromotedHeapLocation> locations = m_locationsForAllocation.get(escapee);
2067             ASSERT(locations.size() == 2);
2068                 
2069             PromotedHeapLocation executable(FunctionExecutablePLoc, allocation.identifier());
2070             ASSERT_UNUSED(executable, locations.contains(executable));
2071                 
2072             PromotedHeapLocation activation(FunctionActivationPLoc, allocation.identifier());
2073             ASSERT(locations.contains(activation));
2074
2075             node->child1() = Edge(resolve(block, activation), KnownCellUse);
2076             break;
2077         }
2078
2079         default:
2080             DFG_CRASH(m_graph, node, "Bad materialize op");
2081         }
2082     }
2083
2084     Node* createRecovery(BasicBlock* block, PromotedHeapLocation location, Node* where, bool& canExit)
2085     {
2086         if (verbose)
2087             dataLog("Recovering ", location, " at ", where, "\n");
2088         ASSERT(location.base()->isPhantomAllocation());
2089         Node* base = getMaterialization(block, location.base());
2090         Node* value = resolve(block, location);
2091
2092         NodeOrigin origin = where->origin.withSemantic(base->origin.semantic);
2093
2094         if (verbose)
2095             dataLog("Base is ", base, " and value is ", value, "\n");
2096
2097         if (base->isPhantomAllocation()) {
2098             return PromotedHeapLocation(base, location.descriptor()).createHint(
2099                 m_graph, origin.takeValidExit(canExit), value);
2100         }
2101
2102         switch (location.kind()) {
2103         case NamedPropertyPLoc: {
2104             Allocation& allocation = m_heap.getAllocation(location.base());
2105
2106             Vector<Structure*> structures;
2107             structures.appendRange(allocation.structures().begin(), allocation.structures().end());
2108             unsigned identifierNumber = location.info();
2109             UniquedStringImpl* uid = m_graph.identifiers()[identifierNumber];
2110
2111             std::sort(
2112                 structures.begin(),
2113                 structures.end(),
2114                 [uid] (Structure *a, Structure* b) -> bool {
2115                     return a->getConcurrently(uid) < b->getConcurrently(uid);
2116                 });
2117
2118             PropertyOffset firstOffset = structures[0]->getConcurrently(uid);
2119
2120             if (firstOffset == structures.last()->getConcurrently(uid)) {
2121                 Node* storage = base;
2122                 // FIXME: When we decide to sink objects with a
2123                 // property storage, we should handle non-inline offsets.
2124                 RELEASE_ASSERT(isInlineOffset(firstOffset));
2125
2126                 StorageAccessData* data = m_graph.m_storageAccessData.add();
2127                 data->offset = firstOffset;
2128                 data->identifierNumber = identifierNumber;
2129
2130                 return m_graph.addNode(
2131                     PutByOffset,
2132                     origin.takeValidExit(canExit),
2133                     OpInfo(data),
2134                     Edge(storage, KnownCellUse),
2135                     Edge(base, KnownCellUse),
2136                     value->defaultEdge());
2137             }
2138
2139             MultiPutByOffsetData* data = m_graph.m_multiPutByOffsetData.add();
2140             data->identifierNumber = identifierNumber;
2141
2142             {
2143                 PropertyOffset currentOffset = firstOffset;
2144                 StructureSet currentSet;
2145                 for (Structure* structure : structures) {
2146                     PropertyOffset offset = structure->getConcurrently(uid);
2147                     if (offset != currentOffset) {
2148                         // Because our analysis treats MultiPutByOffset like an escape, we only have to
2149                         // deal with storing results that would have been previously stored by PutByOffset
2150                         // nodes. Those nodes were guarded by the appropriate type checks. This means that
2151                         // at this point, we can simply trust that the incoming value has the right type
2152                         // for whatever structure we are using.
2153                         data->variants.append(
2154                             PutByIdVariant::replace(currentSet, currentOffset, InferredType::Top));
2155                         currentOffset = offset;
2156                         currentSet.clear();
2157                     }
2158                     currentSet.add(structure);
2159                 }
2160                 data->variants.append(
2161                     PutByIdVariant::replace(currentSet, currentOffset, InferredType::Top));
2162             }
2163
2164             return m_graph.addNode(
2165                 MultiPutByOffset,
2166                 origin.takeValidExit(canExit),
2167                 OpInfo(data),
2168                 Edge(base, KnownCellUse),
2169                 value->defaultEdge());
2170             break;
2171         }
2172
2173         case ClosureVarPLoc: {
2174             return m_graph.addNode(
2175                 PutClosureVar,
2176                 origin.takeValidExit(canExit),
2177                 OpInfo(location.info()),
2178                 Edge(base, KnownCellUse),
2179                 value->defaultEdge());
2180             break;
2181         }
2182
2183         default:
2184             DFG_CRASH(m_graph, base, "Bad location kind");
2185             break;
2186         }
2187     }
2188
2189     // This is a great way of asking value->isStillValid() without having to worry about getting
2190     // different answers. It turns out that this analysis works OK regardless of what this
2191     // returns but breaks badly if this changes its mind for any particular InferredValue. This
2192     // method protects us from that.
2193     bool isStillValid(InferredValue* value)
2194     {
2195         return m_validInferredValues.add(value, value->isStillValid()).iterator->value;
2196     }
2197
2198     SSACalculator m_pointerSSA;
2199     SSACalculator m_allocationSSA;
2200     HashSet<Node*> m_sinkCandidates;
2201     HashMap<PromotedHeapLocation, SSACalculator::Variable*> m_locationToVariable;
2202     HashMap<Node*, SSACalculator::Variable*> m_nodeToVariable;
2203     HashMap<PromotedHeapLocation, Node*> m_localMapping;
2204     HashMap<Node*, Node*> m_escapeeToMaterialization;
2205     InsertionSet m_insertionSet;
2206     CombinedLiveness m_combinedLiveness;
2207
2208     HashMap<InferredValue*, bool> m_validInferredValues;
2209
2210     HashMap<Node*, Node*> m_materializationToEscapee;
2211     HashMap<Node*, Vector<Node*>> m_materializationSiteToMaterializations;
2212     HashMap<Node*, Vector<PromotedHeapLocation>> m_materializationSiteToRecoveries;
2213
2214     HashMap<Node*, Vector<PromotedHeapLocation>> m_locationsForAllocation;
2215
2216     BlockMap<LocalHeap> m_heapAtHead;
2217     BlockMap<LocalHeap> m_heapAtTail;
2218     LocalHeap m_heap;
2219
2220     Node* m_bottom = nullptr;
2221 };
2222
2223 }
2224
2225 bool performObjectAllocationSinking(Graph& graph)
2226 {
2227     return runPhase<ObjectAllocationSinkingPhase>(graph);
2228 }
2229
2230 } } // namespace JSC::DFG
2231
2232 #endif // ENABLE(DFG_JIT)