[ES6] Handle new_generator_func / new_generator_func_exp in DFG / FTL
[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 WTF::move(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 = WTF::move(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(), WTF::move(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 (node->castOperand<FunctionExecutable*>()->singletonFunction()->isStillValid()) {
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 (node->castOperand<SymbolTable*>()->singletonScope()->isStillValid()) {
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(WTF::move(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, WTF::move(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, WTF::move(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(WTF::move(entry.value));
1366                     continue;
1367                 }
1368
1369                 if (reverseDependencies.find(entry.key)->value.isEmpty()) {
1370                     materializeLast(WTF::move(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(WTF::move(*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                     case NewGeneratorFunction:
1794                         node->convertToPhantomNewFunction();
1795                         break;
1796
1797                     case CreateActivation:
1798                         node->convertToPhantomCreateActivation();
1799                         break;
1800
1801                     default:
1802                         node->remove();
1803                         break;
1804                     }
1805                 }
1806
1807                 m_graph.doToChildren(
1808                     node,
1809                     [&] (Edge& edge) {
1810                         edge.setNode(resolve(block, edge.node()));
1811                     });
1812             }
1813
1814             // Gotta drop some Upsilons.
1815             NodeAndIndex terminal = block->findTerminal();
1816             size_t upsilonInsertionPoint = terminal.index;
1817             NodeOrigin upsilonOrigin = terminal.node->origin;
1818             for (BasicBlock* successorBlock : block->successors()) {
1819                 for (SSACalculator::Def* phiDef : m_pointerSSA.phisForBlock(successorBlock)) {
1820                     Node* phiNode = phiDef->value();
1821                     SSACalculator::Variable* variable = phiDef->variable();
1822                     PromotedHeapLocation location = indexToLocation[variable->index()];
1823                     Node* incoming = resolve(block, location);
1824
1825                     m_insertionSet.insertNode(
1826                         upsilonInsertionPoint, SpecNone, Upsilon, upsilonOrigin,
1827                         OpInfo(phiNode), incoming->defaultEdge());
1828                 }
1829
1830                 for (SSACalculator::Def* phiDef : m_allocationSSA.phisForBlock(successorBlock)) {
1831                     Node* phiNode = phiDef->value();
1832                     SSACalculator::Variable* variable = phiDef->variable();
1833                     Node* incoming = getMaterialization(block, indexToNode[variable->index()]);
1834
1835                     m_insertionSet.insertNode(
1836                         upsilonInsertionPoint, SpecNone, Upsilon, upsilonOrigin,
1837                         OpInfo(phiNode), incoming->defaultEdge());
1838                 }
1839             }
1840
1841             m_insertionSet.execute(block);
1842         }
1843     }
1844
1845     Node* resolve(BasicBlock* block, PromotedHeapLocation location)
1846     {
1847         // If we are currently pointing to a single local allocation,
1848         // simply return the associated materialization.
1849         if (Node* identifier = m_heap.follow(location))
1850             return getMaterialization(block, identifier);
1851
1852         if (Node* result = m_localMapping.get(location))
1853             return result;
1854
1855         // This implies that there is no local mapping. Find a non-local mapping.
1856         SSACalculator::Def* def = m_pointerSSA.nonLocalReachingDef(
1857             block, m_locationToVariable.get(location));
1858         ASSERT(def);
1859         ASSERT(def->value());
1860
1861         Node* result = def->value();
1862
1863         ASSERT(!result->replacement());
1864
1865         m_localMapping.add(location, result);
1866         return result;
1867     }
1868
1869     Node* resolve(BasicBlock* block, Node* node)
1870     {
1871         // If we are currently pointing to a single local allocation,
1872         // simply return the associated materialization.
1873         if (Node* identifier = m_heap.follow(node))
1874             return getMaterialization(block, identifier);
1875
1876         if (node->replacement())
1877             node = node->replacement();
1878         ASSERT(!node->replacement());
1879
1880         return node;
1881     }
1882
1883     Node* getMaterialization(BasicBlock* block, Node* identifier)
1884     {
1885         ASSERT(m_heap.isAllocation(identifier));
1886         if (!m_sinkCandidates.contains(identifier))
1887             return identifier;
1888
1889         if (Node* materialization = m_escapeeToMaterialization.get(identifier))
1890             return materialization;
1891
1892         SSACalculator::Def* def = m_allocationSSA.nonLocalReachingDef(
1893             block, m_nodeToVariable.get(identifier));
1894         ASSERT(def && def->value());
1895         m_escapeeToMaterialization.add(identifier, def->value());
1896         ASSERT(!def->value()->replacement());
1897         return def->value();
1898     }
1899
1900     void insertOSRHintsForUpdate(unsigned nodeIndex, NodeOrigin origin, bool& canExit, AvailabilityMap& availability, Node* escapee, Node* materialization)
1901     {
1902         // We need to follow() the value in the heap.
1903         // Consider the following graph:
1904         //
1905         // Block #0
1906         //   0: NewObject({})
1907         //   1: NewObject({})
1908         //   -: PutByOffset(@0, @1, x:0)
1909         //   -: PutStructure(@0, {x:0})
1910         //   2: GetByOffset(@0, x:0)
1911         //   -: MovHint(@2, loc1)
1912         //   -: Branch(#1, #2)
1913         //
1914         // Block #1
1915         //   3: Call(f, @1)
1916         //   4: Return(@0)
1917         //
1918         // Block #2
1919         //   -: Return(undefined)
1920         //
1921         // We need to materialize @1 at @3, and when doing so we need
1922         // to insert a MovHint for the materialization into loc1 as
1923         // well.
1924         // In order to do this, we say that we need to insert an
1925         // update hint for any availability whose node resolve()s to
1926         // the materialization.
1927         for (auto entry : availability.m_heap) {
1928             if (!entry.value.hasNode())
1929                 continue;
1930             if (m_heap.follow(entry.value.node()) != escapee)
1931                 continue;
1932
1933             m_insertionSet.insert(
1934                 nodeIndex,
1935                 entry.key.createHint(m_graph, origin.takeValidExit(canExit), materialization));
1936         }
1937
1938         for (unsigned i = availability.m_locals.size(); i--;) {
1939             if (!availability.m_locals[i].hasNode())
1940                 continue;
1941             if (m_heap.follow(availability.m_locals[i].node()) != escapee)
1942                 continue;
1943
1944             int operand = availability.m_locals.operandForIndex(i);
1945             m_insertionSet.insertNode(
1946                 nodeIndex, SpecNone, MovHint, origin.takeValidExit(canExit), OpInfo(operand),
1947                 materialization->defaultEdge());
1948         }
1949     }
1950
1951     void populateMaterialization(BasicBlock* block, Node* node, Node* escapee)
1952     {
1953         Allocation& allocation = m_heap.getAllocation(escapee);
1954         switch (node->op()) {
1955         case MaterializeNewObject: {
1956             ObjectMaterializationData& data = node->objectMaterializationData();
1957             unsigned firstChild = m_graph.m_varArgChildren.size();
1958
1959             Vector<PromotedHeapLocation> locations = m_locationsForAllocation.get(escapee);
1960
1961             PromotedHeapLocation structure(StructurePLoc, allocation.identifier());
1962             ASSERT(locations.contains(structure));
1963
1964             m_graph.m_varArgChildren.append(Edge(resolve(block, structure), KnownCellUse));
1965
1966             for (PromotedHeapLocation location : locations) {
1967                 switch (location.kind()) {
1968                 case StructurePLoc:
1969                     ASSERT(location == structure);
1970                     break;
1971
1972                 case NamedPropertyPLoc: {
1973                     ASSERT(location.base() == allocation.identifier());
1974                     data.m_properties.append(PhantomPropertyValue(location.info()));
1975                     Node* value = resolve(block, location);
1976                     if (m_sinkCandidates.contains(value))
1977                         m_graph.m_varArgChildren.append(m_bottom);
1978                     else
1979                         m_graph.m_varArgChildren.append(value);
1980                     break;
1981                 }
1982
1983                 default:
1984                     DFG_CRASH(m_graph, node, "Bad location kind");
1985                 }
1986             }
1987
1988             node->children = AdjacencyList(
1989                 AdjacencyList::Variable,
1990                 firstChild, m_graph.m_varArgChildren.size() - firstChild);
1991             break;
1992         }
1993
1994         case MaterializeCreateActivation: {
1995             ObjectMaterializationData& data = node->objectMaterializationData();
1996
1997             unsigned firstChild = m_graph.m_varArgChildren.size();
1998
1999             Vector<PromotedHeapLocation> locations = m_locationsForAllocation.get(escapee);
2000
2001             PromotedHeapLocation symbolTable(ActivationSymbolTablePLoc, allocation.identifier());
2002             ASSERT(locations.contains(symbolTable));
2003             ASSERT(node->cellOperand() == resolve(block, symbolTable)->constant());
2004             m_graph.m_varArgChildren.append(Edge(resolve(block, symbolTable), KnownCellUse));
2005
2006             PromotedHeapLocation scope(ActivationScopePLoc, allocation.identifier());
2007             ASSERT(locations.contains(scope));
2008             m_graph.m_varArgChildren.append(Edge(resolve(block, scope), KnownCellUse));
2009
2010             for (PromotedHeapLocation location : locations) {
2011                 switch (location.kind()) {
2012                 case ActivationScopePLoc: {
2013                     ASSERT(location == scope);
2014                     break;
2015                 }
2016
2017                 case ActivationSymbolTablePLoc: {
2018                     ASSERT(location == symbolTable);
2019                     break;
2020                 }
2021
2022                 case ClosureVarPLoc: {
2023                     ASSERT(location.base() == allocation.identifier());
2024                     data.m_properties.append(PhantomPropertyValue(location.info()));
2025                     Node* value = resolve(block, location);
2026                     if (m_sinkCandidates.contains(value))
2027                         m_graph.m_varArgChildren.append(m_bottom);
2028                     else
2029                         m_graph.m_varArgChildren.append(value);
2030                     break;
2031                 }
2032
2033                 default:
2034                     DFG_CRASH(m_graph, node, "Bad location kind");
2035                 }
2036             }
2037
2038             node->children = AdjacencyList(
2039                 AdjacencyList::Variable,
2040                 firstChild, m_graph.m_varArgChildren.size() - firstChild);
2041             break;
2042         }
2043         
2044         case NewFunction:
2045         case NewArrowFunction:
2046         case NewGeneratorFunction: {
2047             Vector<PromotedHeapLocation> locations = m_locationsForAllocation.get(escapee);
2048             ASSERT(locations.size() == 2);
2049                 
2050             PromotedHeapLocation executable(FunctionExecutablePLoc, allocation.identifier());
2051             ASSERT_UNUSED(executable, locations.contains(executable));
2052                 
2053             PromotedHeapLocation activation(FunctionActivationPLoc, allocation.identifier());
2054             ASSERT(locations.contains(activation));
2055
2056             node->child1() = Edge(resolve(block, activation), KnownCellUse);
2057             break;
2058         }
2059
2060         default:
2061             DFG_CRASH(m_graph, node, "Bad materialize op");
2062         }
2063     }
2064
2065     Node* createRecovery(BasicBlock* block, PromotedHeapLocation location, Node* where, bool& canExit)
2066     {
2067         if (verbose)
2068             dataLog("Recovering ", location, " at ", where, "\n");
2069         ASSERT(location.base()->isPhantomAllocation());
2070         Node* base = getMaterialization(block, location.base());
2071         Node* value = resolve(block, location);
2072
2073         NodeOrigin origin = where->origin.withSemantic(base->origin.semantic);
2074
2075         if (verbose)
2076             dataLog("Base is ", base, " and value is ", value, "\n");
2077
2078         if (base->isPhantomAllocation()) {
2079             return PromotedHeapLocation(base, location.descriptor()).createHint(
2080                 m_graph, origin.takeValidExit(canExit), value);
2081         }
2082
2083         switch (location.kind()) {
2084         case NamedPropertyPLoc: {
2085             Allocation& allocation = m_heap.getAllocation(location.base());
2086
2087             Vector<Structure*> structures;
2088             structures.appendRange(allocation.structures().begin(), allocation.structures().end());
2089             unsigned identifierNumber = location.info();
2090             UniquedStringImpl* uid = m_graph.identifiers()[identifierNumber];
2091
2092             std::sort(
2093                 structures.begin(),
2094                 structures.end(),
2095                 [uid] (Structure *a, Structure* b) -> bool {
2096                     return a->getConcurrently(uid) < b->getConcurrently(uid);
2097                 });
2098
2099             PropertyOffset firstOffset = structures[0]->getConcurrently(uid);
2100
2101             if (firstOffset == structures.last()->getConcurrently(uid)) {
2102                 Node* storage = base;
2103                 // FIXME: When we decide to sink objects with a
2104                 // property storage, we should handle non-inline offsets.
2105                 RELEASE_ASSERT(isInlineOffset(firstOffset));
2106
2107                 StorageAccessData* data = m_graph.m_storageAccessData.add();
2108                 data->offset = firstOffset;
2109                 data->identifierNumber = identifierNumber;
2110
2111                 return m_graph.addNode(
2112                     SpecNone,
2113                     PutByOffset,
2114                     origin.takeValidExit(canExit),
2115                     OpInfo(data),
2116                     Edge(storage, KnownCellUse),
2117                     Edge(base, KnownCellUse),
2118                     value->defaultEdge());
2119             }
2120
2121             MultiPutByOffsetData* data = m_graph.m_multiPutByOffsetData.add();
2122             data->identifierNumber = identifierNumber;
2123
2124             {
2125                 PropertyOffset currentOffset = firstOffset;
2126                 StructureSet currentSet;
2127                 for (Structure* structure : structures) {
2128                     PropertyOffset offset = structure->getConcurrently(uid);
2129                     if (offset != currentOffset) {
2130                         // Because our analysis treats MultiPutByOffset like an escape, we only have to
2131                         // deal with storing results that would have been previously stored by PutByOffset
2132                         // nodes. Those nodes were guarded by the appropriate type checks. This means that
2133                         // at this point, we can simply trust that the incoming value has the right type
2134                         // for whatever structure we are using.
2135                         data->variants.append(
2136                             PutByIdVariant::replace(currentSet, currentOffset, InferredType::Top));
2137                         currentOffset = offset;
2138                         currentSet.clear();
2139                     }
2140                     currentSet.add(structure);
2141                 }
2142                 data->variants.append(
2143                     PutByIdVariant::replace(currentSet, currentOffset, InferredType::Top));
2144             }
2145
2146             return m_graph.addNode(
2147                 SpecNone,
2148                 MultiPutByOffset,
2149                 origin.takeValidExit(canExit),
2150                 OpInfo(data),
2151                 Edge(base, KnownCellUse),
2152                 value->defaultEdge());
2153             break;
2154         }
2155
2156         case ClosureVarPLoc: {
2157             return m_graph.addNode(
2158                 SpecNone,
2159                 PutClosureVar,
2160                 origin.takeValidExit(canExit),
2161                 OpInfo(location.info()),
2162                 Edge(base, KnownCellUse),
2163                 value->defaultEdge());
2164             break;
2165         }
2166
2167         default:
2168             DFG_CRASH(m_graph, base, "Bad location kind");
2169             break;
2170         }
2171     }
2172
2173     SSACalculator m_pointerSSA;
2174     SSACalculator m_allocationSSA;
2175     HashSet<Node*> m_sinkCandidates;
2176     HashMap<PromotedHeapLocation, SSACalculator::Variable*> m_locationToVariable;
2177     HashMap<Node*, SSACalculator::Variable*> m_nodeToVariable;
2178     HashMap<PromotedHeapLocation, Node*> m_localMapping;
2179     HashMap<Node*, Node*> m_escapeeToMaterialization;
2180     InsertionSet m_insertionSet;
2181     CombinedLiveness m_combinedLiveness;
2182
2183     HashMap<Node*, Node*> m_materializationToEscapee;
2184     HashMap<Node*, Vector<Node*>> m_materializationSiteToMaterializations;
2185     HashMap<Node*, Vector<PromotedHeapLocation>> m_materializationSiteToRecoveries;
2186
2187     HashMap<Node*, Vector<PromotedHeapLocation>> m_locationsForAllocation;
2188
2189     BlockMap<LocalHeap> m_heapAtHead;
2190     BlockMap<LocalHeap> m_heapAtTail;
2191     LocalHeap m_heap;
2192
2193     Node* m_bottom = nullptr;
2194 };
2195
2196 }
2197
2198 bool performObjectAllocationSinking(Graph& graph)
2199 {
2200     SamplingRegion samplingRegion("DFG Object Allocation Sinking Phase");
2201     return runPhase<ObjectAllocationSinkingPhase>(graph);
2202 }
2203
2204 } } // namespace JSC::DFG
2205
2206 #endif // ENABLE(DFG_JIT)