DFG::freezeFragile should register the frozen value's structure
[WebKit.git] / Source / JavaScriptCore / dfg / DFGGraph.cpp
1 /*
2  * Copyright (C) 2011, 2013-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 "DFGGraph.h"
28
29 #if ENABLE(DFG_JIT)
30
31 #include "BytecodeKills.h"
32 #include "BytecodeLivenessAnalysisInlines.h"
33 #include "CodeBlock.h"
34 #include "CodeBlockWithJITType.h"
35 #include "DFGBlockWorklist.h"
36 #include "DFGClobberSet.h"
37 #include "DFGJITCode.h"
38 #include "DFGVariableAccessDataDump.h"
39 #include "FullBytecodeLiveness.h"
40 #include "FunctionExecutableDump.h"
41 #include "JIT.h"
42 #include "JSLexicalEnvironment.h"
43 #include "MaxFrameExtentForSlowPathCall.h"
44 #include "OperandsInlines.h"
45 #include "JSCInlines.h"
46 #include "StackAlignment.h"
47 #include <wtf/CommaPrinter.h>
48 #include <wtf/ListDump.h>
49
50 namespace JSC { namespace DFG {
51
52 // Creates an array of stringized names.
53 static const char* dfgOpNames[] = {
54 #define STRINGIZE_DFG_OP_ENUM(opcode, flags) #opcode ,
55     FOR_EACH_DFG_OP(STRINGIZE_DFG_OP_ENUM)
56 #undef STRINGIZE_DFG_OP_ENUM
57 };
58
59 Graph::Graph(VM& vm, Plan& plan, LongLivedState& longLivedState)
60     : m_vm(vm)
61     , m_plan(plan)
62     , m_codeBlock(m_plan.codeBlock.get())
63     , m_profiledBlock(m_codeBlock->alternative())
64     , m_allocator(longLivedState.m_allocator)
65     , m_mustHandleValues(OperandsLike, plan.mustHandleValues)
66     , m_nextMachineLocal(0)
67     , m_fixpointState(BeforeFixpoint)
68     , m_structureRegistrationState(HaveNotStartedRegistering)
69     , m_form(LoadStore)
70     , m_unificationState(LocallyUnified)
71     , m_refCountState(EverythingIsLive)
72 {
73     ASSERT(m_profiledBlock);
74     
75     for (unsigned i = m_mustHandleValues.size(); i--;)
76         m_mustHandleValues[i] = freezeFragile(plan.mustHandleValues[i]);
77
78     m_hasDebuggerEnabled = m_profiledBlock->globalObject()->hasDebugger()
79         || Options::forceDebuggerBytecodeGeneration();
80 }
81
82 Graph::~Graph()
83 {
84     for (BlockIndex blockIndex = numBlocks(); blockIndex--;) {
85         BasicBlock* block = this->block(blockIndex);
86         if (!block)
87             continue;
88
89         for (unsigned phiIndex = block->phis.size(); phiIndex--;)
90             m_allocator.free(block->phis[phiIndex]);
91         for (unsigned nodeIndex = block->size(); nodeIndex--;)
92             m_allocator.free(block->at(nodeIndex));
93     }
94     m_allocator.freeAll();
95 }
96
97 const char *Graph::opName(NodeType op)
98 {
99     return dfgOpNames[op];
100 }
101
102 static void printWhiteSpace(PrintStream& out, unsigned amount)
103 {
104     while (amount-- > 0)
105         out.print(" ");
106 }
107
108 bool Graph::dumpCodeOrigin(PrintStream& out, const char* prefix, Node* previousNode, Node* currentNode, DumpContext* context)
109 {
110     if (!previousNode)
111         return false;
112     
113     if (previousNode->origin.semantic.inlineCallFrame == currentNode->origin.semantic.inlineCallFrame)
114         return false;
115     
116     Vector<CodeOrigin> previousInlineStack = previousNode->origin.semantic.inlineStack();
117     Vector<CodeOrigin> currentInlineStack = currentNode->origin.semantic.inlineStack();
118     unsigned commonSize = std::min(previousInlineStack.size(), currentInlineStack.size());
119     unsigned indexOfDivergence = commonSize;
120     for (unsigned i = 0; i < commonSize; ++i) {
121         if (previousInlineStack[i].inlineCallFrame != currentInlineStack[i].inlineCallFrame) {
122             indexOfDivergence = i;
123             break;
124         }
125     }
126     
127     bool hasPrinted = false;
128     
129     // Print the pops.
130     for (unsigned i = previousInlineStack.size(); i-- > indexOfDivergence;) {
131         out.print(prefix);
132         printWhiteSpace(out, i * 2);
133         out.print("<-- ", inContext(*previousInlineStack[i].inlineCallFrame, context), "\n");
134         hasPrinted = true;
135     }
136     
137     // Print the pushes.
138     for (unsigned i = indexOfDivergence; i < currentInlineStack.size(); ++i) {
139         out.print(prefix);
140         printWhiteSpace(out, i * 2);
141         out.print("--> ", inContext(*currentInlineStack[i].inlineCallFrame, context), "\n");
142         hasPrinted = true;
143     }
144     
145     return hasPrinted;
146 }
147
148 int Graph::amountOfNodeWhiteSpace(Node* node)
149 {
150     return (node->origin.semantic.inlineDepth() - 1) * 2;
151 }
152
153 void Graph::printNodeWhiteSpace(PrintStream& out, Node* node)
154 {
155     printWhiteSpace(out, amountOfNodeWhiteSpace(node));
156 }
157
158 void Graph::dump(PrintStream& out, const char* prefix, Node* node, DumpContext* context)
159 {
160     NodeType op = node->op();
161
162     unsigned refCount = node->refCount();
163     bool mustGenerate = node->mustGenerate();
164     if (mustGenerate)
165         --refCount;
166
167     out.print(prefix);
168     printNodeWhiteSpace(out, node);
169
170     // Example/explanation of dataflow dump output
171     //
172     //   14:   <!2:7>  GetByVal(@3, @13)
173     //   ^1     ^2 ^3     ^4       ^5
174     //
175     // (1) The nodeIndex of this operation.
176     // (2) The reference count. The number printed is the 'real' count,
177     //     not including the 'mustGenerate' ref. If the node is
178     //     'mustGenerate' then the count it prefixed with '!'.
179     // (3) The virtual register slot assigned to this node.
180     // (4) The name of the operation.
181     // (5) The arguments to the operation. The may be of the form:
182     //         @#   - a NodeIndex referencing a prior node in the graph.
183     //         arg# - an argument number.
184     //         id#  - the index in the CodeBlock of an identifier { if codeBlock is passed to dump(), the string representation is displayed }.
185     //         var# - the index of a var on the global object, used by GetGlobalVar/PutGlobalVar operations.
186     out.printf("% 4d:<%c%u:", (int)node->index(), mustGenerate ? '!' : ' ', refCount);
187     if (node->hasResult() && node->hasVirtualRegister() && node->virtualRegister().isValid())
188         out.print(node->virtualRegister());
189     else
190         out.print("-");
191     out.print(">\t", opName(op), "(");
192     CommaPrinter comma;
193     if (node->flags() & NodeHasVarArgs) {
194         for (unsigned childIdx = node->firstChild(); childIdx < node->firstChild() + node->numChildren(); childIdx++) {
195             if (!m_varArgChildren[childIdx])
196                 continue;
197             out.print(comma, m_varArgChildren[childIdx]);
198         }
199     } else {
200         if (!!node->child1() || !!node->child2() || !!node->child3())
201             out.print(comma, node->child1());
202         if (!!node->child2() || !!node->child3())
203             out.print(comma, node->child2());
204         if (!!node->child3())
205             out.print(comma, node->child3());
206     }
207
208     if (toCString(NodeFlagsDump(node->flags())) != "<empty>")
209         out.print(comma, NodeFlagsDump(node->flags()));
210     if (node->prediction())
211         out.print(comma, SpeculationDump(node->prediction()));
212     if (node->hasArrayMode())
213         out.print(comma, node->arrayMode());
214     if (node->hasArithMode())
215         out.print(comma, node->arithMode());
216     if (node->hasScopeOffset())
217         out.print(comma, node->scopeOffset());
218     if (node->hasDirectArgumentsOffset())
219         out.print(comma, node->capturedArgumentsOffset());
220     if (node->hasRegisterPointer())
221         out.print(comma, "global", globalObjectFor(node->origin.semantic)->findVariableIndex(node->variablePointer()), "(", RawPointer(node->variablePointer()), ")");
222     if (node->hasIdentifier())
223         out.print(comma, "id", node->identifierNumber(), "{", identifiers()[node->identifierNumber()], "}");
224     if (node->hasPromotedLocationDescriptor())
225         out.print(comma, node->promotedLocationDescriptor());
226     if (node->hasStructureSet())
227         out.print(comma, inContext(node->structureSet(), context));
228     if (node->hasStructure())
229         out.print(comma, inContext(*node->structure(), context));
230     if (node->hasTransition()) {
231         out.print(comma, pointerDumpInContext(node->transition(), context));
232 #if USE(JSVALUE64)
233         out.print(", ID:", node->transition()->next->id());
234 #else
235         out.print(", ID:", RawPointer(node->transition()->next));
236 #endif
237     }
238     if (node->hasCellOperand()) {
239         if (!node->cellOperand()->value() || !node->cellOperand()->value().isCell())
240             out.print(comma, "invalid cell operand: ", node->cellOperand()->value());
241         else {
242             out.print(comma, pointerDump(node->cellOperand()->value().asCell()));
243             if (node->cellOperand()->value().isCell()) {
244                 CallVariant variant(node->cellOperand()->value().asCell());
245                 if (ExecutableBase* executable = variant.executable()) {
246                     if (executable->isHostFunction())
247                         out.print(comma, "<host function>");
248                     else if (FunctionExecutable* functionExecutable = jsDynamicCast<FunctionExecutable*>(executable))
249                         out.print(comma, FunctionExecutableDump(functionExecutable));
250                     else
251                         out.print(comma, "<non-function executable>");
252                 }
253             }
254         }
255     }
256     if (node->hasStorageAccessData()) {
257         StorageAccessData& storageAccessData = node->storageAccessData();
258         out.print(comma, "id", storageAccessData.identifierNumber, "{", identifiers()[storageAccessData.identifierNumber], "}");
259         out.print(", ", static_cast<ptrdiff_t>(storageAccessData.offset));
260     }
261     if (node->hasMultiGetByOffsetData()) {
262         MultiGetByOffsetData& data = node->multiGetByOffsetData();
263         out.print(comma, "id", data.identifierNumber, "{", identifiers()[data.identifierNumber], "}");
264         for (unsigned i = 0; i < data.variants.size(); ++i)
265             out.print(comma, inContext(data.variants[i], context));
266     }
267     if (node->hasMultiPutByOffsetData()) {
268         MultiPutByOffsetData& data = node->multiPutByOffsetData();
269         out.print(comma, "id", data.identifierNumber, "{", identifiers()[data.identifierNumber], "}");
270         for (unsigned i = 0; i < data.variants.size(); ++i)
271             out.print(comma, inContext(data.variants[i], context));
272     }
273     ASSERT(node->hasVariableAccessData(*this) == node->hasLocal(*this));
274     if (node->hasVariableAccessData(*this)) {
275         VariableAccessData* variableAccessData = node->tryGetVariableAccessData();
276         if (variableAccessData) {
277             VirtualRegister operand = variableAccessData->local();
278             out.print(comma, variableAccessData->local(), "(", VariableAccessDataDump(*this, variableAccessData), ")");
279             operand = variableAccessData->machineLocal();
280             if (operand.isValid())
281                 out.print(comma, "machine:", operand);
282         }
283     }
284     if (node->hasStackAccessData()) {
285         StackAccessData* data = node->stackAccessData();
286         out.print(comma, data->local);
287         if (data->machineLocal.isValid())
288             out.print(comma, "machine:", data->machineLocal);
289         out.print(comma, data->format);
290     }
291     if (node->hasUnlinkedLocal()) 
292         out.print(comma, node->unlinkedLocal());
293     if (node->hasUnlinkedMachineLocal()) {
294         VirtualRegister operand = node->unlinkedMachineLocal();
295         if (operand.isValid())
296             out.print(comma, "machine:", operand);
297     }
298     if (node->hasConstantBuffer()) {
299         out.print(comma);
300         out.print(node->startConstant(), ":[");
301         CommaPrinter anotherComma;
302         for (unsigned i = 0; i < node->numConstants(); ++i)
303             out.print(anotherComma, pointerDumpInContext(freeze(m_codeBlock->constantBuffer(node->startConstant())[i]), context));
304         out.print("]");
305     }
306     if (node->hasIndexingType())
307         out.print(comma, IndexingTypeDump(node->indexingType()));
308     if (node->hasTypedArrayType())
309         out.print(comma, node->typedArrayType());
310     if (node->hasPhi())
311         out.print(comma, "^", node->phi()->index());
312     if (node->hasExecutionCounter())
313         out.print(comma, RawPointer(node->executionCounter()));
314     if (node->hasWatchpointSet())
315         out.print(comma, RawPointer(node->watchpointSet()));
316     if (node->hasStoragePointer())
317         out.print(comma, RawPointer(node->storagePointer()));
318     if (node->hasObjectMaterializationData())
319         out.print(comma, node->objectMaterializationData());
320     if (node->hasCallVarargsData())
321         out.print(comma, "firstVarArgOffset = ", node->callVarargsData()->firstVarArgOffset);
322     if (node->hasLoadVarargsData()) {
323         LoadVarargsData* data = node->loadVarargsData();
324         out.print(comma, "start = ", data->start, ", count = ", data->count);
325         if (data->machineStart.isValid())
326             out.print(", machineStart = ", data->machineStart);
327         if (data->machineCount.isValid())
328             out.print(", machineCount = ", data->machineCount);
329         out.print(", offset = ", data->offset, ", mandatoryMinimum = ", data->mandatoryMinimum);
330         out.print(", limit = ", data->limit);
331     }
332     if (node->isConstant())
333         out.print(comma, pointerDumpInContext(node->constant(), context));
334     if (node->isJump())
335         out.print(comma, "T:", *node->targetBlock());
336     if (node->isBranch())
337         out.print(comma, "T:", node->branchData()->taken, ", F:", node->branchData()->notTaken);
338     if (node->isSwitch()) {
339         SwitchData* data = node->switchData();
340         out.print(comma, data->kind);
341         for (unsigned i = 0; i < data->cases.size(); ++i)
342             out.print(comma, inContext(data->cases[i].value, context), ":", data->cases[i].target);
343         out.print(comma, "default:", data->fallThrough);
344     }
345     ClobberSet reads;
346     ClobberSet writes;
347     addReadsAndWrites(*this, node, reads, writes);
348     if (!reads.isEmpty())
349         out.print(comma, "R:", sortedListDump(reads.direct(), ","));
350     if (!writes.isEmpty())
351         out.print(comma, "W:", sortedListDump(writes.direct(), ","));
352     if (node->origin.isSet()) {
353         out.print(comma, "bc#", node->origin.semantic.bytecodeIndex);
354         if (node->origin.semantic != node->origin.forExit)
355             out.print(comma, "exit: ", node->origin.forExit);
356     }
357     
358     out.print(")");
359
360     if (node->hasVariableAccessData(*this) && node->tryGetVariableAccessData())
361         out.print("  predicting ", SpeculationDump(node->tryGetVariableAccessData()->prediction()));
362     else if (node->hasHeapPrediction())
363         out.print("  predicting ", SpeculationDump(node->getHeapPrediction()));
364     
365     out.print("\n");
366 }
367
368 bool Graph::terminalsAreValid()
369 {
370     for (BasicBlock* block : blocksInNaturalOrder()) {
371         if (!block->terminal())
372             return false;
373     }
374     return true;
375 }
376
377 void Graph::dumpBlockHeader(PrintStream& out, const char* prefix, BasicBlock* block, PhiNodeDumpMode phiNodeDumpMode, DumpContext* context)
378 {
379     out.print(prefix, "Block ", *block, " (", inContext(block->at(0)->origin.semantic, context), "):", block->isReachable ? "" : " (skipped)", block->isOSRTarget ? " (OSR target)" : "", "\n");
380     if (block->executionCount == block->executionCount)
381         out.print(prefix, "  Execution count: ", block->executionCount, "\n");
382     out.print(prefix, "  Predecessors:");
383     for (size_t i = 0; i < block->predecessors.size(); ++i)
384         out.print(" ", *block->predecessors[i]);
385     out.print("\n");
386     out.print(prefix, "  Successors:");
387     if (block->terminal()) {
388         for (BasicBlock* successor : block->successors()) {
389             out.print(" ", *successor);
390             if (m_prePostNumbering.isValid())
391                 out.print(" (", m_prePostNumbering.edgeKind(block, successor), ")");
392         }
393     } else
394         out.print(" <invalid>");
395     out.print("\n");
396     if (m_dominators.isValid() && terminalsAreValid()) {
397         out.print(prefix, "  Dominated by: ", m_dominators.dominatorsOf(block), "\n");
398         out.print(prefix, "  Dominates: ", m_dominators.blocksDominatedBy(block), "\n");
399         out.print(prefix, "  Dominance Frontier: ", m_dominators.dominanceFrontierOf(block), "\n");
400         out.print(prefix, "  Iterated Dominance Frontier: ", m_dominators.iteratedDominanceFrontierOf(BlockList(1, block)), "\n");
401     }
402     if (m_prePostNumbering.isValid())
403         out.print(prefix, "  Pre/Post Numbering: ", m_prePostNumbering.preNumber(block), "/", m_prePostNumbering.postNumber(block), "\n");
404     if (m_naturalLoops.isValid()) {
405         if (const NaturalLoop* loop = m_naturalLoops.headerOf(block)) {
406             out.print(prefix, "  Loop header, contains:");
407             Vector<BlockIndex> sortedBlockList;
408             for (unsigned i = 0; i < loop->size(); ++i)
409                 sortedBlockList.append(loop->at(i)->index);
410             std::sort(sortedBlockList.begin(), sortedBlockList.end());
411             for (unsigned i = 0; i < sortedBlockList.size(); ++i)
412                 out.print(" #", sortedBlockList[i]);
413             out.print("\n");
414         }
415         
416         Vector<const NaturalLoop*> containingLoops =
417             m_naturalLoops.loopsOf(block);
418         if (!containingLoops.isEmpty()) {
419             out.print(prefix, "  Containing loop headers:");
420             for (unsigned i = 0; i < containingLoops.size(); ++i)
421                 out.print(" ", *containingLoops[i]->header());
422             out.print("\n");
423         }
424     }
425     if (!block->phis.isEmpty()) {
426         out.print(prefix, "  Phi Nodes:");
427         for (size_t i = 0; i < block->phis.size(); ++i) {
428             Node* phiNode = block->phis[i];
429             if (!phiNode->shouldGenerate() && phiNodeDumpMode == DumpLivePhisOnly)
430                 continue;
431             out.print(" @", phiNode->index(), "<", phiNode->local(), ",", phiNode->refCount(), ">->(");
432             if (phiNode->child1()) {
433                 out.print("@", phiNode->child1()->index());
434                 if (phiNode->child2()) {
435                     out.print(", @", phiNode->child2()->index());
436                     if (phiNode->child3())
437                         out.print(", @", phiNode->child3()->index());
438                 }
439             }
440             out.print(")", i + 1 < block->phis.size() ? "," : "");
441         }
442         out.print("\n");
443     }
444 }
445
446 void Graph::dump(PrintStream& out, DumpContext* context)
447 {
448     DumpContext myContext;
449     myContext.graph = this;
450     if (!context)
451         context = &myContext;
452     
453     out.print("\n");
454     out.print("DFG for ", CodeBlockWithJITType(m_codeBlock, JITCode::DFGJIT), ":\n");
455     out.print("  Fixpoint state: ", m_fixpointState, "; Form: ", m_form, "; Unification state: ", m_unificationState, "; Ref count state: ", m_refCountState, "\n");
456     if (m_form == SSA)
457         out.print("  Argument formats: ", listDump(m_argumentFormats), "\n");
458     else
459         out.print("  Arguments: ", listDump(m_arguments), "\n");
460     out.print("\n");
461     
462     Node* lastNode = 0;
463     for (size_t b = 0; b < m_blocks.size(); ++b) {
464         BasicBlock* block = m_blocks[b].get();
465         if (!block)
466             continue;
467         dumpBlockHeader(out, "", block, DumpAllPhis, context);
468         out.print("  States: ", block->cfaStructureClobberStateAtHead);
469         if (!block->cfaHasVisited)
470             out.print(", CurrentlyCFAUnreachable");
471         if (!block->intersectionOfCFAHasVisited)
472             out.print(", CFAUnreachable");
473         out.print("\n");
474         switch (m_form) {
475         case LoadStore:
476         case ThreadedCPS: {
477             out.print("  Vars Before: ");
478             if (block->cfaHasVisited)
479                 out.print(inContext(block->valuesAtHead, context));
480             else
481                 out.print("<empty>");
482             out.print("\n");
483             out.print("  Intersected Vars Before: ");
484             if (block->intersectionOfCFAHasVisited)
485                 out.print(inContext(block->intersectionOfPastValuesAtHead, context));
486             else
487                 out.print("<empty>");
488             out.print("\n");
489             out.print("  Var Links: ", block->variablesAtHead, "\n");
490             break;
491         }
492             
493         case SSA: {
494             RELEASE_ASSERT(block->ssa);
495             out.print("  Availability: ", block->ssa->availabilityAtHead, "\n");
496             out.print("  Live: ", nodeListDump(block->ssa->liveAtHead), "\n");
497             out.print("  Values: ", nodeMapDump(block->ssa->valuesAtHead, context), "\n");
498             break;
499         } }
500         for (size_t i = 0; i < block->size(); ++i) {
501             dumpCodeOrigin(out, "", lastNode, block->at(i), context);
502             dump(out, "", block->at(i), context);
503             lastNode = block->at(i);
504         }
505         out.print("  States: ", block->cfaBranchDirection, ", ", block->cfaStructureClobberStateAtTail);
506         if (!block->cfaDidFinish)
507             out.print(", CFAInvalidated");
508         out.print("\n");
509         switch (m_form) {
510         case LoadStore:
511         case ThreadedCPS: {
512             out.print("  Vars After: ");
513             if (block->cfaHasVisited)
514                 out.print(inContext(block->valuesAtTail, context));
515             else
516                 out.print("<empty>");
517             out.print("\n");
518             out.print("  Var Links: ", block->variablesAtTail, "\n");
519             break;
520         }
521             
522         case SSA: {
523             RELEASE_ASSERT(block->ssa);
524             out.print("  Availability: ", block->ssa->availabilityAtTail, "\n");
525             out.print("  Live: ", nodeListDump(block->ssa->liveAtTail), "\n");
526             out.print("  Values: ", nodeMapDump(block->ssa->valuesAtTail, context), "\n");
527             break;
528         } }
529         out.print("\n");
530     }
531     
532     if (!myContext.isEmpty()) {
533         myContext.dump(out);
534         out.print("\n");
535     }
536 }
537
538 void Graph::dethread()
539 {
540     if (m_form == LoadStore || m_form == SSA)
541         return;
542     
543     if (logCompilationChanges())
544         dataLog("Dethreading DFG graph.\n");
545     
546     SamplingRegion samplingRegion("DFG Dethreading");
547     
548     for (BlockIndex blockIndex = m_blocks.size(); blockIndex--;) {
549         BasicBlock* block = m_blocks[blockIndex].get();
550         if (!block)
551             continue;
552         for (unsigned phiIndex = block->phis.size(); phiIndex--;) {
553             Node* phi = block->phis[phiIndex];
554             phi->children.reset();
555         }
556     }
557     
558     m_form = LoadStore;
559 }
560
561 void Graph::handleSuccessor(Vector<BasicBlock*, 16>& worklist, BasicBlock* block, BasicBlock* successor)
562 {
563     if (!successor->isReachable) {
564         successor->isReachable = true;
565         worklist.append(successor);
566     }
567     
568     successor->predecessors.append(block);
569 }
570
571 void Graph::determineReachability()
572 {
573     Vector<BasicBlock*, 16> worklist;
574     worklist.append(block(0));
575     block(0)->isReachable = true;
576     while (!worklist.isEmpty()) {
577         BasicBlock* block = worklist.takeLast();
578         for (unsigned i = block->numSuccessors(); i--;)
579             handleSuccessor(worklist, block, block->successor(i));
580     }
581 }
582
583 void Graph::resetReachability()
584 {
585     for (BlockIndex blockIndex = m_blocks.size(); blockIndex--;) {
586         BasicBlock* block = m_blocks[blockIndex].get();
587         if (!block)
588             continue;
589         block->isReachable = false;
590         block->predecessors.clear();
591     }
592     
593     determineReachability();
594 }
595
596 namespace {
597
598 class RefCountCalculator {
599 public:
600     RefCountCalculator(Graph& graph)
601         : m_graph(graph)
602     {
603     }
604     
605     void calculate()
606     {
607         // First reset the counts to 0 for all nodes.
608         for (BlockIndex blockIndex = 0; blockIndex < m_graph.numBlocks(); ++blockIndex) {
609             BasicBlock* block = m_graph.block(blockIndex);
610             if (!block)
611                 continue;
612             for (unsigned indexInBlock = block->size(); indexInBlock--;)
613                 block->at(indexInBlock)->setRefCount(0);
614             for (unsigned phiIndex = block->phis.size(); phiIndex--;)
615                 block->phis[phiIndex]->setRefCount(0);
616         }
617     
618         // Now find the roots:
619         // - Nodes that are must-generate.
620         // - Nodes that are reachable from type checks.
621         // Set their ref counts to 1 and put them on the worklist.
622         for (BlockIndex blockIndex = 0; blockIndex < m_graph.numBlocks(); ++blockIndex) {
623             BasicBlock* block = m_graph.block(blockIndex);
624             if (!block)
625                 continue;
626             for (unsigned indexInBlock = block->size(); indexInBlock--;) {
627                 Node* node = block->at(indexInBlock);
628                 DFG_NODE_DO_TO_CHILDREN(m_graph, node, findTypeCheckRoot);
629                 if (!(node->flags() & NodeMustGenerate))
630                     continue;
631                 if (!node->postfixRef())
632                     m_worklist.append(node);
633             }
634         }
635         
636         while (!m_worklist.isEmpty()) {
637             while (!m_worklist.isEmpty()) {
638                 Node* node = m_worklist.last();
639                 m_worklist.removeLast();
640                 ASSERT(node->shouldGenerate()); // It should not be on the worklist unless it's ref'ed.
641                 DFG_NODE_DO_TO_CHILDREN(m_graph, node, countEdge);
642             }
643             
644             if (m_graph.m_form == SSA) {
645                 // Find Phi->Upsilon edges, which are represented as meta-data in the
646                 // Upsilon.
647                 for (BlockIndex blockIndex = m_graph.numBlocks(); blockIndex--;) {
648                     BasicBlock* block = m_graph.block(blockIndex);
649                     if (!block)
650                         continue;
651                     for (unsigned nodeIndex = block->size(); nodeIndex--;) {
652                         Node* node = block->at(nodeIndex);
653                         if (node->op() != Upsilon)
654                             continue;
655                         if (node->shouldGenerate())
656                             continue;
657                         if (node->phi()->shouldGenerate())
658                             countNode(node);
659                     }
660                 }
661             }
662         }
663     }
664     
665 private:
666     void findTypeCheckRoot(Node*, Edge edge)
667     {
668         // We may have an "unproved" untyped use for code that is unreachable. The CFA
669         // will just not have gotten around to it.
670         if (edge.isProved() || edge.willNotHaveCheck())
671             return;
672         if (!edge->postfixRef())
673             m_worklist.append(edge.node());
674     }
675     
676     void countNode(Node* node)
677     {
678         if (node->postfixRef())
679             return;
680         m_worklist.append(node);
681     }
682     
683     void countEdge(Node*, Edge edge)
684     {
685         // Don't count edges that are already counted for their type checks.
686         if (!(edge.isProved() || edge.willNotHaveCheck()))
687             return;
688         countNode(edge.node());
689     }
690     
691     Graph& m_graph;
692     Vector<Node*, 128> m_worklist;
693 };
694
695 } // anonymous namespace
696
697 void Graph::computeRefCounts()
698 {
699     RefCountCalculator calculator(*this);
700     calculator.calculate();
701 }
702
703 void Graph::killBlockAndItsContents(BasicBlock* block)
704 {
705     for (unsigned phiIndex = block->phis.size(); phiIndex--;)
706         m_allocator.free(block->phis[phiIndex]);
707     for (unsigned nodeIndex = block->size(); nodeIndex--;)
708         m_allocator.free(block->at(nodeIndex));
709     
710     killBlock(block);
711 }
712
713 void Graph::killUnreachableBlocks()
714 {
715     for (BlockIndex blockIndex = 0; blockIndex < numBlocks(); ++blockIndex) {
716         BasicBlock* block = this->block(blockIndex);
717         if (!block)
718             continue;
719         if (block->isReachable)
720             continue;
721         
722         killBlockAndItsContents(block);
723     }
724 }
725
726 void Graph::invalidateCFG()
727 {
728     m_dominators.invalidate();
729     m_naturalLoops.invalidate();
730     m_prePostNumbering.invalidate();
731 }
732
733 void Graph::substituteGetLocal(BasicBlock& block, unsigned startIndexInBlock, VariableAccessData* variableAccessData, Node* newGetLocal)
734 {
735     for (unsigned indexInBlock = startIndexInBlock; indexInBlock < block.size(); ++indexInBlock) {
736         Node* node = block[indexInBlock];
737         bool shouldContinue = true;
738         switch (node->op()) {
739         case SetLocal: {
740             if (node->local() == variableAccessData->local())
741                 shouldContinue = false;
742             break;
743         }
744                 
745         case GetLocal: {
746             if (node->variableAccessData() != variableAccessData)
747                 continue;
748             substitute(block, indexInBlock, node, newGetLocal);
749             Node* oldTailNode = block.variablesAtTail.operand(variableAccessData->local());
750             if (oldTailNode == node)
751                 block.variablesAtTail.operand(variableAccessData->local()) = newGetLocal;
752             shouldContinue = false;
753             break;
754         }
755                 
756         default:
757             break;
758         }
759         if (!shouldContinue)
760             break;
761     }
762 }
763
764 BlockList Graph::blocksInPreOrder()
765 {
766     BlockList result;
767     BlockWorklist worklist;
768     worklist.push(block(0));
769     while (BasicBlock* block = worklist.pop()) {
770         result.append(block);
771         for (unsigned i = block->numSuccessors(); i--;)
772             worklist.push(block->successor(i));
773     }
774     return result;
775 }
776
777 BlockList Graph::blocksInPostOrder()
778 {
779     BlockList result;
780     PostOrderBlockWorklist worklist;
781     worklist.push(block(0));
782     while (BlockWithOrder item = worklist.pop()) {
783         switch (item.order) {
784         case PreOrder:
785             worklist.pushPost(item.block);
786             for (unsigned i = item.block->numSuccessors(); i--;)
787                 worklist.push(item.block->successor(i));
788             break;
789         case PostOrder:
790             result.append(item.block);
791             break;
792         }
793     }
794     return result;
795 }
796
797 void Graph::clearReplacements()
798 {
799     for (BlockIndex blockIndex = numBlocks(); blockIndex--;) {
800         BasicBlock* block = m_blocks[blockIndex].get();
801         if (!block)
802             continue;
803         for (unsigned phiIndex = block->phis.size(); phiIndex--;)
804             block->phis[phiIndex]->setReplacement(nullptr);
805         for (unsigned nodeIndex = block->size(); nodeIndex--;)
806             block->at(nodeIndex)->setReplacement(nullptr);
807     }
808 }
809
810 void Graph::clearEpochs()
811 {
812     for (BlockIndex blockIndex = numBlocks(); blockIndex--;) {
813         BasicBlock* block = m_blocks[blockIndex].get();
814         if (!block)
815             continue;
816         for (unsigned phiIndex = block->phis.size(); phiIndex--;)
817             block->phis[phiIndex]->setEpoch(Epoch());
818         for (unsigned nodeIndex = block->size(); nodeIndex--;)
819             block->at(nodeIndex)->setEpoch(Epoch());
820     }
821 }
822
823 void Graph::initializeNodeOwners()
824 {
825     for (BlockIndex blockIndex = numBlocks(); blockIndex--;) {
826         BasicBlock* block = m_blocks[blockIndex].get();
827         if (!block)
828             continue;
829         for (unsigned phiIndex = block->phis.size(); phiIndex--;)
830             block->phis[phiIndex]->owner = block;
831         for (unsigned nodeIndex = block->size(); nodeIndex--;)
832             block->at(nodeIndex)->owner = block;
833     }
834 }
835
836 void Graph::clearFlagsOnAllNodes(NodeFlags flags)
837 {
838     for (BlockIndex blockIndex = numBlocks(); blockIndex--;) {
839         BasicBlock* block = m_blocks[blockIndex].get();
840         if (!block)
841             continue;
842         for (unsigned phiIndex = block->phis.size(); phiIndex--;)
843             block->phis[phiIndex]->clearFlags(flags);
844         for (unsigned nodeIndex = block->size(); nodeIndex--;)
845             block->at(nodeIndex)->clearFlags(flags);
846     }
847 }
848
849 FullBytecodeLiveness& Graph::livenessFor(CodeBlock* codeBlock)
850 {
851     HashMap<CodeBlock*, std::unique_ptr<FullBytecodeLiveness>>::iterator iter = m_bytecodeLiveness.find(codeBlock);
852     if (iter != m_bytecodeLiveness.end())
853         return *iter->value;
854     
855     std::unique_ptr<FullBytecodeLiveness> liveness = std::make_unique<FullBytecodeLiveness>();
856     codeBlock->livenessAnalysis().computeFullLiveness(*liveness);
857     FullBytecodeLiveness& result = *liveness;
858     m_bytecodeLiveness.add(codeBlock, WTF::move(liveness));
859     return result;
860 }
861
862 FullBytecodeLiveness& Graph::livenessFor(InlineCallFrame* inlineCallFrame)
863 {
864     return livenessFor(baselineCodeBlockFor(inlineCallFrame));
865 }
866
867 BytecodeKills& Graph::killsFor(CodeBlock* codeBlock)
868 {
869     HashMap<CodeBlock*, std::unique_ptr<BytecodeKills>>::iterator iter = m_bytecodeKills.find(codeBlock);
870     if (iter != m_bytecodeKills.end())
871         return *iter->value;
872     
873     std::unique_ptr<BytecodeKills> kills = std::make_unique<BytecodeKills>();
874     codeBlock->livenessAnalysis().computeKills(*kills);
875     BytecodeKills& result = *kills;
876     m_bytecodeKills.add(codeBlock, WTF::move(kills));
877     return result;
878 }
879
880 BytecodeKills& Graph::killsFor(InlineCallFrame* inlineCallFrame)
881 {
882     return killsFor(baselineCodeBlockFor(inlineCallFrame));
883 }
884
885 bool Graph::isLiveInBytecode(VirtualRegister operand, CodeOrigin codeOrigin)
886 {
887     for (;;) {
888         VirtualRegister reg = VirtualRegister(
889             operand.offset() - codeOrigin.stackOffset());
890         
891         if (operand.offset() < codeOrigin.stackOffset() + JSStack::CallFrameHeaderSize) {
892             if (reg.isArgument()) {
893                 RELEASE_ASSERT(reg.offset() < JSStack::CallFrameHeaderSize);
894                 
895                 if (codeOrigin.inlineCallFrame->isClosureCall
896                     && reg.offset() == JSStack::Callee)
897                     return true;
898                 
899                 if (codeOrigin.inlineCallFrame->isVarargs()
900                     && reg.offset() == JSStack::ArgumentCount)
901                     return true;
902                 
903                 return false;
904             }
905             
906             return livenessFor(codeOrigin.inlineCallFrame).operandIsLive(
907                 reg.offset(), codeOrigin.bytecodeIndex);
908         }
909         
910         InlineCallFrame* inlineCallFrame = codeOrigin.inlineCallFrame;
911         if (!inlineCallFrame)
912             break;
913
914         // Arguments are always live. This would be redundant if it wasn't for our
915         // op_call_varargs inlining.
916         if (reg.isArgument()
917             && static_cast<size_t>(reg.toArgument()) < inlineCallFrame->arguments.size())
918             return true;
919         
920         codeOrigin = inlineCallFrame->caller;
921     }
922     
923     return true;
924 }
925
926 BitVector Graph::localsLiveInBytecode(CodeOrigin codeOrigin)
927 {
928     BitVector result;
929     result.ensureSize(block(0)->variablesAtHead.numberOfLocals());
930     forAllLocalsLiveInBytecode(
931         codeOrigin,
932         [&] (VirtualRegister reg) {
933             ASSERT(reg.isLocal());
934             result.quickSet(reg.toLocal());
935         });
936     return result;
937 }
938
939 unsigned Graph::frameRegisterCount()
940 {
941     unsigned result = m_nextMachineLocal + std::max(m_parameterSlots, static_cast<unsigned>(maxFrameExtentForSlowPathCallInRegisters));
942     return roundLocalRegisterCountForFramePointerOffset(result);
943 }
944
945 unsigned Graph::stackPointerOffset()
946 {
947     return virtualRegisterForLocal(frameRegisterCount() - 1).offset();
948 }
949
950 unsigned Graph::requiredRegisterCountForExit()
951 {
952     unsigned count = JIT::frameRegisterCountFor(m_profiledBlock);
953     for (InlineCallFrameSet::iterator iter = m_plan.inlineCallFrames->begin(); !!iter; ++iter) {
954         InlineCallFrame* inlineCallFrame = *iter;
955         CodeBlock* codeBlock = baselineCodeBlockForInlineCallFrame(inlineCallFrame);
956         unsigned requiredCount = VirtualRegister(inlineCallFrame->stackOffset).toLocal() + 1 + JIT::frameRegisterCountFor(codeBlock);
957         count = std::max(count, requiredCount);
958     }
959     return count;
960 }
961
962 unsigned Graph::requiredRegisterCountForExecutionAndExit()
963 {
964     return std::max(frameRegisterCount(), requiredRegisterCountForExit());
965 }
966
967 JSValue Graph::tryGetConstantProperty(
968     JSValue base, const StructureSet& structureSet, PropertyOffset offset)
969 {
970     if (!base || !base.isObject())
971         return JSValue();
972     
973     JSObject* object = asObject(base);
974     
975     for (unsigned i = structureSet.size(); i--;) {
976         Structure* structure = structureSet[i];
977         WatchpointSet* set = structure->propertyReplacementWatchpointSet(offset);
978         if (!set || !set->isStillValid())
979             return JSValue();
980         
981         ASSERT(structure->isValidOffset(offset));
982         ASSERT(!structure->isUncacheableDictionary());
983         
984         watchpoints().addLazily(set);
985     }
986     
987     // What follows may require some extra thought. We need this load to load a valid JSValue. If
988     // our profiling makes sense and we're still on track to generate code that won't be
989     // invalidated, then we have nothing to worry about. We do, however, have to worry about
990     // loading - and then using - an invalid JSValue in the case that unbeknownst to us our code
991     // is doomed.
992     //
993     // One argument in favor of this code is that it should definitely work because the butterfly
994     // is always set before the structure. However, we don't currently have a fence between those
995     // stores. It's not clear if this matters, however. We don't ever shrink the property storage.
996     // So, for this to fail, you'd need an access on a constant object pointer such that the inline
997     // caches told us that the object had a structure that it did not *yet* have, and then later,
998     // the object transitioned to that structure that the inline caches had alraedy seen. And then
999     // the processor reordered the stores. Seems unlikely and difficult to test. I believe that
1000     // this is worth revisiting but it isn't worth losing sleep over. Filed:
1001     // https://bugs.webkit.org/show_bug.cgi?id=134641
1002     //
1003     // For now, we just do the minimal thing: defend against the structure right now being
1004     // incompatible with the getDirect we're trying to do. The easiest way to do that is to
1005     // determine if the structure belongs to the proven set.
1006     
1007     if (!structureSet.contains(object->structure()))
1008         return JSValue();
1009     
1010     return object->getDirect(offset);
1011 }
1012
1013 JSValue Graph::tryGetConstantProperty(JSValue base, Structure* structure, PropertyOffset offset)
1014 {
1015     return tryGetConstantProperty(base, StructureSet(structure), offset);
1016 }
1017
1018 JSValue Graph::tryGetConstantProperty(
1019     JSValue base, const StructureAbstractValue& structure, PropertyOffset offset)
1020 {
1021     if (structure.isTop() || structure.isClobbered())
1022         return JSValue();
1023     
1024     return tryGetConstantProperty(base, structure.set(), offset);
1025 }
1026
1027 JSValue Graph::tryGetConstantProperty(const AbstractValue& base, PropertyOffset offset)
1028 {
1029     return tryGetConstantProperty(base.m_value, base.m_structure, offset);
1030 }
1031
1032 JSValue Graph::tryGetConstantClosureVar(JSValue base, ScopeOffset offset)
1033 {
1034     // This has an awesome concurrency story. See comment for GetGlobalVar in ByteCodeParser.
1035     
1036     if (!base)
1037         return JSValue();
1038     
1039     JSLexicalEnvironment* activation = jsDynamicCast<JSLexicalEnvironment*>(base);
1040     if (!activation)
1041         return JSValue();
1042     
1043     SymbolTable* symbolTable = activation->symbolTable();
1044     JSValue value;
1045     WatchpointSet* set;
1046     {
1047         ConcurrentJITLocker locker(symbolTable->m_lock);
1048         
1049         SymbolTableEntry* entry = symbolTable->entryFor(locker, offset);
1050         if (!entry)
1051             return JSValue();
1052         
1053         set = entry->watchpointSet();
1054         if (!set)
1055             return JSValue();
1056         
1057         if (set->state() != IsWatched)
1058             return JSValue();
1059         
1060         ASSERT(entry->scopeOffset() == offset);
1061         value = activation->variableAt(offset).get();
1062         if (!value)
1063             return JSValue();
1064     }
1065     
1066     watchpoints().addLazily(set);
1067     
1068     return value;
1069 }
1070
1071 JSValue Graph::tryGetConstantClosureVar(const AbstractValue& value, ScopeOffset offset)
1072 {
1073     return tryGetConstantClosureVar(value.m_value, offset);
1074 }
1075
1076 JSValue Graph::tryGetConstantClosureVar(Node* node, ScopeOffset offset)
1077 {
1078     if (!node->hasConstant())
1079         return JSValue();
1080     return tryGetConstantClosureVar(node->asJSValue(), offset);
1081 }
1082
1083 JSArrayBufferView* Graph::tryGetFoldableView(JSValue value)
1084 {
1085     if (!value)
1086         return nullptr;
1087     JSArrayBufferView* view = jsDynamicCast<JSArrayBufferView*>(value);
1088     if (!value)
1089         return nullptr;
1090     if (!view->length())
1091         return nullptr;
1092     WTF::loadLoadFence();
1093     watchpoints().addLazily(view);
1094     return view;
1095 }
1096
1097 JSArrayBufferView* Graph::tryGetFoldableView(JSValue value, ArrayMode arrayMode)
1098 {
1099     if (arrayMode.typedArrayType() == NotTypedArray)
1100         return nullptr;
1101     return tryGetFoldableView(value);
1102 }
1103
1104 void Graph::registerFrozenValues()
1105 {
1106     m_codeBlock->constants().resize(0);
1107     m_codeBlock->constantsSourceCodeRepresentation().resize(0);
1108     for (FrozenValue* value : m_frozenValues) {
1109         if (value->structure())
1110             ASSERT(m_plan.weakReferences.contains(value->structure()));
1111         
1112         switch (value->strength()) {
1113         case FragileValue: {
1114             break;
1115         }
1116         case WeakValue: {
1117             m_plan.weakReferences.addLazily(value->value().asCell());
1118             break;
1119         }
1120         case StrongValue: {
1121             unsigned constantIndex = m_codeBlock->addConstantLazily();
1122             initializeLazyWriteBarrierForConstant(
1123                 m_plan.writeBarriers,
1124                 m_codeBlock->constants()[constantIndex],
1125                 m_codeBlock,
1126                 constantIndex,
1127                 m_codeBlock->ownerExecutable(),
1128                 value->value());
1129             break;
1130         } }
1131     }
1132     m_codeBlock->constants().shrinkToFit();
1133     m_codeBlock->constantsSourceCodeRepresentation().shrinkToFit();
1134 }
1135
1136 void Graph::visitChildren(SlotVisitor& visitor)
1137 {
1138     for (FrozenValue* value : m_frozenValues) {
1139         visitor.appendUnbarrieredReadOnlyValue(value->value());
1140         visitor.appendUnbarrieredReadOnlyPointer(value->structure());
1141     }
1142     
1143     for (BlockIndex blockIndex = numBlocks(); blockIndex--;) {
1144         BasicBlock* block = this->block(blockIndex);
1145         if (!block)
1146             continue;
1147         
1148         for (unsigned nodeIndex = 0; nodeIndex < block->size(); ++nodeIndex) {
1149             Node* node = block->at(nodeIndex);
1150             
1151             switch (node->op()) {
1152             case CheckStructure:
1153                 for (unsigned i = node->structureSet().size(); i--;)
1154                     visitor.appendUnbarrieredReadOnlyPointer(node->structureSet()[i]);
1155                 break;
1156                 
1157             case NewObject:
1158             case ArrayifyToStructure:
1159             case NewStringObject:
1160                 visitor.appendUnbarrieredReadOnlyPointer(node->structure());
1161                 break;
1162                 
1163             case PutStructure:
1164             case AllocatePropertyStorage:
1165             case ReallocatePropertyStorage:
1166                 visitor.appendUnbarrieredReadOnlyPointer(
1167                     node->transition()->previous);
1168                 visitor.appendUnbarrieredReadOnlyPointer(
1169                     node->transition()->next);
1170                 break;
1171                 
1172             case MultiGetByOffset:
1173                 for (unsigned i = node->multiGetByOffsetData().variants.size(); i--;) {
1174                     GetByIdVariant& variant = node->multiGetByOffsetData().variants[i];
1175                     const StructureSet& set = variant.structureSet();
1176                     for (unsigned j = set.size(); j--;)
1177                         visitor.appendUnbarrieredReadOnlyPointer(set[j]);
1178
1179                     // Don't need to mark anything in the structure chain because that would
1180                     // have been decomposed into CheckStructure's. Don't need to mark the
1181                     // callLinkStatus because we wouldn't use MultiGetByOffset if any of the
1182                     // variants did that.
1183                     ASSERT(!variant.callLinkStatus());
1184                 }
1185                 break;
1186                     
1187             case MultiPutByOffset:
1188                 for (unsigned i = node->multiPutByOffsetData().variants.size(); i--;) {
1189                     PutByIdVariant& variant = node->multiPutByOffsetData().variants[i];
1190                     const StructureSet& set = variant.oldStructure();
1191                     for (unsigned j = set.size(); j--;)
1192                         visitor.appendUnbarrieredReadOnlyPointer(set[j]);
1193                     if (variant.kind() == PutByIdVariant::Transition)
1194                         visitor.appendUnbarrieredReadOnlyPointer(variant.newStructure());
1195                 }
1196                 break;
1197                 
1198             default:
1199                 break;
1200             }
1201         }
1202     }
1203 }
1204
1205 FrozenValue* Graph::freezeFragile(JSValue value)
1206 {
1207     if (UNLIKELY(!value))
1208         return FrozenValue::emptySingleton();
1209     
1210     auto result = m_frozenValueMap.add(JSValue::encode(value), nullptr);
1211     if (LIKELY(!result.isNewEntry))
1212         return result.iterator->value;
1213
1214     if (value.isUInt32())
1215         m_uint32ValuesInUse.append(value.asUInt32());
1216     
1217     FrozenValue frozenValue = FrozenValue::freeze(value);
1218     if (Structure* structure = frozenValue.structure())
1219         registerStructure(structure);
1220     
1221     return result.iterator->value = m_frozenValues.add(frozenValue);
1222 }
1223
1224 FrozenValue* Graph::freeze(JSValue value)
1225 {
1226     FrozenValue* result = freezeFragile(value);
1227     result->strengthenTo(WeakValue);
1228     return result;
1229 }
1230
1231 FrozenValue* Graph::freezeStrong(JSValue value)
1232 {
1233     FrozenValue* result = freezeFragile(value);
1234     result->strengthenTo(StrongValue);
1235     return result;
1236 }
1237
1238 void Graph::convertToConstant(Node* node, FrozenValue* value)
1239 {
1240     if (value->structure())
1241         assertIsRegistered(value->structure());
1242     node->convertToConstant(value);
1243 }
1244
1245 void Graph::convertToConstant(Node* node, JSValue value)
1246 {
1247     convertToConstant(node, freeze(value));
1248 }
1249
1250 void Graph::convertToStrongConstant(Node* node, JSValue value)
1251 {
1252     convertToConstant(node, freezeStrong(value));
1253 }
1254
1255 StructureRegistrationResult Graph::registerStructure(Structure* structure)
1256 {
1257     m_plan.weakReferences.addLazily(structure);
1258     if (m_plan.watchpoints.consider(structure))
1259         return StructureRegisteredAndWatched;
1260     return StructureRegisteredNormally;
1261 }
1262
1263 void Graph::assertIsRegistered(Structure* structure)
1264 {
1265     // It's convenient to be able to call this with a maybe-null structure.
1266     if (!structure)
1267         return;
1268     
1269     if (m_structureRegistrationState == HaveNotStartedRegistering)
1270         return;
1271     
1272     DFG_ASSERT(*this, nullptr, m_plan.weakReferences.contains(structure));
1273     
1274     if (!structure->dfgShouldWatch())
1275         return;
1276     if (watchpoints().isWatched(structure->transitionWatchpointSet()))
1277         return;
1278     
1279     DFG_CRASH(*this, nullptr, toCString("Structure ", pointerDump(structure), " is watchable but isn't being watched.").data());
1280 }
1281
1282 NO_RETURN_DUE_TO_CRASH static void crash(
1283     Graph& graph, const CString& whileText, const char* file, int line, const char* function,
1284     const char* assertion)
1285 {
1286     startCrashing();
1287     dataLog("DFG ASSERTION FAILED: ", assertion, "\n");
1288     dataLog(file, "(", line, ") : ", function, "\n");
1289     dataLog("\n");
1290     dataLog(whileText);
1291     dataLog("Graph at time of failure:\n");
1292     graph.dump();
1293     dataLog("\n");
1294     dataLog("DFG ASSERTION FAILED: ", assertion, "\n");
1295     dataLog(file, "(", line, ") : ", function, "\n");
1296     CRASH_WITH_SECURITY_IMPLICATION();
1297 }
1298
1299 void Graph::handleAssertionFailure(
1300     std::nullptr_t, const char* file, int line, const char* function, const char* assertion)
1301 {
1302     crash(*this, "", file, line, function, assertion);
1303 }
1304
1305 void Graph::handleAssertionFailure(
1306     Node* node, const char* file, int line, const char* function, const char* assertion)
1307 {
1308     crash(*this, toCString("While handling node ", node, "\n\n"), file, line, function, assertion);
1309 }
1310
1311 void Graph::handleAssertionFailure(
1312     BasicBlock* block, const char* file, int line, const char* function, const char* assertion)
1313 {
1314     crash(*this, toCString("While handling block ", pointerDump(block), "\n\n"), file, line, function, assertion);
1315 }
1316
1317 ValueProfile* Graph::valueProfileFor(Node* node)
1318 {
1319     if (!node)
1320         return nullptr;
1321         
1322     CodeBlock* profiledBlock = baselineCodeBlockFor(node->origin.semantic);
1323         
1324     if (node->hasLocal(*this)) {
1325         if (!node->local().isArgument())
1326             return nullptr;
1327         int argument = node->local().toArgument();
1328         Node* argumentNode = m_arguments[argument];
1329         if (!argumentNode)
1330             return nullptr;
1331         if (node->variableAccessData() != argumentNode->variableAccessData())
1332             return nullptr;
1333         return profiledBlock->valueProfileForArgument(argument);
1334     }
1335         
1336     if (node->hasHeapPrediction())
1337         return profiledBlock->valueProfileForBytecodeOffset(node->origin.semantic.bytecodeIndex);
1338         
1339     return nullptr;
1340 }
1341
1342 MethodOfGettingAValueProfile Graph::methodOfGettingAValueProfileFor(Node* node)
1343 {
1344     if (!node)
1345         return MethodOfGettingAValueProfile();
1346     
1347     if (ValueProfile* valueProfile = valueProfileFor(node))
1348         return MethodOfGettingAValueProfile(valueProfile);
1349     
1350     if (node->op() == GetLocal) {
1351         CodeBlock* profiledBlock = baselineCodeBlockFor(node->origin.semantic);
1352         
1353         return MethodOfGettingAValueProfile::fromLazyOperand(
1354             profiledBlock,
1355             LazyOperandValueProfileKey(
1356                 node->origin.semantic.bytecodeIndex, node->local()));
1357     }
1358     
1359     return MethodOfGettingAValueProfile();
1360 }
1361
1362 } } // namespace JSC::DFG
1363
1364 #endif // ENABLE(DFG_JIT)