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