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