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