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