Remove old Wasm object model
[WebKit-https.git] / Source / JavaScriptCore / bytecode / CodeBlock.cpp
1 /*
2  * Copyright (C) 2008-2010, 2012-2016 Apple Inc. All rights reserved.
3  * Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca>
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1.  Redistributions of source code must retain the above copyright
10  *     notice, this list of conditions and the following disclaimer.
11  * 2.  Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution.
14  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
15  *     its contributors may be used to endorse or promote products derived
16  *     from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include "config.h"
31 #include "CodeBlock.h"
32
33 #include "ArithProfile.h"
34 #include "BasicBlockLocation.h"
35 #include "BytecodeGenerator.h"
36 #include "BytecodeLivenessAnalysis.h"
37 #include "BytecodeUseDef.h"
38 #include "CallLinkStatus.h"
39 #include "CodeBlockSet.h"
40 #include "DFGCapabilities.h"
41 #include "DFGCommon.h"
42 #include "DFGDriver.h"
43 #include "DFGJITCode.h"
44 #include "DFGWorklist.h"
45 #include "Debugger.h"
46 #include "EvalCodeBlock.h"
47 #include "FunctionCodeBlock.h"
48 #include "FunctionExecutableDump.h"
49 #include "GetPutInfo.h"
50 #include "InlineCallFrame.h"
51 #include "Interpreter.h"
52 #include "JIT.h"
53 #include "JITMathIC.h"
54 #include "JSCInlines.h"
55 #include "JSCJSValue.h"
56 #include "JSFunction.h"
57 #include "JSLexicalEnvironment.h"
58 #include "JSModuleEnvironment.h"
59 #include "LLIntData.h"
60 #include "LLIntEntrypoint.h"
61 #include "LLIntPrototypeLoadAdaptiveStructureWatchpoint.h"
62 #include "LowLevelInterpreter.h"
63 #include "ModuleProgramCodeBlock.h"
64 #include "PCToCodeOriginMap.h"
65 #include "PolymorphicAccess.h"
66 #include "ProfilerDatabase.h"
67 #include "ProgramCodeBlock.h"
68 #include "ReduceWhitespace.h"
69 #include "Repatch.h"
70 #include "SlotVisitorInlines.h"
71 #include "StackVisitor.h"
72 #include "StructureStubInfo.h"
73 #include "TypeLocationCache.h"
74 #include "TypeProfiler.h"
75 #include "UnlinkedInstructionStream.h"
76 #include "VMInlines.h"
77 #include <wtf/BagToHashMap.h>
78 #include <wtf/CommaPrinter.h>
79 #include <wtf/SimpleStats.h>
80 #include <wtf/StringExtras.h>
81 #include <wtf/StringPrintStream.h>
82 #include <wtf/text/UniquedStringImpl.h>
83
84 #if ENABLE(JIT)
85 #include "RegisterAtOffsetList.h"
86 #endif
87
88 #if ENABLE(DFG_JIT)
89 #include "DFGOperations.h"
90 #endif
91
92 #if ENABLE(FTL_JIT)
93 #include "FTLJITCode.h"
94 #endif
95
96 namespace JSC {
97
98 const ClassInfo CodeBlock::s_info = {
99     "CodeBlock", 0, 0,
100     CREATE_METHOD_TABLE(CodeBlock)
101 };
102
103 CString CodeBlock::inferredName() const
104 {
105     switch (codeType()) {
106     case GlobalCode:
107         return "<global>";
108     case EvalCode:
109         return "<eval>";
110     case FunctionCode:
111         return jsCast<FunctionExecutable*>(ownerExecutable())->inferredName().utf8();
112     case ModuleCode:
113         return "<module>";
114     default:
115         CRASH();
116         return CString("", 0);
117     }
118 }
119
120 bool CodeBlock::hasHash() const
121 {
122     return !!m_hash;
123 }
124
125 bool CodeBlock::isSafeToComputeHash() const
126 {
127     return !isCompilationThread();
128 }
129
130 CodeBlockHash CodeBlock::hash() const
131 {
132     if (!m_hash) {
133         RELEASE_ASSERT(isSafeToComputeHash());
134         m_hash = CodeBlockHash(ownerScriptExecutable()->source(), specializationKind());
135     }
136     return m_hash;
137 }
138
139 CString CodeBlock::sourceCodeForTools() const
140 {
141     if (codeType() != FunctionCode)
142         return ownerScriptExecutable()->source().toUTF8();
143     
144     SourceProvider* provider = source();
145     FunctionExecutable* executable = jsCast<FunctionExecutable*>(ownerExecutable());
146     UnlinkedFunctionExecutable* unlinked = executable->unlinkedExecutable();
147     unsigned unlinkedStartOffset = unlinked->startOffset();
148     unsigned linkedStartOffset = executable->source().startOffset();
149     int delta = linkedStartOffset - unlinkedStartOffset;
150     unsigned rangeStart = delta + unlinked->unlinkedFunctionNameStart();
151     unsigned rangeEnd = delta + unlinked->startOffset() + unlinked->sourceLength();
152     return toCString(
153         "function ",
154         provider->source().substring(rangeStart, rangeEnd - rangeStart).utf8());
155 }
156
157 CString CodeBlock::sourceCodeOnOneLine() const
158 {
159     return reduceWhitespace(sourceCodeForTools());
160 }
161
162 CString CodeBlock::hashAsStringIfPossible() const
163 {
164     if (hasHash() || isSafeToComputeHash())
165         return toCString(hash());
166     return "<no-hash>";
167 }
168
169 void CodeBlock::dumpAssumingJITType(PrintStream& out, JITCode::JITType jitType) const
170 {
171     out.print(inferredName(), "#", hashAsStringIfPossible());
172     out.print(":[", RawPointer(this), "->");
173     if (!!m_alternative)
174         out.print(RawPointer(alternative()), "->");
175     out.print(RawPointer(ownerExecutable()), ", ", jitType, codeType());
176
177     if (codeType() == FunctionCode)
178         out.print(specializationKind());
179     out.print(", ", instructionCount());
180     if (this->jitType() == JITCode::BaselineJIT && m_shouldAlwaysBeInlined)
181         out.print(" (ShouldAlwaysBeInlined)");
182     if (ownerScriptExecutable()->neverInline())
183         out.print(" (NeverInline)");
184     if (ownerScriptExecutable()->neverOptimize())
185         out.print(" (NeverOptimize)");
186     else if (ownerScriptExecutable()->neverFTLOptimize())
187         out.print(" (NeverFTLOptimize)");
188     if (ownerScriptExecutable()->didTryToEnterInLoop())
189         out.print(" (DidTryToEnterInLoop)");
190     if (ownerScriptExecutable()->isStrictMode())
191         out.print(" (StrictMode)");
192     if (m_didFailJITCompilation)
193         out.print(" (JITFail)");
194     if (this->jitType() == JITCode::BaselineJIT && m_didFailFTLCompilation)
195         out.print(" (FTLFail)");
196     if (this->jitType() == JITCode::BaselineJIT && m_hasBeenCompiledWithFTL)
197         out.print(" (HadFTLReplacement)");
198     out.print("]");
199 }
200
201 void CodeBlock::dump(PrintStream& out) const
202 {
203     dumpAssumingJITType(out, jitType());
204 }
205
206 static CString idName(int id0, const Identifier& ident)
207 {
208     return toCString(ident.impl(), "(@id", id0, ")");
209 }
210
211 CString CodeBlock::registerName(int r) const
212 {
213     if (isConstantRegisterIndex(r))
214         return constantName(r);
215
216     return toCString(VirtualRegister(r));
217 }
218
219 CString CodeBlock::constantName(int index) const
220 {
221     JSValue value = getConstant(index);
222     return toCString(value, "(", VirtualRegister(index), ")");
223 }
224
225 static CString regexpToSourceString(RegExp* regExp)
226 {
227     char postfix[5] = { '/', 0, 0, 0, 0 };
228     int index = 1;
229     if (regExp->global())
230         postfix[index++] = 'g';
231     if (regExp->ignoreCase())
232         postfix[index++] = 'i';
233     if (regExp->multiline())
234         postfix[index] = 'm';
235     if (regExp->sticky())
236         postfix[index++] = 'y';
237     if (regExp->unicode())
238         postfix[index++] = 'u';
239
240     return toCString("/", regExp->pattern().impl(), postfix);
241 }
242
243 static CString regexpName(int re, RegExp* regexp)
244 {
245     return toCString(regexpToSourceString(regexp), "(@re", re, ")");
246 }
247
248 NEVER_INLINE static const char* debugHookName(int debugHookType)
249 {
250     switch (static_cast<DebugHookType>(debugHookType)) {
251         case DidEnterCallFrame:
252             return "didEnterCallFrame";
253         case WillLeaveCallFrame:
254             return "willLeaveCallFrame";
255         case WillExecuteStatement:
256             return "willExecuteStatement";
257         case WillExecuteExpression:
258             return "willExecuteExpression";
259         case WillExecuteProgram:
260             return "willExecuteProgram";
261         case DidExecuteProgram:
262             return "didExecuteProgram";
263         case DidReachBreakpoint:
264             return "didReachBreakpoint";
265     }
266
267     RELEASE_ASSERT_NOT_REACHED();
268     return "";
269 }
270
271 void CodeBlock::printUnaryOp(PrintStream& out, ExecState* exec, int location, const Instruction*& it, const char* op)
272 {
273     int r0 = (++it)->u.operand;
274     int r1 = (++it)->u.operand;
275
276     printLocationAndOp(out, exec, location, it, op);
277     out.printf("%s, %s", registerName(r0).data(), registerName(r1).data());
278 }
279
280 void CodeBlock::printBinaryOp(PrintStream& out, ExecState* exec, int location, const Instruction*& it, const char* op)
281 {
282     int r0 = (++it)->u.operand;
283     int r1 = (++it)->u.operand;
284     int r2 = (++it)->u.operand;
285     printLocationAndOp(out, exec, location, it, op);
286     out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
287 }
288
289 void CodeBlock::printConditionalJump(PrintStream& out, ExecState* exec, const Instruction*, const Instruction*& it, int location, const char* op)
290 {
291     int r0 = (++it)->u.operand;
292     int offset = (++it)->u.operand;
293     printLocationAndOp(out, exec, location, it, op);
294     out.printf("%s, %d(->%d)", registerName(r0).data(), offset, location + offset);
295 }
296
297 void CodeBlock::printGetByIdOp(PrintStream& out, ExecState* exec, int location, const Instruction*& it)
298 {
299     const char* op;
300     switch (exec->interpreter()->getOpcodeID(it->u.opcode)) {
301     case op_get_by_id:
302         op = "get_by_id";
303         break;
304     case op_get_by_id_proto_load:
305         op = "get_by_id_proto_load";
306         break;
307     case op_get_by_id_unset:
308         op = "get_by_id_unset";
309         break;
310     case op_get_array_length:
311         op = "array_length";
312         break;
313     default:
314         RELEASE_ASSERT_NOT_REACHED();
315 #if COMPILER_QUIRK(CONSIDERS_UNREACHABLE_CODE)
316         op = 0;
317 #endif
318     }
319     int r0 = (++it)->u.operand;
320     int r1 = (++it)->u.operand;
321     int id0 = (++it)->u.operand;
322     printLocationAndOp(out, exec, location, it, op);
323     out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), idName(id0, identifier(id0)).data());
324     it += 4; // Increment up to the value profiler.
325 }
326
327 static void dumpStructure(PrintStream& out, const char* name, Structure* structure, const Identifier& ident)
328 {
329     if (!structure)
330         return;
331     
332     out.printf("%s = %p", name, structure);
333     
334     PropertyOffset offset = structure->getConcurrently(ident.impl());
335     if (offset != invalidOffset)
336         out.printf(" (offset = %d)", offset);
337 }
338
339 static void dumpChain(PrintStream& out, StructureChain* chain, const Identifier& ident)
340 {
341     out.printf("chain = %p: [", chain);
342     bool first = true;
343     for (WriteBarrier<Structure>* currentStructure = chain->head();
344          *currentStructure;
345          ++currentStructure) {
346         if (first)
347             first = false;
348         else
349             out.printf(", ");
350         dumpStructure(out, "struct", currentStructure->get(), ident);
351     }
352     out.printf("]");
353 }
354
355 void CodeBlock::printGetByIdCacheStatus(PrintStream& out, ExecState* exec, int location, const StubInfoMap& map)
356 {
357     Instruction* instruction = instructions().begin() + location;
358
359     const Identifier& ident = identifier(instruction[3].u.operand);
360     
361     UNUSED_PARAM(ident); // tell the compiler to shut up in certain platform configurations.
362     
363     if (exec->interpreter()->getOpcodeID(instruction[0].u.opcode) == op_get_array_length)
364         out.printf(" llint(array_length)");
365     else if (StructureID structureID = instruction[4].u.structureID) {
366         Structure* structure = m_vm->heap.structureIDTable().get(structureID);
367         out.printf(" llint(");
368         dumpStructure(out, "struct", structure, ident);
369         out.printf(")");
370         if (exec->interpreter()->getOpcodeID(instruction[0].u.opcode) == op_get_by_id_proto_load)
371             out.printf(" proto(%p)", instruction[6].u.pointer);
372     }
373
374 #if ENABLE(JIT)
375     if (StructureStubInfo* stubPtr = map.get(CodeOrigin(location))) {
376         StructureStubInfo& stubInfo = *stubPtr;
377         if (stubInfo.resetByGC)
378             out.print(" (Reset By GC)");
379         
380         out.printf(" jit(");
381             
382         Structure* baseStructure = nullptr;
383         PolymorphicAccess* stub = nullptr;
384             
385         switch (stubInfo.cacheType) {
386         case CacheType::GetByIdSelf:
387             out.printf("self");
388             baseStructure = stubInfo.u.byIdSelf.baseObjectStructure.get();
389             break;
390         case CacheType::Stub:
391             out.printf("stub");
392             stub = stubInfo.u.stub;
393             break;
394         case CacheType::Unset:
395             out.printf("unset");
396             break;
397         case CacheType::ArrayLength:
398             out.printf("ArrayLength");
399             break;
400         default:
401             RELEASE_ASSERT_NOT_REACHED();
402             break;
403         }
404             
405         if (baseStructure) {
406             out.printf(", ");
407             dumpStructure(out, "struct", baseStructure, ident);
408         }
409
410         if (stub)
411             out.print(", ", *stub);
412
413         out.printf(")");
414     }
415 #else
416     UNUSED_PARAM(map);
417 #endif
418 }
419
420 void CodeBlock::printPutByIdCacheStatus(PrintStream& out, int location, const StubInfoMap& map)
421 {
422     Instruction* instruction = instructions().begin() + location;
423
424     const Identifier& ident = identifier(instruction[2].u.operand);
425     
426     UNUSED_PARAM(ident); // tell the compiler to shut up in certain platform configurations.
427
428     out.print(", ", instruction[8].u.putByIdFlags);
429     
430     if (StructureID structureID = instruction[4].u.structureID) {
431         Structure* structure = m_vm->heap.structureIDTable().get(structureID);
432         out.print(" llint(");
433         if (StructureID newStructureID = instruction[6].u.structureID) {
434             Structure* newStructure = m_vm->heap.structureIDTable().get(newStructureID);
435             dumpStructure(out, "prev", structure, ident);
436             out.print(", ");
437             dumpStructure(out, "next", newStructure, ident);
438             if (StructureChain* chain = instruction[7].u.structureChain.get()) {
439                 out.print(", ");
440                 dumpChain(out, chain, ident);
441             }
442         } else
443             dumpStructure(out, "struct", structure, ident);
444         out.print(")");
445     }
446
447 #if ENABLE(JIT)
448     if (StructureStubInfo* stubPtr = map.get(CodeOrigin(location))) {
449         StructureStubInfo& stubInfo = *stubPtr;
450         if (stubInfo.resetByGC)
451             out.print(" (Reset By GC)");
452         
453         out.printf(" jit(");
454         
455         switch (stubInfo.cacheType) {
456         case CacheType::PutByIdReplace:
457             out.print("replace, ");
458             dumpStructure(out, "struct", stubInfo.u.byIdSelf.baseObjectStructure.get(), ident);
459             break;
460         case CacheType::Stub: {
461             out.print("stub, ", *stubInfo.u.stub);
462             break;
463         }
464         case CacheType::Unset:
465             out.printf("unset");
466             break;
467         default:
468             RELEASE_ASSERT_NOT_REACHED();
469             break;
470         }
471         out.printf(")");
472     }
473 #else
474     UNUSED_PARAM(map);
475 #endif
476 }
477
478 void CodeBlock::printCallOp(PrintStream& out, ExecState* exec, int location, const Instruction*& it, const char* op, CacheDumpMode cacheDumpMode, bool& hasPrintedProfiling, const CallLinkInfoMap& map)
479 {
480     int dst = (++it)->u.operand;
481     int func = (++it)->u.operand;
482     int argCount = (++it)->u.operand;
483     int registerOffset = (++it)->u.operand;
484     printLocationAndOp(out, exec, location, it, op);
485     out.print(registerName(dst), ", ", registerName(func), ", ", argCount, ", ", registerOffset);
486     out.print(" (this at ", virtualRegisterForArgument(0, -registerOffset), ")");
487     if (cacheDumpMode == DumpCaches) {
488         LLIntCallLinkInfo* callLinkInfo = it[1].u.callLinkInfo;
489         if (callLinkInfo->lastSeenCallee) {
490             out.printf(
491                 " llint(%p, exec %p)",
492                 callLinkInfo->lastSeenCallee.get(),
493                 callLinkInfo->lastSeenCallee->executable());
494         }
495 #if ENABLE(JIT)
496         if (CallLinkInfo* info = map.get(CodeOrigin(location))) {
497             JSFunction* target = info->lastSeenCallee();
498             if (target)
499                 out.printf(" jit(%p, exec %p)", target, target->executable());
500         }
501         
502         if (jitType() != JITCode::FTLJIT)
503             out.print(" status(", CallLinkStatus::computeFor(this, location, map), ")");
504 #else
505         UNUSED_PARAM(map);
506 #endif
507     }
508     ++it;
509     ++it;
510     dumpArrayProfiling(out, it, hasPrintedProfiling);
511     dumpValueProfiling(out, it, hasPrintedProfiling);
512 }
513
514 void CodeBlock::printPutByIdOp(PrintStream& out, ExecState* exec, int location, const Instruction*& it, const char* op)
515 {
516     int r0 = (++it)->u.operand;
517     int id0 = (++it)->u.operand;
518     int r1 = (++it)->u.operand;
519     printLocationAndOp(out, exec, location, it, op);
520     out.printf("%s, %s, %s", registerName(r0).data(), idName(id0, identifier(id0)).data(), registerName(r1).data());
521     it += 5;
522 }
523
524 void CodeBlock::dumpSource()
525 {
526     dumpSource(WTF::dataFile());
527 }
528
529 void CodeBlock::dumpSource(PrintStream& out)
530 {
531     ScriptExecutable* executable = ownerScriptExecutable();
532     if (executable->isFunctionExecutable()) {
533         FunctionExecutable* functionExecutable = reinterpret_cast<FunctionExecutable*>(executable);
534         StringView source = functionExecutable->source().provider()->getRange(
535             functionExecutable->parametersStartOffset(),
536             functionExecutable->typeProfilingEndOffset() + 1); // Type profiling end offset is the character before the '}'.
537         
538         out.print("function ", inferredName(), source);
539         return;
540     }
541     out.print(executable->source().view());
542 }
543
544 void CodeBlock::dumpBytecode()
545 {
546     dumpBytecode(WTF::dataFile());
547 }
548
549 void CodeBlock::dumpBytecode(PrintStream& out)
550 {
551     // We only use the ExecState* for things that don't actually lead to JS execution,
552     // like converting a JSString to a String. Hence the globalExec is appropriate.
553     ExecState* exec = m_globalObject->globalExec();
554     
555     size_t instructionCount = 0;
556
557     for (size_t i = 0; i < instructions().size(); i += opcodeLengths[exec->interpreter()->getOpcodeID(instructions()[i].u.opcode)])
558         ++instructionCount;
559
560     out.print(*this);
561     out.printf(
562         ": %lu m_instructions; %lu bytes; %d parameter(s); %d callee register(s); %d variable(s)",
563         static_cast<unsigned long>(instructions().size()),
564         static_cast<unsigned long>(instructions().size() * sizeof(Instruction)),
565         m_numParameters, m_numCalleeLocals, m_numVars);
566     out.print("; scope at ", scopeRegister());
567     out.printf("\n");
568     
569     StubInfoMap stubInfos;
570     CallLinkInfoMap callLinkInfos;
571     getStubInfoMap(stubInfos);
572     getCallLinkInfoMap(callLinkInfos);
573     
574     const Instruction* begin = instructions().begin();
575     const Instruction* end = instructions().end();
576     for (const Instruction* it = begin; it != end; ++it)
577         dumpBytecode(out, exec, begin, it, stubInfos, callLinkInfos);
578     
579     if (numberOfIdentifiers()) {
580         out.printf("\nIdentifiers:\n");
581         size_t i = 0;
582         do {
583             out.printf("  id%u = %s\n", static_cast<unsigned>(i), identifier(i).string().utf8().data());
584             ++i;
585         } while (i != numberOfIdentifiers());
586     }
587
588     if (!m_constantRegisters.isEmpty()) {
589         out.printf("\nConstants:\n");
590         size_t i = 0;
591         do {
592             const char* sourceCodeRepresentationDescription = nullptr;
593             switch (m_constantsSourceCodeRepresentation[i]) {
594             case SourceCodeRepresentation::Double:
595                 sourceCodeRepresentationDescription = ": in source as double";
596                 break;
597             case SourceCodeRepresentation::Integer:
598                 sourceCodeRepresentationDescription = ": in source as integer";
599                 break;
600             case SourceCodeRepresentation::Other:
601                 sourceCodeRepresentationDescription = "";
602                 break;
603             }
604             out.printf("   k%u = %s%s\n", static_cast<unsigned>(i), toCString(m_constantRegisters[i].get()).data(), sourceCodeRepresentationDescription);
605             ++i;
606         } while (i < m_constantRegisters.size());
607     }
608
609     if (size_t count = m_unlinkedCode->numberOfRegExps()) {
610         out.printf("\nm_regexps:\n");
611         size_t i = 0;
612         do {
613             out.printf("  re%u = %s\n", static_cast<unsigned>(i), regexpToSourceString(m_unlinkedCode->regexp(i)).data());
614             ++i;
615         } while (i < count);
616     }
617
618     dumpExceptionHandlers(out);
619     
620     if (m_rareData && !m_rareData->m_switchJumpTables.isEmpty()) {
621         out.printf("Switch Jump Tables:\n");
622         unsigned i = 0;
623         do {
624             out.printf("  %1d = {\n", i);
625             int entry = 0;
626             Vector<int32_t>::const_iterator end = m_rareData->m_switchJumpTables[i].branchOffsets.end();
627             for (Vector<int32_t>::const_iterator iter = m_rareData->m_switchJumpTables[i].branchOffsets.begin(); iter != end; ++iter, ++entry) {
628                 if (!*iter)
629                     continue;
630                 out.printf("\t\t%4d => %04d\n", entry + m_rareData->m_switchJumpTables[i].min, *iter);
631             }
632             out.printf("      }\n");
633             ++i;
634         } while (i < m_rareData->m_switchJumpTables.size());
635     }
636     
637     if (m_rareData && !m_rareData->m_stringSwitchJumpTables.isEmpty()) {
638         out.printf("\nString Switch Jump Tables:\n");
639         unsigned i = 0;
640         do {
641             out.printf("  %1d = {\n", i);
642             StringJumpTable::StringOffsetTable::const_iterator end = m_rareData->m_stringSwitchJumpTables[i].offsetTable.end();
643             for (StringJumpTable::StringOffsetTable::const_iterator iter = m_rareData->m_stringSwitchJumpTables[i].offsetTable.begin(); iter != end; ++iter)
644                 out.printf("\t\t\"%s\" => %04d\n", iter->key->utf8().data(), iter->value.branchOffset);
645             out.printf("      }\n");
646             ++i;
647         } while (i < m_rareData->m_stringSwitchJumpTables.size());
648     }
649
650     out.printf("\n");
651 }
652
653 void CodeBlock::dumpExceptionHandlers(PrintStream& out)
654 {
655     if (m_rareData && !m_rareData->m_exceptionHandlers.isEmpty()) {
656         out.printf("\nException Handlers:\n");
657         unsigned i = 0;
658         do {
659             HandlerInfo& handler = m_rareData->m_exceptionHandlers[i];
660             out.printf("\t %d: { start: [%4d] end: [%4d] target: [%4d] } %s\n",
661                 i + 1, handler.start, handler.end, handler.target, handler.typeName());
662             ++i;
663         } while (i < m_rareData->m_exceptionHandlers.size());
664     }
665 }
666
667 void CodeBlock::beginDumpProfiling(PrintStream& out, bool& hasPrintedProfiling)
668 {
669     if (hasPrintedProfiling) {
670         out.print("; ");
671         return;
672     }
673     
674     out.print("    ");
675     hasPrintedProfiling = true;
676 }
677
678 void CodeBlock::dumpValueProfiling(PrintStream& out, const Instruction*& it, bool& hasPrintedProfiling)
679 {
680     ConcurrentJSLocker locker(m_lock);
681     
682     ++it;
683     CString description = it->u.profile->briefDescription(locker);
684     if (!description.length())
685         return;
686     beginDumpProfiling(out, hasPrintedProfiling);
687     out.print(description);
688 }
689
690 void CodeBlock::dumpArrayProfiling(PrintStream& out, const Instruction*& it, bool& hasPrintedProfiling)
691 {
692     ConcurrentJSLocker locker(m_lock);
693     
694     ++it;
695     if (!it->u.arrayProfile)
696         return;
697     CString description = it->u.arrayProfile->briefDescription(locker, this);
698     if (!description.length())
699         return;
700     beginDumpProfiling(out, hasPrintedProfiling);
701     out.print(description);
702 }
703
704 void CodeBlock::dumpRareCaseProfile(PrintStream& out, const char* name, RareCaseProfile* profile, bool& hasPrintedProfiling)
705 {
706     if (!profile || !profile->m_counter)
707         return;
708
709     beginDumpProfiling(out, hasPrintedProfiling);
710     out.print(name, profile->m_counter);
711 }
712
713 void CodeBlock::dumpArithProfile(PrintStream& out, ArithProfile* profile, bool& hasPrintedProfiling)
714 {
715     if (!profile)
716         return;
717     
718     beginDumpProfiling(out, hasPrintedProfiling);
719     out.print("results: ", *profile);
720 }
721
722 void CodeBlock::printLocationAndOp(PrintStream& out, ExecState*, int location, const Instruction*&, const char* op)
723 {
724     out.printf("[%4d] %-17s ", location, op);
725 }
726
727 void CodeBlock::printLocationOpAndRegisterOperand(PrintStream& out, ExecState* exec, int location, const Instruction*& it, const char* op, int operand)
728 {
729     printLocationAndOp(out, exec, location, it, op);
730     out.printf("%s", registerName(operand).data());
731 }
732
733 void CodeBlock::dumpBytecode(
734     PrintStream& out, ExecState* exec, const Instruction* begin, const Instruction*& it,
735     const StubInfoMap& stubInfos, const CallLinkInfoMap& callLinkInfos)
736 {
737     int location = it - begin;
738     bool hasPrintedProfiling = false;
739     OpcodeID opcode = exec->interpreter()->getOpcodeID(it->u.opcode);
740     switch (opcode) {
741         case op_enter: {
742             printLocationAndOp(out, exec, location, it, "enter");
743             break;
744         }
745         case op_get_scope: {
746             int r0 = (++it)->u.operand;
747             printLocationOpAndRegisterOperand(out, exec, location, it, "get_scope", r0);
748             break;
749         }
750         case op_create_direct_arguments: {
751             int r0 = (++it)->u.operand;
752             printLocationAndOp(out, exec, location, it, "create_direct_arguments");
753             out.printf("%s", registerName(r0).data());
754             break;
755         }
756         case op_create_scoped_arguments: {
757             int r0 = (++it)->u.operand;
758             int r1 = (++it)->u.operand;
759             printLocationAndOp(out, exec, location, it, "create_scoped_arguments");
760             out.printf("%s, %s", registerName(r0).data(), registerName(r1).data());
761             break;
762         }
763         case op_create_cloned_arguments: {
764             int r0 = (++it)->u.operand;
765             printLocationAndOp(out, exec, location, it, "create_cloned_arguments");
766             out.printf("%s", registerName(r0).data());
767             break;
768         }
769         case op_argument_count: {
770             int r0 = (++it)->u.operand;
771             printLocationOpAndRegisterOperand(out, exec, location, it, "argument_count", r0);
772             break;
773         }
774         case op_get_argument: {
775             int r0 = (++it)->u.operand;
776             int index = (++it)->u.operand;
777             printLocationOpAndRegisterOperand(out, exec, location, it, "argument", r0);
778             out.printf(", %d", index);
779             dumpValueProfiling(out, it, hasPrintedProfiling);
780             break;
781         }
782         case op_create_rest: {
783             int r0 = (++it)->u.operand;
784             int r1 = (++it)->u.operand;
785             unsigned argumentOffset = (++it)->u.unsignedValue;
786             printLocationAndOp(out, exec, location, it, "create_rest");
787             out.printf("%s, %s, ", registerName(r0).data(), registerName(r1).data());
788             out.printf("ArgumentsOffset: %u", argumentOffset);
789             break;
790         }
791         case op_get_rest_length: {
792             int r0 = (++it)->u.operand;
793             printLocationAndOp(out, exec, location, it, "get_rest_length");
794             out.printf("%s, ", registerName(r0).data());
795             unsigned argumentOffset = (++it)->u.unsignedValue;
796             out.printf("ArgumentsOffset: %u", argumentOffset);
797             break;
798         }
799         case op_create_this: {
800             int r0 = (++it)->u.operand;
801             int r1 = (++it)->u.operand;
802             unsigned inferredInlineCapacity = (++it)->u.operand;
803             unsigned cachedFunction = (++it)->u.operand;
804             printLocationAndOp(out, exec, location, it, "create_this");
805             out.printf("%s, %s, %u, %u", registerName(r0).data(), registerName(r1).data(), inferredInlineCapacity, cachedFunction);
806             break;
807         }
808         case op_to_this: {
809             int r0 = (++it)->u.operand;
810             printLocationOpAndRegisterOperand(out, exec, location, it, "to_this", r0);
811             Structure* structure = (++it)->u.structure.get();
812             if (structure)
813                 out.print(", cache(struct = ", RawPointer(structure), ")");
814             out.print(", ", (++it)->u.toThisStatus);
815             break;
816         }
817         case op_check_tdz: {
818             int r0 = (++it)->u.operand;
819             printLocationOpAndRegisterOperand(out, exec, location, it, "op_check_tdz", r0);
820             break;
821         }
822         case op_new_object: {
823             int r0 = (++it)->u.operand;
824             unsigned inferredInlineCapacity = (++it)->u.operand;
825             printLocationAndOp(out, exec, location, it, "new_object");
826             out.printf("%s, %u", registerName(r0).data(), inferredInlineCapacity);
827             ++it; // Skip object allocation profile.
828             break;
829         }
830         case op_new_array: {
831             int dst = (++it)->u.operand;
832             int argv = (++it)->u.operand;
833             int argc = (++it)->u.operand;
834             printLocationAndOp(out, exec, location, it, "new_array");
835             out.printf("%s, %s, %d", registerName(dst).data(), registerName(argv).data(), argc);
836             ++it; // Skip array allocation profile.
837             break;
838         }
839         case op_new_array_with_spread: {
840             int dst = (++it)->u.operand;
841             int argv = (++it)->u.operand;
842             int argc = (++it)->u.operand;
843             printLocationAndOp(out, exec, location, it, "new_array_with_spread");
844             out.printf("%s, %s, %d, ", registerName(dst).data(), registerName(argv).data(), argc);
845             unsigned bitVectorIndex = (++it)->u.unsignedValue;
846             const BitVector& bitVector = m_unlinkedCode->bitVector(bitVectorIndex);
847             out.print("BitVector:", bitVectorIndex, ":");
848             for (unsigned i = 0; i < static_cast<unsigned>(argc); i++) {
849                 if (bitVector.get(i))
850                     out.print("1");
851                 else
852                     out.print("0");
853             }
854             break;
855         }
856         case op_spread: {
857             int dst = (++it)->u.operand;
858             int arg = (++it)->u.operand;
859             printLocationAndOp(out, exec, location, it, "spread");
860             out.printf("%s, %s", registerName(dst).data(), registerName(arg).data());
861             break;
862         }
863         case op_new_array_with_size: {
864             int dst = (++it)->u.operand;
865             int length = (++it)->u.operand;
866             printLocationAndOp(out, exec, location, it, "new_array_with_size");
867             out.printf("%s, %s", registerName(dst).data(), registerName(length).data());
868             ++it; // Skip array allocation profile.
869             break;
870         }
871         case op_new_array_buffer: {
872             int dst = (++it)->u.operand;
873             int argv = (++it)->u.operand;
874             int argc = (++it)->u.operand;
875             printLocationAndOp(out, exec, location, it, "new_array_buffer");
876             out.printf("%s, %d, %d", registerName(dst).data(), argv, argc);
877             ++it; // Skip array allocation profile.
878             break;
879         }
880         case op_new_regexp: {
881             int r0 = (++it)->u.operand;
882             int re0 = (++it)->u.operand;
883             printLocationAndOp(out, exec, location, it, "new_regexp");
884             out.printf("%s, ", registerName(r0).data());
885             if (r0 >=0 && r0 < (int)m_unlinkedCode->numberOfRegExps())
886                 out.printf("%s", regexpName(re0, regexp(re0)).data());
887             else
888                 out.printf("bad_regexp(%d)", re0);
889             break;
890         }
891         case op_mov: {
892             int r0 = (++it)->u.operand;
893             int r1 = (++it)->u.operand;
894             printLocationAndOp(out, exec, location, it, "mov");
895             out.printf("%s, %s", registerName(r0).data(), registerName(r1).data());
896             break;
897         }
898         case op_profile_type: {
899             int r0 = (++it)->u.operand;
900             ++it;
901             ++it;
902             ++it;
903             ++it;
904             printLocationAndOp(out, exec, location, it, "op_profile_type");
905             out.printf("%s", registerName(r0).data());
906             break;
907         }
908         case op_profile_control_flow: {
909             BasicBlockLocation* basicBlockLocation = (++it)->u.basicBlockLocation;
910             printLocationAndOp(out, exec, location, it, "profile_control_flow");
911             out.printf("[%d, %d]", basicBlockLocation->startOffset(), basicBlockLocation->endOffset());
912             break;
913         }
914         case op_not: {
915             printUnaryOp(out, exec, location, it, "not");
916             break;
917         }
918         case op_eq: {
919             printBinaryOp(out, exec, location, it, "eq");
920             break;
921         }
922         case op_eq_null: {
923             printUnaryOp(out, exec, location, it, "eq_null");
924             break;
925         }
926         case op_neq: {
927             printBinaryOp(out, exec, location, it, "neq");
928             break;
929         }
930         case op_neq_null: {
931             printUnaryOp(out, exec, location, it, "neq_null");
932             break;
933         }
934         case op_stricteq: {
935             printBinaryOp(out, exec, location, it, "stricteq");
936             break;
937         }
938         case op_nstricteq: {
939             printBinaryOp(out, exec, location, it, "nstricteq");
940             break;
941         }
942         case op_less: {
943             printBinaryOp(out, exec, location, it, "less");
944             break;
945         }
946         case op_lesseq: {
947             printBinaryOp(out, exec, location, it, "lesseq");
948             break;
949         }
950         case op_greater: {
951             printBinaryOp(out, exec, location, it, "greater");
952             break;
953         }
954         case op_greatereq: {
955             printBinaryOp(out, exec, location, it, "greatereq");
956             break;
957         }
958         case op_inc: {
959             int r0 = (++it)->u.operand;
960             printLocationOpAndRegisterOperand(out, exec, location, it, "inc", r0);
961             break;
962         }
963         case op_dec: {
964             int r0 = (++it)->u.operand;
965             printLocationOpAndRegisterOperand(out, exec, location, it, "dec", r0);
966             break;
967         }
968         case op_to_number: {
969             printUnaryOp(out, exec, location, it, "to_number");
970             dumpValueProfiling(out, it, hasPrintedProfiling);
971             break;
972         }
973         case op_to_string: {
974             printUnaryOp(out, exec, location, it, "to_string");
975             break;
976         }
977         case op_negate: {
978             printUnaryOp(out, exec, location, it, "negate");
979             ++it; // op_negate has an extra operand for the ArithProfile.
980             break;
981         }
982         case op_add: {
983             printBinaryOp(out, exec, location, it, "add");
984             ++it;
985             break;
986         }
987         case op_mul: {
988             printBinaryOp(out, exec, location, it, "mul");
989             ++it;
990             break;
991         }
992         case op_div: {
993             printBinaryOp(out, exec, location, it, "div");
994             ++it;
995             break;
996         }
997         case op_mod: {
998             printBinaryOp(out, exec, location, it, "mod");
999             break;
1000         }
1001         case op_pow: {
1002             printBinaryOp(out, exec, location, it, "pow");
1003             break;
1004         }
1005         case op_sub: {
1006             printBinaryOp(out, exec, location, it, "sub");
1007             ++it;
1008             break;
1009         }
1010         case op_lshift: {
1011             printBinaryOp(out, exec, location, it, "lshift");
1012             break;            
1013         }
1014         case op_rshift: {
1015             printBinaryOp(out, exec, location, it, "rshift");
1016             break;
1017         }
1018         case op_urshift: {
1019             printBinaryOp(out, exec, location, it, "urshift");
1020             break;
1021         }
1022         case op_bitand: {
1023             printBinaryOp(out, exec, location, it, "bitand");
1024             ++it;
1025             break;
1026         }
1027         case op_bitxor: {
1028             printBinaryOp(out, exec, location, it, "bitxor");
1029             ++it;
1030             break;
1031         }
1032         case op_bitor: {
1033             printBinaryOp(out, exec, location, it, "bitor");
1034             ++it;
1035             break;
1036         }
1037         case op_overrides_has_instance: {
1038             int r0 = (++it)->u.operand;
1039             int r1 = (++it)->u.operand;
1040             int r2 = (++it)->u.operand;
1041             printLocationAndOp(out, exec, location, it, "overrides_has_instance");
1042             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
1043             break;
1044         }
1045         case op_instanceof: {
1046             int r0 = (++it)->u.operand;
1047             int r1 = (++it)->u.operand;
1048             int r2 = (++it)->u.operand;
1049             printLocationAndOp(out, exec, location, it, "instanceof");
1050             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
1051             break;
1052         }
1053         case op_instanceof_custom: {
1054             int r0 = (++it)->u.operand;
1055             int r1 = (++it)->u.operand;
1056             int r2 = (++it)->u.operand;
1057             int r3 = (++it)->u.operand;
1058             printLocationAndOp(out, exec, location, it, "instanceof_custom");
1059             out.printf("%s, %s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data(), registerName(r3).data());
1060             break;
1061         }
1062         case op_unsigned: {
1063             printUnaryOp(out, exec, location, it, "unsigned");
1064             break;
1065         }
1066         case op_typeof: {
1067             printUnaryOp(out, exec, location, it, "typeof");
1068             break;
1069         }
1070         case op_is_empty: {
1071             printUnaryOp(out, exec, location, it, "is_empty");
1072             break;
1073         }
1074         case op_is_undefined: {
1075             printUnaryOp(out, exec, location, it, "is_undefined");
1076             break;
1077         }
1078         case op_is_boolean: {
1079             printUnaryOp(out, exec, location, it, "is_boolean");
1080             break;
1081         }
1082         case op_is_number: {
1083             printUnaryOp(out, exec, location, it, "is_number");
1084             break;
1085         }
1086         case op_is_cell_with_type: {
1087             int r0 = (++it)->u.operand;
1088             int r1 = (++it)->u.operand;
1089             int type = (++it)->u.operand;
1090             printLocationAndOp(out, exec, location, it, "is_cell_with_type");
1091             out.printf("%s, %s, %d", registerName(r0).data(), registerName(r1).data(), type);
1092             break;
1093         }
1094         case op_is_object: {
1095             printUnaryOp(out, exec, location, it, "is_object");
1096             break;
1097         }
1098         case op_is_object_or_null: {
1099             printUnaryOp(out, exec, location, it, "is_object_or_null");
1100             break;
1101         }
1102         case op_is_function: {
1103             printUnaryOp(out, exec, location, it, "is_function");
1104             break;
1105         }
1106         case op_in: {
1107             printBinaryOp(out, exec, location, it, "in");
1108             break;
1109         }
1110         case op_try_get_by_id: {
1111             int r0 = (++it)->u.operand;
1112             int r1 = (++it)->u.operand;
1113             int id0 = (++it)->u.operand;
1114             printLocationAndOp(out, exec, location, it, "try_get_by_id");
1115             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), idName(id0, identifier(id0)).data());
1116             dumpValueProfiling(out, it, hasPrintedProfiling);
1117             break;
1118         }
1119         case op_get_by_id:
1120         case op_get_by_id_proto_load:
1121         case op_get_by_id_unset:
1122         case op_get_array_length: {
1123             printGetByIdOp(out, exec, location, it);
1124             printGetByIdCacheStatus(out, exec, location, stubInfos);
1125             dumpValueProfiling(out, it, hasPrintedProfiling);
1126             break;
1127         }
1128         case op_get_by_id_with_this: {
1129             printLocationAndOp(out, exec, location, it, "get_by_id_with_this");
1130             int r0 = (++it)->u.operand;
1131             int r1 = (++it)->u.operand;
1132             int r2 = (++it)->u.operand;
1133             int id0 = (++it)->u.operand;
1134             out.printf("%s, %s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data(), idName(id0, identifier(id0)).data());
1135             dumpValueProfiling(out, it, hasPrintedProfiling);
1136             break;
1137         }
1138         case op_get_by_val_with_this: {
1139             int r0 = (++it)->u.operand;
1140             int r1 = (++it)->u.operand;
1141             int r2 = (++it)->u.operand;
1142             int r3 = (++it)->u.operand;
1143             printLocationAndOp(out, exec, location, it, "get_by_val_with_this");
1144             out.printf("%s, %s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data(), registerName(r3).data());
1145             dumpValueProfiling(out, it, hasPrintedProfiling);
1146             break;
1147         }
1148         case op_put_by_id: {
1149             printPutByIdOp(out, exec, location, it, "put_by_id");
1150             printPutByIdCacheStatus(out, location, stubInfos);
1151             break;
1152         }
1153         case op_put_by_id_with_this: {
1154             int r0 = (++it)->u.operand;
1155             int r1 = (++it)->u.operand;
1156             int id0 = (++it)->u.operand;
1157             int r2 = (++it)->u.operand;
1158             printLocationAndOp(out, exec, location, it, "put_by_id_with_this");
1159             out.printf("%s, %s, %s, %s", registerName(r0).data(), registerName(r1).data(), idName(id0, identifier(id0)).data(), registerName(r2).data());
1160             break;
1161         }
1162         case op_put_by_val_with_this: {
1163             int r0 = (++it)->u.operand;
1164             int r1 = (++it)->u.operand;
1165             int r2 = (++it)->u.operand;
1166             int r3 = (++it)->u.operand;
1167             printLocationAndOp(out, exec, location, it, "put_by_val_with_this");
1168             out.printf("%s, %s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data(), registerName(r3).data());
1169             break;
1170         }
1171         case op_put_getter_by_id: {
1172             int r0 = (++it)->u.operand;
1173             int id0 = (++it)->u.operand;
1174             int n0 = (++it)->u.operand;
1175             int r1 = (++it)->u.operand;
1176             printLocationAndOp(out, exec, location, it, "put_getter_by_id");
1177             out.printf("%s, %s, %d, %s", registerName(r0).data(), idName(id0, identifier(id0)).data(), n0, registerName(r1).data());
1178             break;
1179         }
1180         case op_put_setter_by_id: {
1181             int r0 = (++it)->u.operand;
1182             int id0 = (++it)->u.operand;
1183             int n0 = (++it)->u.operand;
1184             int r1 = (++it)->u.operand;
1185             printLocationAndOp(out, exec, location, it, "put_setter_by_id");
1186             out.printf("%s, %s, %d, %s", registerName(r0).data(), idName(id0, identifier(id0)).data(), n0, registerName(r1).data());
1187             break;
1188         }
1189         case op_put_getter_setter_by_id: {
1190             int r0 = (++it)->u.operand;
1191             int id0 = (++it)->u.operand;
1192             int n0 = (++it)->u.operand;
1193             int r1 = (++it)->u.operand;
1194             int r2 = (++it)->u.operand;
1195             printLocationAndOp(out, exec, location, it, "put_getter_setter_by_id");
1196             out.printf("%s, %s, %d, %s, %s", registerName(r0).data(), idName(id0, identifier(id0)).data(), n0, registerName(r1).data(), registerName(r2).data());
1197             break;
1198         }
1199         case op_put_getter_by_val: {
1200             int r0 = (++it)->u.operand;
1201             int r1 = (++it)->u.operand;
1202             int n0 = (++it)->u.operand;
1203             int r2 = (++it)->u.operand;
1204             printLocationAndOp(out, exec, location, it, "put_getter_by_val");
1205             out.printf("%s, %s, %d, %s", registerName(r0).data(), registerName(r1).data(), n0, registerName(r2).data());
1206             break;
1207         }
1208         case op_put_setter_by_val: {
1209             int r0 = (++it)->u.operand;
1210             int r1 = (++it)->u.operand;
1211             int n0 = (++it)->u.operand;
1212             int r2 = (++it)->u.operand;
1213             printLocationAndOp(out, exec, location, it, "put_setter_by_val");
1214             out.printf("%s, %s, %d, %s", registerName(r0).data(), registerName(r1).data(), n0, registerName(r2).data());
1215             break;
1216         }
1217         case op_define_data_property: {
1218             int r0 = (++it)->u.operand;
1219             int r1 = (++it)->u.operand;
1220             int r2 = (++it)->u.operand;
1221             int r3 = (++it)->u.operand;
1222             printLocationAndOp(out, exec, location, it, "define_data_property");
1223             out.printf("%s, %s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data(), registerName(r3).data());
1224             break;
1225         }
1226         case op_define_accessor_property: {
1227             int r0 = (++it)->u.operand;
1228             int r1 = (++it)->u.operand;
1229             int r2 = (++it)->u.operand;
1230             int r3 = (++it)->u.operand;
1231             int r4 = (++it)->u.operand;
1232             printLocationAndOp(out, exec, location, it, "define_accessor_property");
1233             out.printf("%s, %s, %s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data(), registerName(r3).data(), registerName(r4).data());
1234             break;
1235         }
1236         case op_del_by_id: {
1237             int r0 = (++it)->u.operand;
1238             int r1 = (++it)->u.operand;
1239             int id0 = (++it)->u.operand;
1240             printLocationAndOp(out, exec, location, it, "del_by_id");
1241             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), idName(id0, identifier(id0)).data());
1242             break;
1243         }
1244         case op_get_by_val: {
1245             int r0 = (++it)->u.operand;
1246             int r1 = (++it)->u.operand;
1247             int r2 = (++it)->u.operand;
1248             printLocationAndOp(out, exec, location, it, "get_by_val");
1249             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
1250             dumpArrayProfiling(out, it, hasPrintedProfiling);
1251             dumpValueProfiling(out, it, hasPrintedProfiling);
1252             break;
1253         }
1254         case op_put_by_val: {
1255             int r0 = (++it)->u.operand;
1256             int r1 = (++it)->u.operand;
1257             int r2 = (++it)->u.operand;
1258             printLocationAndOp(out, exec, location, it, "put_by_val");
1259             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
1260             dumpArrayProfiling(out, it, hasPrintedProfiling);
1261             break;
1262         }
1263         case op_put_by_val_direct: {
1264             int r0 = (++it)->u.operand;
1265             int r1 = (++it)->u.operand;
1266             int r2 = (++it)->u.operand;
1267             printLocationAndOp(out, exec, location, it, "put_by_val_direct");
1268             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
1269             dumpArrayProfiling(out, it, hasPrintedProfiling);
1270             break;
1271         }
1272         case op_del_by_val: {
1273             int r0 = (++it)->u.operand;
1274             int r1 = (++it)->u.operand;
1275             int r2 = (++it)->u.operand;
1276             printLocationAndOp(out, exec, location, it, "del_by_val");
1277             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
1278             break;
1279         }
1280         case op_put_by_index: {
1281             int r0 = (++it)->u.operand;
1282             unsigned n0 = (++it)->u.operand;
1283             int r1 = (++it)->u.operand;
1284             printLocationAndOp(out, exec, location, it, "put_by_index");
1285             out.printf("%s, %u, %s", registerName(r0).data(), n0, registerName(r1).data());
1286             break;
1287         }
1288         case op_jmp: {
1289             int offset = (++it)->u.operand;
1290             printLocationAndOp(out, exec, location, it, "jmp");
1291             out.printf("%d(->%d)", offset, location + offset);
1292             break;
1293         }
1294         case op_jtrue: {
1295             printConditionalJump(out, exec, begin, it, location, "jtrue");
1296             break;
1297         }
1298         case op_jfalse: {
1299             printConditionalJump(out, exec, begin, it, location, "jfalse");
1300             break;
1301         }
1302         case op_jeq_null: {
1303             printConditionalJump(out, exec, begin, it, location, "jeq_null");
1304             break;
1305         }
1306         case op_jneq_null: {
1307             printConditionalJump(out, exec, begin, it, location, "jneq_null");
1308             break;
1309         }
1310         case op_jneq_ptr: {
1311             int r0 = (++it)->u.operand;
1312             Special::Pointer pointer = (++it)->u.specialPointer;
1313             int offset = (++it)->u.operand;
1314             printLocationAndOp(out, exec, location, it, "jneq_ptr");
1315             out.printf("%s, %d (%p), %d(->%d)", registerName(r0).data(), pointer, m_globalObject->actualPointerFor(pointer), offset, location + offset);
1316             ++it;
1317             break;
1318         }
1319         case op_jless: {
1320             int r0 = (++it)->u.operand;
1321             int r1 = (++it)->u.operand;
1322             int offset = (++it)->u.operand;
1323             printLocationAndOp(out, exec, location, it, "jless");
1324             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1325             break;
1326         }
1327         case op_jlesseq: {
1328             int r0 = (++it)->u.operand;
1329             int r1 = (++it)->u.operand;
1330             int offset = (++it)->u.operand;
1331             printLocationAndOp(out, exec, location, it, "jlesseq");
1332             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1333             break;
1334         }
1335         case op_jgreater: {
1336             int r0 = (++it)->u.operand;
1337             int r1 = (++it)->u.operand;
1338             int offset = (++it)->u.operand;
1339             printLocationAndOp(out, exec, location, it, "jgreater");
1340             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1341             break;
1342         }
1343         case op_jgreatereq: {
1344             int r0 = (++it)->u.operand;
1345             int r1 = (++it)->u.operand;
1346             int offset = (++it)->u.operand;
1347             printLocationAndOp(out, exec, location, it, "jgreatereq");
1348             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1349             break;
1350         }
1351         case op_jnless: {
1352             int r0 = (++it)->u.operand;
1353             int r1 = (++it)->u.operand;
1354             int offset = (++it)->u.operand;
1355             printLocationAndOp(out, exec, location, it, "jnless");
1356             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1357             break;
1358         }
1359         case op_jnlesseq: {
1360             int r0 = (++it)->u.operand;
1361             int r1 = (++it)->u.operand;
1362             int offset = (++it)->u.operand;
1363             printLocationAndOp(out, exec, location, it, "jnlesseq");
1364             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1365             break;
1366         }
1367         case op_jngreater: {
1368             int r0 = (++it)->u.operand;
1369             int r1 = (++it)->u.operand;
1370             int offset = (++it)->u.operand;
1371             printLocationAndOp(out, exec, location, it, "jngreater");
1372             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1373             break;
1374         }
1375         case op_jngreatereq: {
1376             int r0 = (++it)->u.operand;
1377             int r1 = (++it)->u.operand;
1378             int offset = (++it)->u.operand;
1379             printLocationAndOp(out, exec, location, it, "jngreatereq");
1380             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1381             break;
1382         }
1383         case op_loop_hint: {
1384             printLocationAndOp(out, exec, location, it, "loop_hint");
1385             break;
1386         }
1387         case op_watchdog: {
1388             printLocationAndOp(out, exec, location, it, "watchdog");
1389             break;
1390         }
1391         case op_log_shadow_chicken_prologue: {
1392             int r0 = (++it)->u.operand;
1393             printLocationAndOp(out, exec, location, it, "log_shadow_chicken_prologue");
1394             out.printf("%s", registerName(r0).data());
1395             break;
1396         }
1397         case op_log_shadow_chicken_tail: {
1398             int r0 = (++it)->u.operand;
1399             int r1 = (++it)->u.operand;
1400             printLocationAndOp(out, exec, location, it, "log_shadow_chicken_tail");
1401             out.printf("%s, %s", registerName(r0).data(), registerName(r1).data());
1402             break;
1403         }
1404         case op_switch_imm: {
1405             int tableIndex = (++it)->u.operand;
1406             int defaultTarget = (++it)->u.operand;
1407             int scrutineeRegister = (++it)->u.operand;
1408             printLocationAndOp(out, exec, location, it, "switch_imm");
1409             out.printf("%d, %d(->%d), %s", tableIndex, defaultTarget, location + defaultTarget, registerName(scrutineeRegister).data());
1410             break;
1411         }
1412         case op_switch_char: {
1413             int tableIndex = (++it)->u.operand;
1414             int defaultTarget = (++it)->u.operand;
1415             int scrutineeRegister = (++it)->u.operand;
1416             printLocationAndOp(out, exec, location, it, "switch_char");
1417             out.printf("%d, %d(->%d), %s", tableIndex, defaultTarget, location + defaultTarget, registerName(scrutineeRegister).data());
1418             break;
1419         }
1420         case op_switch_string: {
1421             int tableIndex = (++it)->u.operand;
1422             int defaultTarget = (++it)->u.operand;
1423             int scrutineeRegister = (++it)->u.operand;
1424             printLocationAndOp(out, exec, location, it, "switch_string");
1425             out.printf("%d, %d(->%d), %s", tableIndex, defaultTarget, location + defaultTarget, registerName(scrutineeRegister).data());
1426             break;
1427         }
1428         case op_new_func: {
1429             int r0 = (++it)->u.operand;
1430             int r1 = (++it)->u.operand;
1431             int f0 = (++it)->u.operand;
1432             printLocationAndOp(out, exec, location, it, "new_func");
1433             out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1434             break;
1435         }
1436         case op_new_generator_func: {
1437             int r0 = (++it)->u.operand;
1438             int r1 = (++it)->u.operand;
1439             int f0 = (++it)->u.operand;
1440             printLocationAndOp(out, exec, location, it, "new_generator_func");
1441             out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1442             break;
1443         }
1444         case op_new_async_func: {
1445             int r0 = (++it)->u.operand;
1446             int r1 = (++it)->u.operand;
1447             int f0 = (++it)->u.operand;
1448             printLocationAndOp(out, exec, location, it, "new_async_func");
1449             out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1450             break;
1451         }
1452         case op_new_func_exp: {
1453             int r0 = (++it)->u.operand;
1454             int r1 = (++it)->u.operand;
1455             int f0 = (++it)->u.operand;
1456             printLocationAndOp(out, exec, location, it, "new_func_exp");
1457             out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1458             break;
1459         }
1460         case op_new_generator_func_exp: {
1461             int r0 = (++it)->u.operand;
1462             int r1 = (++it)->u.operand;
1463             int f0 = (++it)->u.operand;
1464             printLocationAndOp(out, exec, location, it, "new_generator_func_exp");
1465             out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1466             break;
1467         }
1468         case op_new_async_func_exp: {
1469             int r0 = (++it)->u.operand;
1470             int r1 = (++it)->u.operand;
1471             int f0 = (++it)->u.operand;
1472             printLocationAndOp(out, exec, location, it, "new_async_func_exp");
1473             out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1474             break;
1475         }
1476         case op_set_function_name: {
1477             int funcReg = (++it)->u.operand;
1478             int nameReg = (++it)->u.operand;
1479             printLocationAndOp(out, exec, location, it, "set_function_name");
1480             out.printf("%s, %s", registerName(funcReg).data(), registerName(nameReg).data());
1481             break;
1482         }
1483         case op_call: {
1484             printCallOp(out, exec, location, it, "call", DumpCaches, hasPrintedProfiling, callLinkInfos);
1485             break;
1486         }
1487         case op_tail_call: {
1488             printCallOp(out, exec, location, it, "tail_call", DumpCaches, hasPrintedProfiling, callLinkInfos);
1489             break;
1490         }
1491         case op_call_eval: {
1492             printCallOp(out, exec, location, it, "call_eval", DontDumpCaches, hasPrintedProfiling, callLinkInfos);
1493             break;
1494         }
1495             
1496         case op_construct_varargs:
1497         case op_call_varargs:
1498         case op_tail_call_varargs:
1499         case op_tail_call_forward_arguments: {
1500             int result = (++it)->u.operand;
1501             int callee = (++it)->u.operand;
1502             int thisValue = (++it)->u.operand;
1503             int arguments = (++it)->u.operand;
1504             int firstFreeRegister = (++it)->u.operand;
1505             int varArgOffset = (++it)->u.operand;
1506             ++it;
1507             const char* opName;
1508             if (opcode == op_call_varargs)
1509                 opName = "call_varargs";
1510             else if (opcode == op_construct_varargs)
1511                 opName = "construct_varargs";
1512             else if (opcode == op_tail_call_varargs)
1513                 opName = "tail_call_varargs";
1514             else if (opcode == op_tail_call_forward_arguments)
1515                 opName = "tail_call_forward_arguments";
1516             else
1517                 RELEASE_ASSERT_NOT_REACHED();
1518
1519             printLocationAndOp(out, exec, location, it, opName);
1520             out.printf("%s, %s, %s, %s, %d, %d", registerName(result).data(), registerName(callee).data(), registerName(thisValue).data(), registerName(arguments).data(), firstFreeRegister, varArgOffset);
1521             dumpValueProfiling(out, it, hasPrintedProfiling);
1522             break;
1523         }
1524
1525         case op_ret: {
1526             int r0 = (++it)->u.operand;
1527             printLocationOpAndRegisterOperand(out, exec, location, it, "ret", r0);
1528             break;
1529         }
1530         case op_construct: {
1531             printCallOp(out, exec, location, it, "construct", DumpCaches, hasPrintedProfiling, callLinkInfos);
1532             break;
1533         }
1534         case op_strcat: {
1535             int r0 = (++it)->u.operand;
1536             int r1 = (++it)->u.operand;
1537             int count = (++it)->u.operand;
1538             printLocationAndOp(out, exec, location, it, "strcat");
1539             out.printf("%s, %s, %d", registerName(r0).data(), registerName(r1).data(), count);
1540             break;
1541         }
1542         case op_to_primitive: {
1543             int r0 = (++it)->u.operand;
1544             int r1 = (++it)->u.operand;
1545             printLocationAndOp(out, exec, location, it, "to_primitive");
1546             out.printf("%s, %s", registerName(r0).data(), registerName(r1).data());
1547             break;
1548         }
1549         case op_get_enumerable_length: {
1550             int dst = it[1].u.operand;
1551             int base = it[2].u.operand;
1552             printLocationAndOp(out, exec, location, it, "op_get_enumerable_length");
1553             out.printf("%s, %s", registerName(dst).data(), registerName(base).data());
1554             it += OPCODE_LENGTH(op_get_enumerable_length) - 1;
1555             break;
1556         }
1557         case op_has_indexed_property: {
1558             int dst = it[1].u.operand;
1559             int base = it[2].u.operand;
1560             int propertyName = it[3].u.operand;
1561             ArrayProfile* arrayProfile = it[4].u.arrayProfile;
1562             printLocationAndOp(out, exec, location, it, "op_has_indexed_property");
1563             out.printf("%s, %s, %s, %p", registerName(dst).data(), registerName(base).data(), registerName(propertyName).data(), arrayProfile);
1564             it += OPCODE_LENGTH(op_has_indexed_property) - 1;
1565             break;
1566         }
1567         case op_has_structure_property: {
1568             int dst = it[1].u.operand;
1569             int base = it[2].u.operand;
1570             int propertyName = it[3].u.operand;
1571             int enumerator = it[4].u.operand;
1572             printLocationAndOp(out, exec, location, it, "op_has_structure_property");
1573             out.printf("%s, %s, %s, %s", registerName(dst).data(), registerName(base).data(), registerName(propertyName).data(), registerName(enumerator).data());
1574             it += OPCODE_LENGTH(op_has_structure_property) - 1;
1575             break;
1576         }
1577         case op_has_generic_property: {
1578             int dst = it[1].u.operand;
1579             int base = it[2].u.operand;
1580             int propertyName = it[3].u.operand;
1581             printLocationAndOp(out, exec, location, it, "op_has_generic_property");
1582             out.printf("%s, %s, %s", registerName(dst).data(), registerName(base).data(), registerName(propertyName).data());
1583             it += OPCODE_LENGTH(op_has_generic_property) - 1;
1584             break;
1585         }
1586         case op_get_direct_pname: {
1587             int dst = it[1].u.operand;
1588             int base = it[2].u.operand;
1589             int propertyName = it[3].u.operand;
1590             int index = it[4].u.operand;
1591             int enumerator = it[5].u.operand;
1592             ValueProfile* profile = it[6].u.profile;
1593             printLocationAndOp(out, exec, location, it, "op_get_direct_pname");
1594             out.printf("%s, %s, %s, %s, %s, %p", registerName(dst).data(), registerName(base).data(), registerName(propertyName).data(), registerName(index).data(), registerName(enumerator).data(), profile);
1595             it += OPCODE_LENGTH(op_get_direct_pname) - 1;
1596             break;
1597
1598         }
1599         case op_get_property_enumerator: {
1600             int dst = it[1].u.operand;
1601             int base = it[2].u.operand;
1602             printLocationAndOp(out, exec, location, it, "op_get_property_enumerator");
1603             out.printf("%s, %s", registerName(dst).data(), registerName(base).data());
1604             it += OPCODE_LENGTH(op_get_property_enumerator) - 1;
1605             break;
1606         }
1607         case op_enumerator_structure_pname: {
1608             int dst = it[1].u.operand;
1609             int enumerator = it[2].u.operand;
1610             int index = it[3].u.operand;
1611             printLocationAndOp(out, exec, location, it, "op_enumerator_structure_pname");
1612             out.printf("%s, %s, %s", registerName(dst).data(), registerName(enumerator).data(), registerName(index).data());
1613             it += OPCODE_LENGTH(op_enumerator_structure_pname) - 1;
1614             break;
1615         }
1616         case op_enumerator_generic_pname: {
1617             int dst = it[1].u.operand;
1618             int enumerator = it[2].u.operand;
1619             int index = it[3].u.operand;
1620             printLocationAndOp(out, exec, location, it, "op_enumerator_generic_pname");
1621             out.printf("%s, %s, %s", registerName(dst).data(), registerName(enumerator).data(), registerName(index).data());
1622             it += OPCODE_LENGTH(op_enumerator_generic_pname) - 1;
1623             break;
1624         }
1625         case op_to_index_string: {
1626             int dst = it[1].u.operand;
1627             int index = it[2].u.operand;
1628             printLocationAndOp(out, exec, location, it, "op_to_index_string");
1629             out.printf("%s, %s", registerName(dst).data(), registerName(index).data());
1630             it += OPCODE_LENGTH(op_to_index_string) - 1;
1631             break;
1632         }
1633         case op_push_with_scope: {
1634             int dst = (++it)->u.operand;
1635             int newScope = (++it)->u.operand;
1636             int currentScope = (++it)->u.operand;
1637             printLocationAndOp(out, exec, location, it, "push_with_scope");
1638             out.printf("%s, %s, %s", registerName(dst).data(), registerName(newScope).data(), registerName(currentScope).data());
1639             break;
1640         }
1641         case op_get_parent_scope: {
1642             int dst = (++it)->u.operand;
1643             int parentScope = (++it)->u.operand;
1644             printLocationAndOp(out, exec, location, it, "get_parent_scope");
1645             out.printf("%s, %s", registerName(dst).data(), registerName(parentScope).data());
1646             break;
1647         }
1648         case op_create_lexical_environment: {
1649             int dst = (++it)->u.operand;
1650             int scope = (++it)->u.operand;
1651             int symbolTable = (++it)->u.operand;
1652             int initialValue = (++it)->u.operand;
1653             printLocationAndOp(out, exec, location, it, "create_lexical_environment");
1654             out.printf("%s, %s, %s, %s", 
1655                 registerName(dst).data(), registerName(scope).data(), registerName(symbolTable).data(), registerName(initialValue).data());
1656             break;
1657         }
1658         case op_catch: {
1659             int r0 = (++it)->u.operand;
1660             int r1 = (++it)->u.operand;
1661             printLocationAndOp(out, exec, location, it, "catch");
1662             out.printf("%s, %s", registerName(r0).data(), registerName(r1).data());
1663             break;
1664         }
1665         case op_throw: {
1666             int r0 = (++it)->u.operand;
1667             printLocationOpAndRegisterOperand(out, exec, location, it, "throw", r0);
1668             break;
1669         }
1670         case op_throw_static_error: {
1671             int k0 = (++it)->u.operand;
1672             ErrorType k1 = static_cast<ErrorType>((++it)->u.unsignedValue);
1673             printLocationAndOp(out, exec, location, it, "throw_static_error");
1674             out.printf("%s, ", constantName(k0).data());
1675             out.print(k1);
1676             break;
1677         }
1678         case op_debug: {
1679             int debugHookType = (++it)->u.operand;
1680             int hasBreakpointFlag = (++it)->u.operand;
1681             printLocationAndOp(out, exec, location, it, "debug");
1682             out.printf("%s, %d", debugHookName(debugHookType), hasBreakpointFlag);
1683             break;
1684         }
1685         case op_assert: {
1686             int condition = (++it)->u.operand;
1687             int line = (++it)->u.operand;
1688             printLocationAndOp(out, exec, location, it, "assert");
1689             out.printf("%s, %d", registerName(condition).data(), line);
1690             break;
1691         }
1692         case op_end: {
1693             int r0 = (++it)->u.operand;
1694             printLocationOpAndRegisterOperand(out, exec, location, it, "end", r0);
1695             break;
1696         }
1697         case op_resolve_scope: {
1698             int r0 = (++it)->u.operand;
1699             int scope = (++it)->u.operand;
1700             int id0 = (++it)->u.operand;
1701             ResolveType resolveType = static_cast<ResolveType>((++it)->u.operand);
1702             int depth = (++it)->u.operand;
1703             void* pointer = (++it)->u.pointer;
1704             printLocationAndOp(out, exec, location, it, "resolve_scope");
1705             out.printf("%s, %s, %s, <%s>, %d, %p", registerName(r0).data(), registerName(scope).data(), idName(id0, identifier(id0)).data(), resolveTypeName(resolveType), depth, pointer);
1706             break;
1707         }
1708         case op_get_from_scope: {
1709             int r0 = (++it)->u.operand;
1710             int r1 = (++it)->u.operand;
1711             int id0 = (++it)->u.operand;
1712             GetPutInfo getPutInfo = GetPutInfo((++it)->u.operand);
1713             ++it; // Structure
1714             int operand = (++it)->u.operand; // Operand
1715             printLocationAndOp(out, exec, location, it, "get_from_scope");
1716             out.print(registerName(r0), ", ", registerName(r1));
1717             if (static_cast<unsigned>(id0) == UINT_MAX)
1718                 out.print(", anonymous");
1719             else
1720                 out.print(", ", idName(id0, identifier(id0)));
1721             out.print(", ", getPutInfo.operand(), "<", resolveModeName(getPutInfo.resolveMode()), "|", resolveTypeName(getPutInfo.resolveType()), "|", initializationModeName(getPutInfo.initializationMode()), ">, ", operand);
1722             dumpValueProfiling(out, it, hasPrintedProfiling);
1723             break;
1724         }
1725         case op_put_to_scope: {
1726             int r0 = (++it)->u.operand;
1727             int id0 = (++it)->u.operand;
1728             int r1 = (++it)->u.operand;
1729             GetPutInfo getPutInfo = GetPutInfo((++it)->u.operand);
1730             ++it; // Structure
1731             int operand = (++it)->u.operand; // Operand
1732             printLocationAndOp(out, exec, location, it, "put_to_scope");
1733             out.print(registerName(r0));
1734             if (static_cast<unsigned>(id0) == UINT_MAX)
1735                 out.print(", anonymous");
1736             else
1737                 out.print(", ", idName(id0, identifier(id0)));
1738             out.print(", ", registerName(r1), ", ", getPutInfo.operand(), "<", resolveModeName(getPutInfo.resolveMode()), "|", resolveTypeName(getPutInfo.resolveType()), "|", initializationModeName(getPutInfo.initializationMode()), ">, <structure>, ", operand);
1739             break;
1740         }
1741         case op_get_from_arguments: {
1742             int r0 = (++it)->u.operand;
1743             int r1 = (++it)->u.operand;
1744             int offset = (++it)->u.operand;
1745             printLocationAndOp(out, exec, location, it, "get_from_arguments");
1746             out.printf("%s, %s, %d", registerName(r0).data(), registerName(r1).data(), offset);
1747             dumpValueProfiling(out, it, hasPrintedProfiling);
1748             break;
1749         }
1750         case op_put_to_arguments: {
1751             int r0 = (++it)->u.operand;
1752             int offset = (++it)->u.operand;
1753             int r1 = (++it)->u.operand;
1754             printLocationAndOp(out, exec, location, it, "put_to_arguments");
1755             out.printf("%s, %d, %s", registerName(r0).data(), offset, registerName(r1).data());
1756             break;
1757         }
1758         default:
1759             RELEASE_ASSERT_NOT_REACHED();
1760     }
1761
1762     dumpRareCaseProfile(out, "rare case: ", rareCaseProfileForBytecodeOffset(location), hasPrintedProfiling);
1763     {
1764         dumpArithProfile(out, arithProfileForBytecodeOffset(location), hasPrintedProfiling);
1765     }
1766     
1767 #if ENABLE(DFG_JIT)
1768     Vector<DFG::FrequentExitSite> exitSites = exitProfile().exitSitesFor(location);
1769     if (!exitSites.isEmpty()) {
1770         out.print(" !! frequent exits: ");
1771         CommaPrinter comma;
1772         for (unsigned i = 0; i < exitSites.size(); ++i)
1773             out.print(comma, exitSites[i].kind(), " ", exitSites[i].jitType());
1774     }
1775 #else // ENABLE(DFG_JIT)
1776     UNUSED_PARAM(location);
1777 #endif // ENABLE(DFG_JIT)
1778     out.print("\n");
1779 }
1780
1781 void CodeBlock::dumpBytecode(
1782     PrintStream& out, unsigned bytecodeOffset,
1783     const StubInfoMap& stubInfos, const CallLinkInfoMap& callLinkInfos)
1784 {
1785     ExecState* exec = m_globalObject->globalExec();
1786     const Instruction* it = instructions().begin() + bytecodeOffset;
1787     dumpBytecode(out, exec, instructions().begin(), it, stubInfos, callLinkInfos);
1788 }
1789
1790 #define FOR_EACH_MEMBER_VECTOR(macro) \
1791     macro(instructions) \
1792     macro(callLinkInfos) \
1793     macro(linkedCallerList) \
1794     macro(identifiers) \
1795     macro(functionExpressions) \
1796     macro(constantRegisters)
1797
1798 template<typename T>
1799 static size_t sizeInBytes(const Vector<T>& vector)
1800 {
1801     return vector.capacity() * sizeof(T);
1802 }
1803
1804 namespace {
1805
1806 class PutToScopeFireDetail : public FireDetail {
1807 public:
1808     PutToScopeFireDetail(CodeBlock* codeBlock, const Identifier& ident)
1809         : m_codeBlock(codeBlock)
1810         , m_ident(ident)
1811     {
1812     }
1813     
1814     void dump(PrintStream& out) const override
1815     {
1816         out.print("Linking put_to_scope in ", FunctionExecutableDump(jsCast<FunctionExecutable*>(m_codeBlock->ownerExecutable())), " for ", m_ident);
1817     }
1818     
1819 private:
1820     CodeBlock* m_codeBlock;
1821     const Identifier& m_ident;
1822 };
1823
1824 } // anonymous namespace
1825
1826 CodeBlock::CodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, CodeBlock& other)
1827     : JSCell(*vm, structure)
1828     , m_globalObject(other.m_globalObject)
1829     , m_numCalleeLocals(other.m_numCalleeLocals)
1830     , m_numVars(other.m_numVars)
1831     , m_shouldAlwaysBeInlined(true)
1832 #if ENABLE(JIT)
1833     , m_capabilityLevelState(DFG::CapabilityLevelNotSet)
1834 #endif
1835     , m_didFailJITCompilation(false)
1836     , m_didFailFTLCompilation(false)
1837     , m_hasBeenCompiledWithFTL(false)
1838     , m_isConstructor(other.m_isConstructor)
1839     , m_isStrictMode(other.m_isStrictMode)
1840     , m_codeType(other.m_codeType)
1841     , m_unlinkedCode(*other.m_vm, this, other.m_unlinkedCode.get())
1842     , m_hasDebuggerStatement(false)
1843     , m_steppingMode(SteppingModeDisabled)
1844     , m_numBreakpoints(0)
1845     , m_ownerExecutable(*other.m_vm, this, other.m_ownerExecutable.get())
1846     , m_vm(other.m_vm)
1847     , m_instructions(other.m_instructions)
1848     , m_thisRegister(other.m_thisRegister)
1849     , m_scopeRegister(other.m_scopeRegister)
1850     , m_hash(other.m_hash)
1851     , m_source(other.m_source)
1852     , m_sourceOffset(other.m_sourceOffset)
1853     , m_firstLineColumnOffset(other.m_firstLineColumnOffset)
1854     , m_constantRegisters(other.m_constantRegisters)
1855     , m_constantsSourceCodeRepresentation(other.m_constantsSourceCodeRepresentation)
1856     , m_functionDecls(other.m_functionDecls)
1857     , m_functionExprs(other.m_functionExprs)
1858     , m_osrExitCounter(0)
1859     , m_optimizationDelayCounter(0)
1860     , m_reoptimizationRetryCounter(0)
1861     , m_creationTime(std::chrono::steady_clock::now())
1862 {
1863     m_visitWeaklyHasBeenCalled = false;
1864
1865     ASSERT(heap()->isDeferred());
1866     ASSERT(m_scopeRegister.isLocal());
1867
1868     setNumParameters(other.numParameters());
1869 }
1870
1871 void CodeBlock::finishCreation(VM& vm, CopyParsedBlockTag, CodeBlock& other)
1872 {
1873     Base::finishCreation(vm);
1874
1875     optimizeAfterWarmUp();
1876     jitAfterWarmUp();
1877
1878     if (other.m_rareData) {
1879         createRareDataIfNecessary();
1880         
1881         m_rareData->m_exceptionHandlers = other.m_rareData->m_exceptionHandlers;
1882         m_rareData->m_constantBuffers = other.m_rareData->m_constantBuffers;
1883         m_rareData->m_switchJumpTables = other.m_rareData->m_switchJumpTables;
1884         m_rareData->m_stringSwitchJumpTables = other.m_rareData->m_stringSwitchJumpTables;
1885     }
1886     
1887     heap()->m_codeBlocks->add(this);
1888 }
1889
1890 CodeBlock::CodeBlock(VM* vm, Structure* structure, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock,
1891     JSScope* scope, PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset, unsigned firstLineColumnOffset)
1892     : JSCell(*vm, structure)
1893     , m_globalObject(scope->globalObject()->vm(), this, scope->globalObject())
1894     , m_numCalleeLocals(unlinkedCodeBlock->m_numCalleeLocals)
1895     , m_numVars(unlinkedCodeBlock->m_numVars)
1896     , m_shouldAlwaysBeInlined(true)
1897 #if ENABLE(JIT)
1898     , m_capabilityLevelState(DFG::CapabilityLevelNotSet)
1899 #endif
1900     , m_didFailJITCompilation(false)
1901     , m_didFailFTLCompilation(false)
1902     , m_hasBeenCompiledWithFTL(false)
1903     , m_isConstructor(unlinkedCodeBlock->isConstructor())
1904     , m_isStrictMode(unlinkedCodeBlock->isStrictMode())
1905     , m_codeType(unlinkedCodeBlock->codeType())
1906     , m_unlinkedCode(m_globalObject->vm(), this, unlinkedCodeBlock)
1907     , m_hasDebuggerStatement(false)
1908     , m_steppingMode(SteppingModeDisabled)
1909     , m_numBreakpoints(0)
1910     , m_ownerExecutable(m_globalObject->vm(), this, ownerExecutable)
1911     , m_vm(unlinkedCodeBlock->vm())
1912     , m_thisRegister(unlinkedCodeBlock->thisRegister())
1913     , m_scopeRegister(unlinkedCodeBlock->scopeRegister())
1914     , m_source(sourceProvider)
1915     , m_sourceOffset(sourceOffset)
1916     , m_firstLineColumnOffset(firstLineColumnOffset)
1917     , m_osrExitCounter(0)
1918     , m_optimizationDelayCounter(0)
1919     , m_reoptimizationRetryCounter(0)
1920     , m_creationTime(std::chrono::steady_clock::now())
1921 {
1922     m_visitWeaklyHasBeenCalled = false;
1923
1924     ASSERT(heap()->isDeferred());
1925     ASSERT(m_scopeRegister.isLocal());
1926
1927     ASSERT(m_source);
1928     setNumParameters(unlinkedCodeBlock->numParameters());
1929 }
1930
1931 void CodeBlock::finishCreation(VM& vm, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock,
1932     JSScope* scope)
1933 {
1934     Base::finishCreation(vm);
1935
1936     if (vm.typeProfiler() || vm.controlFlowProfiler())
1937         vm.functionHasExecutedCache()->removeUnexecutedRange(ownerExecutable->sourceID(), ownerExecutable->typeProfilingStartOffset(), ownerExecutable->typeProfilingEndOffset());
1938
1939     setConstantRegisters(unlinkedCodeBlock->constantRegisters(), unlinkedCodeBlock->constantsSourceCodeRepresentation());
1940     if (unlinkedCodeBlock->usesGlobalObject())
1941         m_constantRegisters[unlinkedCodeBlock->globalObjectRegister().toConstantIndex()].set(*m_vm, this, m_globalObject.get());
1942
1943     for (unsigned i = 0; i < LinkTimeConstantCount; i++) {
1944         LinkTimeConstant type = static_cast<LinkTimeConstant>(i);
1945         if (unsigned registerIndex = unlinkedCodeBlock->registerIndexForLinkTimeConstant(type))
1946             m_constantRegisters[registerIndex].set(*m_vm, this, m_globalObject->jsCellForLinkTimeConstant(type));
1947     }
1948
1949     // We already have the cloned symbol table for the module environment since we need to instantiate
1950     // the module environments before linking the code block. We replace the stored symbol table with the already cloned one.
1951     if (UnlinkedModuleProgramCodeBlock* unlinkedModuleProgramCodeBlock = jsDynamicCast<UnlinkedModuleProgramCodeBlock*>(unlinkedCodeBlock)) {
1952         SymbolTable* clonedSymbolTable = jsCast<ModuleProgramExecutable*>(ownerExecutable)->moduleEnvironmentSymbolTable();
1953         if (m_vm->typeProfiler()) {
1954             ConcurrentJSLocker locker(clonedSymbolTable->m_lock);
1955             clonedSymbolTable->prepareForTypeProfiling(locker);
1956         }
1957         replaceConstant(unlinkedModuleProgramCodeBlock->moduleEnvironmentSymbolTableConstantRegisterOffset(), clonedSymbolTable);
1958     }
1959
1960     bool shouldUpdateFunctionHasExecutedCache = vm.typeProfiler() || vm.controlFlowProfiler();
1961     m_functionDecls = RefCountedArray<WriteBarrier<FunctionExecutable>>(unlinkedCodeBlock->numberOfFunctionDecls());
1962     for (size_t count = unlinkedCodeBlock->numberOfFunctionDecls(), i = 0; i < count; ++i) {
1963         UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionDecl(i);
1964         if (shouldUpdateFunctionHasExecutedCache)
1965             vm.functionHasExecutedCache()->insertUnexecutedRange(ownerExecutable->sourceID(), unlinkedExecutable->typeProfilingStartOffset(), unlinkedExecutable->typeProfilingEndOffset());
1966         m_functionDecls[i].set(*m_vm, this, unlinkedExecutable->link(*m_vm, ownerExecutable->source()));
1967     }
1968
1969     m_functionExprs = RefCountedArray<WriteBarrier<FunctionExecutable>>(unlinkedCodeBlock->numberOfFunctionExprs());
1970     for (size_t count = unlinkedCodeBlock->numberOfFunctionExprs(), i = 0; i < count; ++i) {
1971         UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionExpr(i);
1972         if (shouldUpdateFunctionHasExecutedCache)
1973             vm.functionHasExecutedCache()->insertUnexecutedRange(ownerExecutable->sourceID(), unlinkedExecutable->typeProfilingStartOffset(), unlinkedExecutable->typeProfilingEndOffset());
1974         m_functionExprs[i].set(*m_vm, this, unlinkedExecutable->link(*m_vm, ownerExecutable->source()));
1975     }
1976
1977     if (unlinkedCodeBlock->hasRareData()) {
1978         createRareDataIfNecessary();
1979         if (size_t count = unlinkedCodeBlock->constantBufferCount()) {
1980             m_rareData->m_constantBuffers.grow(count);
1981             for (size_t i = 0; i < count; i++) {
1982                 const UnlinkedCodeBlock::ConstantBuffer& buffer = unlinkedCodeBlock->constantBuffer(i);
1983                 m_rareData->m_constantBuffers[i] = buffer;
1984             }
1985         }
1986         if (size_t count = unlinkedCodeBlock->numberOfExceptionHandlers()) {
1987             m_rareData->m_exceptionHandlers.resizeToFit(count);
1988             for (size_t i = 0; i < count; i++) {
1989                 const UnlinkedHandlerInfo& unlinkedHandler = unlinkedCodeBlock->exceptionHandler(i);
1990                 HandlerInfo& handler = m_rareData->m_exceptionHandlers[i];
1991 #if ENABLE(JIT)
1992                 handler.initialize(unlinkedHandler, CodeLocationLabel(MacroAssemblerCodePtr::createFromExecutableAddress(LLInt::getCodePtr(op_catch))));
1993 #else
1994                 handler.initialize(unlinkedHandler);
1995 #endif
1996             }
1997         }
1998
1999         if (size_t count = unlinkedCodeBlock->numberOfStringSwitchJumpTables()) {
2000             m_rareData->m_stringSwitchJumpTables.grow(count);
2001             for (size_t i = 0; i < count; i++) {
2002                 UnlinkedStringJumpTable::StringOffsetTable::iterator ptr = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.begin();
2003                 UnlinkedStringJumpTable::StringOffsetTable::iterator end = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.end();
2004                 for (; ptr != end; ++ptr) {
2005                     OffsetLocation offset;
2006                     offset.branchOffset = ptr->value.branchOffset;
2007                     m_rareData->m_stringSwitchJumpTables[i].offsetTable.add(ptr->key, offset);
2008                 }
2009             }
2010         }
2011
2012         if (size_t count = unlinkedCodeBlock->numberOfSwitchJumpTables()) {
2013             m_rareData->m_switchJumpTables.grow(count);
2014             for (size_t i = 0; i < count; i++) {
2015                 UnlinkedSimpleJumpTable& sourceTable = unlinkedCodeBlock->switchJumpTable(i);
2016                 SimpleJumpTable& destTable = m_rareData->m_switchJumpTables[i];
2017                 destTable.branchOffsets = sourceTable.branchOffsets;
2018                 destTable.min = sourceTable.min;
2019             }
2020         }
2021     }
2022
2023     // Allocate metadata buffers for the bytecode
2024     if (size_t size = unlinkedCodeBlock->numberOfLLintCallLinkInfos())
2025         m_llintCallLinkInfos = RefCountedArray<LLIntCallLinkInfo>(size);
2026     if (size_t size = unlinkedCodeBlock->numberOfArrayProfiles())
2027         m_arrayProfiles.grow(size);
2028     if (size_t size = unlinkedCodeBlock->numberOfArrayAllocationProfiles())
2029         m_arrayAllocationProfiles = RefCountedArray<ArrayAllocationProfile>(size);
2030     if (size_t size = unlinkedCodeBlock->numberOfValueProfiles())
2031         m_valueProfiles = RefCountedArray<ValueProfile>(size);
2032     if (size_t size = unlinkedCodeBlock->numberOfObjectAllocationProfiles())
2033         m_objectAllocationProfiles = RefCountedArray<ObjectAllocationProfile>(size);
2034
2035 #if ENABLE(JIT)
2036     setCalleeSaveRegisters(RegisterSet::llintBaselineCalleeSaveRegisters());
2037 #endif
2038
2039     // Copy and translate the UnlinkedInstructions
2040     unsigned instructionCount = unlinkedCodeBlock->instructions().count();
2041     UnlinkedInstructionStream::Reader instructionReader(unlinkedCodeBlock->instructions());
2042
2043     // Bookkeep the strongly referenced module environments.
2044     HashSet<JSModuleEnvironment*> stronglyReferencedModuleEnvironments;
2045
2046     RefCountedArray<Instruction> instructions(instructionCount);
2047
2048     unsigned valueProfileCount = 0;
2049     auto linkValueProfile = [&](unsigned bytecodeOffset, unsigned opLength) {
2050         unsigned valueProfileIndex = valueProfileCount++;
2051         ValueProfile* profile = &m_valueProfiles[valueProfileIndex];
2052         ASSERT(profile->m_bytecodeOffset == -1);
2053         profile->m_bytecodeOffset = bytecodeOffset;
2054         instructions[bytecodeOffset + opLength - 1] = profile;
2055     };
2056
2057     for (unsigned i = 0; !instructionReader.atEnd(); ) {
2058         const UnlinkedInstruction* pc = instructionReader.next();
2059
2060         unsigned opLength = opcodeLength(pc[0].u.opcode);
2061
2062         instructions[i] = vm.interpreter->getOpcode(pc[0].u.opcode);
2063         for (size_t j = 1; j < opLength; ++j) {
2064             if (sizeof(int32_t) != sizeof(intptr_t))
2065                 instructions[i + j].u.pointer = 0;
2066             instructions[i + j].u.operand = pc[j].u.operand;
2067         }
2068         switch (pc[0].u.opcode) {
2069         case op_has_indexed_property: {
2070             int arrayProfileIndex = pc[opLength - 1].u.operand;
2071             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
2072
2073             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
2074             break;
2075         }
2076         case op_call_varargs:
2077         case op_tail_call_varargs:
2078         case op_tail_call_forward_arguments:
2079         case op_construct_varargs:
2080         case op_get_by_val: {
2081             int arrayProfileIndex = pc[opLength - 2].u.operand;
2082             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
2083
2084             instructions[i + opLength - 2] = &m_arrayProfiles[arrayProfileIndex];
2085             FALLTHROUGH;
2086         }
2087         case op_get_direct_pname:
2088         case op_get_by_id:
2089         case op_get_by_id_with_this:
2090         case op_try_get_by_id:
2091         case op_get_by_val_with_this:
2092         case op_get_from_arguments:
2093         case op_to_number:
2094         case op_get_argument: {
2095             linkValueProfile(i, opLength);
2096             break;
2097         }
2098         case op_put_by_val: {
2099             int arrayProfileIndex = pc[opLength - 1].u.operand;
2100             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
2101             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
2102             break;
2103         }
2104         case op_put_by_val_direct: {
2105             int arrayProfileIndex = pc[opLength - 1].u.operand;
2106             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
2107             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
2108             break;
2109         }
2110
2111         case op_new_array:
2112         case op_new_array_buffer:
2113         case op_new_array_with_size: {
2114             int arrayAllocationProfileIndex = pc[opLength - 1].u.operand;
2115             instructions[i + opLength - 1] = &m_arrayAllocationProfiles[arrayAllocationProfileIndex];
2116             break;
2117         }
2118         case op_new_object: {
2119             int objectAllocationProfileIndex = pc[opLength - 1].u.operand;
2120             ObjectAllocationProfile* objectAllocationProfile = &m_objectAllocationProfiles[objectAllocationProfileIndex];
2121             int inferredInlineCapacity = pc[opLength - 2].u.operand;
2122
2123             instructions[i + opLength - 1] = objectAllocationProfile;
2124             objectAllocationProfile->initialize(vm,
2125                 this, m_globalObject->objectPrototype(), inferredInlineCapacity);
2126             break;
2127         }
2128
2129         case op_call:
2130         case op_tail_call:
2131         case op_call_eval: {
2132             linkValueProfile(i, opLength);
2133             int arrayProfileIndex = pc[opLength - 2].u.operand;
2134             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
2135             instructions[i + opLength - 2] = &m_arrayProfiles[arrayProfileIndex];
2136             instructions[i + 5] = &m_llintCallLinkInfos[pc[5].u.operand];
2137             break;
2138         }
2139         case op_construct: {
2140             instructions[i + 5] = &m_llintCallLinkInfos[pc[5].u.operand];
2141             linkValueProfile(i, opLength);
2142             break;
2143         }
2144         case op_get_array_length:
2145             CRASH();
2146
2147         case op_resolve_scope: {
2148             const Identifier& ident = identifier(pc[3].u.operand);
2149             ResolveType type = static_cast<ResolveType>(pc[4].u.operand);
2150             RELEASE_ASSERT(type != LocalClosureVar);
2151             int localScopeDepth = pc[5].u.operand;
2152
2153             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Get, type, InitializationMode::NotInitialization);
2154             instructions[i + 4].u.operand = op.type;
2155             instructions[i + 5].u.operand = op.depth;
2156             if (op.lexicalEnvironment) {
2157                 if (op.type == ModuleVar) {
2158                     // Keep the linked module environment strongly referenced.
2159                     if (stronglyReferencedModuleEnvironments.add(jsCast<JSModuleEnvironment*>(op.lexicalEnvironment)).isNewEntry)
2160                         addConstant(op.lexicalEnvironment);
2161                     instructions[i + 6].u.jsCell.set(vm, this, op.lexicalEnvironment);
2162                 } else
2163                     instructions[i + 6].u.symbolTable.set(vm, this, op.lexicalEnvironment->symbolTable());
2164             } else if (JSScope* constantScope = JSScope::constantScopeForCodeBlock(op.type, this))
2165                 instructions[i + 6].u.jsCell.set(vm, this, constantScope);
2166             else
2167                 instructions[i + 6].u.pointer = nullptr;
2168             break;
2169         }
2170
2171         case op_get_from_scope: {
2172             linkValueProfile(i, opLength);
2173
2174             // get_from_scope dst, scope, id, GetPutInfo, Structure, Operand
2175
2176             int localScopeDepth = pc[5].u.operand;
2177             instructions[i + 5].u.pointer = nullptr;
2178
2179             GetPutInfo getPutInfo = GetPutInfo(pc[4].u.operand);
2180             ASSERT(!isInitialization(getPutInfo.initializationMode()));
2181             if (getPutInfo.resolveType() == LocalClosureVar) {
2182                 instructions[i + 4] = GetPutInfo(getPutInfo.resolveMode(), ClosureVar, getPutInfo.initializationMode()).operand();
2183                 break;
2184             }
2185
2186             const Identifier& ident = identifier(pc[3].u.operand);
2187             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Get, getPutInfo.resolveType(), InitializationMode::NotInitialization);
2188
2189             instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), op.type, getPutInfo.initializationMode()).operand();
2190             if (op.type == ModuleVar)
2191                 instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), ClosureVar, getPutInfo.initializationMode()).operand();
2192             if (op.type == GlobalVar || op.type == GlobalVarWithVarInjectionChecks || op.type == GlobalLexicalVar || op.type == GlobalLexicalVarWithVarInjectionChecks)
2193                 instructions[i + 5].u.watchpointSet = op.watchpointSet;
2194             else if (op.structure)
2195                 instructions[i + 5].u.structure.set(vm, this, op.structure);
2196             instructions[i + 6].u.pointer = reinterpret_cast<void*>(op.operand);
2197             break;
2198         }
2199
2200         case op_put_to_scope: {
2201             // put_to_scope scope, id, value, GetPutInfo, Structure, Operand
2202             GetPutInfo getPutInfo = GetPutInfo(pc[4].u.operand);
2203             if (getPutInfo.resolveType() == LocalClosureVar) {
2204                 // Only do watching if the property we're putting to is not anonymous.
2205                 if (static_cast<unsigned>(pc[2].u.operand) != UINT_MAX) {
2206                     int symbolTableIndex = pc[5].u.operand;
2207                     SymbolTable* symbolTable = jsCast<SymbolTable*>(getConstant(symbolTableIndex));
2208                     const Identifier& ident = identifier(pc[2].u.operand);
2209                     ConcurrentJSLocker locker(symbolTable->m_lock);
2210                     auto iter = symbolTable->find(locker, ident.impl());
2211                     ASSERT(iter != symbolTable->end(locker));
2212                     iter->value.prepareToWatch();
2213                     instructions[i + 5].u.watchpointSet = iter->value.watchpointSet();
2214                 } else
2215                     instructions[i + 5].u.watchpointSet = nullptr;
2216                 break;
2217             }
2218
2219             const Identifier& ident = identifier(pc[2].u.operand);
2220             int localScopeDepth = pc[5].u.operand;
2221             instructions[i + 5].u.pointer = nullptr;
2222             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Put, getPutInfo.resolveType(), getPutInfo.initializationMode());
2223
2224             instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), op.type, getPutInfo.initializationMode()).operand();
2225             if (op.type == GlobalVar || op.type == GlobalVarWithVarInjectionChecks || op.type == GlobalLexicalVar || op.type == GlobalLexicalVarWithVarInjectionChecks)
2226                 instructions[i + 5].u.watchpointSet = op.watchpointSet;
2227             else if (op.type == ClosureVar || op.type == ClosureVarWithVarInjectionChecks) {
2228                 if (op.watchpointSet)
2229                     op.watchpointSet->invalidate(vm, PutToScopeFireDetail(this, ident));
2230             } else if (op.structure)
2231                 instructions[i + 5].u.structure.set(vm, this, op.structure);
2232             instructions[i + 6].u.pointer = reinterpret_cast<void*>(op.operand);
2233
2234             break;
2235         }
2236
2237         case op_profile_type: {
2238             RELEASE_ASSERT(vm.typeProfiler());
2239             // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType?
2240             size_t instructionOffset = i + opLength - 1;
2241             unsigned divotStart, divotEnd;
2242             GlobalVariableID globalVariableID = 0;
2243             RefPtr<TypeSet> globalTypeSet;
2244             bool shouldAnalyze = m_unlinkedCode->typeProfilerExpressionInfoForBytecodeOffset(instructionOffset, divotStart, divotEnd);
2245             VirtualRegister profileRegister(pc[1].u.operand);
2246             ProfileTypeBytecodeFlag flag = static_cast<ProfileTypeBytecodeFlag>(pc[3].u.operand);
2247             SymbolTable* symbolTable = nullptr;
2248
2249             switch (flag) {
2250             case ProfileTypeBytecodeClosureVar: {
2251                 const Identifier& ident = identifier(pc[4].u.operand);
2252                 int localScopeDepth = pc[2].u.operand;
2253                 ResolveType type = static_cast<ResolveType>(pc[5].u.operand);
2254                 // Even though type profiling may be profiling either a Get or a Put, we can always claim a Get because
2255                 // we're abstractly "read"ing from a JSScope.
2256                 ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Get, type, InitializationMode::NotInitialization);
2257
2258                 if (op.type == ClosureVar || op.type == ModuleVar)
2259                     symbolTable = op.lexicalEnvironment->symbolTable();
2260                 else if (op.type == GlobalVar)
2261                     symbolTable = m_globalObject.get()->symbolTable();
2262
2263                 UniquedStringImpl* impl = (op.type == ModuleVar) ? op.importedName.get() : ident.impl();
2264                 if (symbolTable) {
2265                     ConcurrentJSLocker locker(symbolTable->m_lock);
2266                     // If our parent scope was created while profiling was disabled, it will not have prepared for profiling yet.
2267                     symbolTable->prepareForTypeProfiling(locker);
2268                     globalVariableID = symbolTable->uniqueIDForVariable(locker, impl, vm);
2269                     globalTypeSet = symbolTable->globalTypeSetForVariable(locker, impl, vm);
2270                 } else
2271                     globalVariableID = TypeProfilerNoGlobalIDExists;
2272
2273                 break;
2274             }
2275             case ProfileTypeBytecodeLocallyResolved: {
2276                 int symbolTableIndex = pc[2].u.operand;
2277                 SymbolTable* symbolTable = jsCast<SymbolTable*>(getConstant(symbolTableIndex));
2278                 const Identifier& ident = identifier(pc[4].u.operand);
2279                 ConcurrentJSLocker locker(symbolTable->m_lock);
2280                 // If our parent scope was created while profiling was disabled, it will not have prepared for profiling yet.
2281                 globalVariableID = symbolTable->uniqueIDForVariable(locker, ident.impl(), vm);
2282                 globalTypeSet = symbolTable->globalTypeSetForVariable(locker, ident.impl(), vm);
2283
2284                 break;
2285             }
2286             case ProfileTypeBytecodeDoesNotHaveGlobalID: 
2287             case ProfileTypeBytecodeFunctionArgument: {
2288                 globalVariableID = TypeProfilerNoGlobalIDExists;
2289                 break;
2290             }
2291             case ProfileTypeBytecodeFunctionReturnStatement: {
2292                 RELEASE_ASSERT(ownerExecutable->isFunctionExecutable());
2293                 globalTypeSet = jsCast<FunctionExecutable*>(ownerExecutable)->returnStatementTypeSet();
2294                 globalVariableID = TypeProfilerReturnStatement;
2295                 if (!shouldAnalyze) {
2296                     // Because a return statement can be added implicitly to return undefined at the end of a function,
2297                     // and these nodes don't emit expression ranges because they aren't in the actual source text of
2298                     // the user's program, give the type profiler some range to identify these return statements.
2299                     // Currently, the text offset that is used as identification is "f" in the function keyword
2300                     // and is stored on TypeLocation's m_divotForFunctionOffsetIfReturnStatement member variable.
2301                     divotStart = divotEnd = ownerExecutable->typeProfilingStartOffset();
2302                     shouldAnalyze = true;
2303                 }
2304                 break;
2305             }
2306             }
2307
2308             std::pair<TypeLocation*, bool> locationPair = vm.typeProfiler()->typeLocationCache()->getTypeLocation(globalVariableID,
2309                 ownerExecutable->sourceID(), divotStart, divotEnd, globalTypeSet, &vm);
2310             TypeLocation* location = locationPair.first;
2311             bool isNewLocation = locationPair.second;
2312
2313             if (flag == ProfileTypeBytecodeFunctionReturnStatement)
2314                 location->m_divotForFunctionOffsetIfReturnStatement = ownerExecutable->typeProfilingStartOffset();
2315
2316             if (shouldAnalyze && isNewLocation)
2317                 vm.typeProfiler()->insertNewLocation(location);
2318
2319             instructions[i + 2].u.location = location;
2320             break;
2321         }
2322
2323         case op_debug: {
2324             if (pc[1].u.index == DidReachBreakpoint)
2325                 m_hasDebuggerStatement = true;
2326             break;
2327         }
2328
2329         case op_create_rest: {
2330             int numberOfArgumentsToSkip = instructions[i + 3].u.operand;
2331             ASSERT_UNUSED(numberOfArgumentsToSkip, numberOfArgumentsToSkip >= 0);
2332             ASSERT_WITH_MESSAGE(numberOfArgumentsToSkip == numParameters() - 1, "We assume that this is true when rematerializing the rest parameter during OSR exit in the FTL JIT.");
2333             break;
2334         }
2335
2336         default:
2337             break;
2338         }
2339         i += opLength;
2340     }
2341
2342     if (vm.controlFlowProfiler())
2343         insertBasicBlockBoundariesForControlFlowProfiler(instructions);
2344
2345     m_instructions = WTFMove(instructions);
2346
2347     // Set optimization thresholds only after m_instructions is initialized, since these
2348     // rely on the instruction count (and are in theory permitted to also inspect the
2349     // instruction stream to more accurate assess the cost of tier-up).
2350     optimizeAfterWarmUp();
2351     jitAfterWarmUp();
2352
2353     // If the concurrent thread will want the code block's hash, then compute it here
2354     // synchronously.
2355     if (Options::alwaysComputeHash())
2356         hash();
2357
2358     if (Options::dumpGeneratedBytecodes())
2359         dumpBytecode();
2360     
2361     heap()->m_codeBlocks->add(this);
2362     heap()->reportExtraMemoryAllocated(m_instructions.size() * sizeof(Instruction));
2363 }
2364
2365 CodeBlock::~CodeBlock()
2366 {
2367     if (m_vm->m_perBytecodeProfiler)
2368         m_vm->m_perBytecodeProfiler->notifyDestruction(this);
2369
2370     if (unlinkedCodeBlock()->didOptimize() == MixedTriState)
2371         unlinkedCodeBlock()->setDidOptimize(FalseTriState);
2372
2373 #if ENABLE(VERBOSE_VALUE_PROFILE)
2374     dumpValueProfiles();
2375 #endif
2376
2377     // We may be destroyed before any CodeBlocks that refer to us are destroyed.
2378     // Consider that two CodeBlocks become unreachable at the same time. There
2379     // is no guarantee about the order in which the CodeBlocks are destroyed.
2380     // So, if we don't remove incoming calls, and get destroyed before the
2381     // CodeBlock(s) that have calls into us, then the CallLinkInfo vector's
2382     // destructor will try to remove nodes from our (no longer valid) linked list.
2383     unlinkIncomingCalls();
2384     
2385     // Note that our outgoing calls will be removed from other CodeBlocks'
2386     // m_incomingCalls linked lists through the execution of the ~CallLinkInfo
2387     // destructors.
2388
2389 #if ENABLE(JIT)
2390     for (Bag<StructureStubInfo>::iterator iter = m_stubInfos.begin(); !!iter; ++iter) {
2391         StructureStubInfo* stub = *iter;
2392         stub->aboutToDie();
2393         stub->deref();
2394     }
2395 #endif // ENABLE(JIT)
2396 }
2397
2398 void CodeBlock::setConstantRegisters(const Vector<WriteBarrier<Unknown>>& constants, const Vector<SourceCodeRepresentation>& constantsSourceCodeRepresentation)
2399 {
2400     ASSERT(constants.size() == constantsSourceCodeRepresentation.size());
2401     size_t count = constants.size();
2402     m_constantRegisters.resizeToFit(count);
2403     bool hasTypeProfiler = !!m_vm->typeProfiler();
2404     for (size_t i = 0; i < count; i++) {
2405         JSValue constant = constants[i].get();
2406
2407         if (!constant.isEmpty()) {
2408             if (SymbolTable* symbolTable = jsDynamicCast<SymbolTable*>(constant)) {
2409                 if (hasTypeProfiler) {
2410                     ConcurrentJSLocker locker(symbolTable->m_lock);
2411                     symbolTable->prepareForTypeProfiling(locker);
2412                 }
2413
2414                 SymbolTable* clone = symbolTable->cloneScopePart(*m_vm);
2415                 if (wasCompiledWithDebuggingOpcodes())
2416                     clone->setRareDataCodeBlock(this);
2417
2418                 constant = clone;
2419             }
2420         }
2421
2422         m_constantRegisters[i].set(*m_vm, this, constant);
2423     }
2424
2425     m_constantsSourceCodeRepresentation = constantsSourceCodeRepresentation;
2426 }
2427
2428 void CodeBlock::setAlternative(VM& vm, CodeBlock* alternative)
2429 {
2430     m_alternative.set(vm, this, alternative);
2431 }
2432
2433 void CodeBlock::setNumParameters(int newValue)
2434 {
2435     m_numParameters = newValue;
2436
2437     m_argumentValueProfiles = RefCountedArray<ValueProfile>(newValue);
2438 }
2439
2440 void DirectEvalCodeCache::visitAggregate(SlotVisitor& visitor)
2441 {
2442     EvalCacheMap::iterator end = m_cacheMap.end();
2443     for (EvalCacheMap::iterator ptr = m_cacheMap.begin(); ptr != end; ++ptr)
2444         visitor.append(&ptr->value);
2445 }
2446
2447 CodeBlock* CodeBlock::specialOSREntryBlockOrNull()
2448 {
2449 #if ENABLE(FTL_JIT)
2450     if (jitType() != JITCode::DFGJIT)
2451         return 0;
2452     DFG::JITCode* jitCode = m_jitCode->dfg();
2453     return jitCode->osrEntryBlock();
2454 #else // ENABLE(FTL_JIT)
2455     return 0;
2456 #endif // ENABLE(FTL_JIT)
2457 }
2458
2459 void CodeBlock::visitWeakly(SlotVisitor& visitor)
2460 {
2461     ConcurrentJSLocker locker(m_lock);
2462     if (m_visitWeaklyHasBeenCalled)
2463         return;
2464     
2465     m_visitWeaklyHasBeenCalled = true;
2466
2467     if (Heap::isMarkedConcurrently(this))
2468         return;
2469
2470     if (shouldVisitStrongly(locker)) {
2471         visitor.appendUnbarrieredReadOnlyPointer(this);
2472         return;
2473     }
2474     
2475     // There are two things that may use unconditional finalizers: inline cache clearing
2476     // and jettisoning. The probability of us wanting to do at least one of those things
2477     // is probably quite close to 1. So we add one no matter what and when it runs, it
2478     // figures out whether it has any work to do.
2479     visitor.addUnconditionalFinalizer(&m_unconditionalFinalizer);
2480
2481     if (!JITCode::isOptimizingJIT(jitType()))
2482         return;
2483
2484     // If we jettison ourselves we'll install our alternative, so make sure that it
2485     // survives GC even if we don't.
2486     visitor.append(&m_alternative);
2487     
2488     // There are two things that we use weak reference harvesters for: DFG fixpoint for
2489     // jettisoning, and trying to find structures that would be live based on some
2490     // inline cache. So it makes sense to register them regardless.
2491     visitor.addWeakReferenceHarvester(&m_weakReferenceHarvester);
2492
2493 #if ENABLE(DFG_JIT)
2494     // We get here if we're live in the sense that our owner executable is live,
2495     // but we're not yet live for sure in another sense: we may yet decide that this
2496     // code block should be jettisoned based on its outgoing weak references being
2497     // stale. Set a flag to indicate that we're still assuming that we're dead, and
2498     // perform one round of determining if we're live. The GC may determine, based on
2499     // either us marking additional objects, or by other objects being marked for
2500     // other reasons, that this iteration should run again; it will notify us of this
2501     // decision by calling harvestWeakReferences().
2502
2503     m_allTransitionsHaveBeenMarked = false;
2504     propagateTransitions(locker, visitor);
2505
2506     m_jitCode->dfgCommon()->livenessHasBeenProved = false;
2507     determineLiveness(locker, visitor);
2508 #endif // ENABLE(DFG_JIT)
2509 }
2510
2511 size_t CodeBlock::estimatedSize(JSCell* cell)
2512 {
2513     CodeBlock* thisObject = jsCast<CodeBlock*>(cell);
2514     size_t extraMemoryAllocated = thisObject->m_instructions.size() * sizeof(Instruction);
2515     if (thisObject->m_jitCode)
2516         extraMemoryAllocated += thisObject->m_jitCode->size();
2517     return Base::estimatedSize(cell) + extraMemoryAllocated;
2518 }
2519
2520 void CodeBlock::visitChildren(JSCell* cell, SlotVisitor& visitor)
2521 {
2522     CodeBlock* thisObject = jsCast<CodeBlock*>(cell);
2523     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
2524     JSCell::visitChildren(thisObject, visitor);
2525     thisObject->visitChildren(visitor);
2526 }
2527
2528 void CodeBlock::visitChildren(SlotVisitor& visitor)
2529 {
2530     ConcurrentJSLocker locker(m_lock);
2531     // There are two things that may use unconditional finalizers: inline cache clearing
2532     // and jettisoning. The probability of us wanting to do at least one of those things
2533     // is probably quite close to 1. So we add one no matter what and when it runs, it
2534     // figures out whether it has any work to do.
2535     visitor.addUnconditionalFinalizer(&m_unconditionalFinalizer);
2536
2537     if (CodeBlock* otherBlock = specialOSREntryBlockOrNull())
2538         visitor.appendUnbarrieredReadOnlyPointer(otherBlock);
2539
2540     if (m_jitCode)
2541         visitor.reportExtraMemoryVisited(m_jitCode->size());
2542     if (m_instructions.size()) {
2543         unsigned refCount = m_instructions.refCount();
2544         RELEASE_ASSERT(refCount);
2545         visitor.reportExtraMemoryVisited(m_instructions.size() * sizeof(Instruction) / refCount);
2546     }
2547
2548     stronglyVisitStrongReferences(locker, visitor);
2549     stronglyVisitWeakReferences(locker, visitor);
2550
2551     m_allTransitionsHaveBeenMarked = false;
2552     propagateTransitions(locker, visitor);
2553 }
2554
2555 bool CodeBlock::shouldVisitStrongly(const ConcurrentJSLocker& locker)
2556 {
2557     if (Options::forceCodeBlockLiveness())
2558         return true;
2559
2560     if (shouldJettisonDueToOldAge(locker))
2561         return false;
2562
2563     // Interpreter and Baseline JIT CodeBlocks don't need to be jettisoned when
2564     // their weak references go stale. So if a basline JIT CodeBlock gets
2565     // scanned, we can assume that this means that it's live.
2566     if (!JITCode::isOptimizingJIT(jitType()))
2567         return true;
2568
2569     return false;
2570 }
2571
2572 bool CodeBlock::shouldJettisonDueToWeakReference()
2573 {
2574     if (!JITCode::isOptimizingJIT(jitType()))
2575         return false;
2576     return !Heap::isMarked(this);
2577 }
2578
2579 static std::chrono::milliseconds timeToLive(JITCode::JITType jitType)
2580 {
2581     if (UNLIKELY(Options::useEagerCodeBlockJettisonTiming())) {
2582         switch (jitType) {
2583         case JITCode::InterpreterThunk:
2584             return std::chrono::milliseconds(10);
2585         case JITCode::BaselineJIT:
2586             return std::chrono::milliseconds(10 + 20);
2587         case JITCode::DFGJIT:
2588             return std::chrono::milliseconds(40);
2589         case JITCode::FTLJIT:
2590             return std::chrono::milliseconds(120);
2591         default:
2592             return std::chrono::milliseconds::max();
2593         }
2594     }
2595
2596     switch (jitType) {
2597     case JITCode::InterpreterThunk:
2598         return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::seconds(5));
2599     case JITCode::BaselineJIT:
2600         // Effectively 10 additional seconds, since BaselineJIT and
2601         // InterpreterThunk share a CodeBlock.
2602         return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::seconds(5 + 10));
2603     case JITCode::DFGJIT:
2604         return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::seconds(20));
2605     case JITCode::FTLJIT:
2606         return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::seconds(60));
2607     default:
2608         return std::chrono::milliseconds::max();
2609     }
2610 }
2611
2612 bool CodeBlock::shouldJettisonDueToOldAge(const ConcurrentJSLocker&)
2613 {
2614     if (Heap::isMarkedConcurrently(this))
2615         return false;
2616
2617     if (UNLIKELY(Options::forceCodeBlockToJettisonDueToOldAge()))
2618         return true;
2619     
2620     if (timeSinceCreation() < timeToLive(jitType()))
2621         return false;
2622     
2623     return true;
2624 }
2625
2626 #if ENABLE(DFG_JIT)
2627 static bool shouldMarkTransition(DFG::WeakReferenceTransition& transition)
2628 {
2629     if (transition.m_codeOrigin && !Heap::isMarkedConcurrently(transition.m_codeOrigin.get()))
2630         return false;
2631     
2632     if (!Heap::isMarkedConcurrently(transition.m_from.get()))
2633         return false;
2634     
2635     return true;
2636 }
2637 #endif // ENABLE(DFG_JIT)
2638
2639 void CodeBlock::propagateTransitions(const ConcurrentJSLocker&, SlotVisitor& visitor)
2640 {
2641     UNUSED_PARAM(visitor);
2642
2643     if (m_allTransitionsHaveBeenMarked)
2644         return;
2645
2646     bool allAreMarkedSoFar = true;
2647         
2648     Interpreter* interpreter = m_vm->interpreter;
2649     if (jitType() == JITCode::InterpreterThunk) {
2650         const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
2651         for (size_t i = 0; i < propertyAccessInstructions.size(); ++i) {
2652             Instruction* instruction = &instructions()[propertyAccessInstructions[i]];
2653             switch (interpreter->getOpcodeID(instruction[0].u.opcode)) {
2654             case op_put_by_id: {
2655                 StructureID oldStructureID = instruction[4].u.structureID;
2656                 StructureID newStructureID = instruction[6].u.structureID;
2657                 if (!oldStructureID || !newStructureID)
2658                     break;
2659                 Structure* oldStructure =
2660                     m_vm->heap.structureIDTable().get(oldStructureID);
2661                 Structure* newStructure =
2662                     m_vm->heap.structureIDTable().get(newStructureID);
2663                 if (Heap::isMarkedConcurrently(oldStructure))
2664                     visitor.appendUnbarrieredReadOnlyPointer(newStructure);
2665                 else
2666                     allAreMarkedSoFar = false;
2667                 break;
2668             }
2669             default:
2670                 break;
2671             }
2672         }
2673     }
2674
2675 #if ENABLE(JIT)
2676     if (JITCode::isJIT(jitType())) {
2677         for (Bag<StructureStubInfo>::iterator iter = m_stubInfos.begin(); !!iter; ++iter)
2678             allAreMarkedSoFar &= (*iter)->propagateTransitions(visitor);
2679     }
2680 #endif // ENABLE(JIT)
2681     
2682 #if ENABLE(DFG_JIT)
2683     if (JITCode::isOptimizingJIT(jitType())) {
2684         DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2685         for (auto& weakReference : dfgCommon->weakStructureReferences)
2686             allAreMarkedSoFar &= weakReference->markIfCheap(visitor);
2687         
2688         for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
2689             if (shouldMarkTransition(dfgCommon->transitions[i])) {
2690                 // If the following three things are live, then the target of the
2691                 // transition is also live:
2692                 //
2693                 // - This code block. We know it's live already because otherwise
2694                 //   we wouldn't be scanning ourselves.
2695                 //
2696                 // - The code origin of the transition. Transitions may arise from
2697                 //   code that was inlined. They are not relevant if the user's
2698                 //   object that is required for the inlinee to run is no longer
2699                 //   live.
2700                 //
2701                 // - The source of the transition. The transition checks if some
2702                 //   heap location holds the source, and if so, stores the target.
2703                 //   Hence the source must be live for the transition to be live.
2704                 //
2705                 // We also short-circuit the liveness if the structure is harmless
2706                 // to mark (i.e. its global object and prototype are both already
2707                 // live).
2708                 
2709                 visitor.append(&dfgCommon->transitions[i].m_to);
2710             } else
2711                 allAreMarkedSoFar = false;
2712         }
2713     }
2714 #endif // ENABLE(DFG_JIT)
2715     
2716     if (allAreMarkedSoFar)
2717         m_allTransitionsHaveBeenMarked = true;
2718 }
2719
2720 void CodeBlock::determineLiveness(const ConcurrentJSLocker&, SlotVisitor& visitor)
2721 {
2722     UNUSED_PARAM(visitor);
2723     
2724 #if ENABLE(DFG_JIT)
2725     // Check if we have any remaining work to do.
2726     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2727     if (dfgCommon->livenessHasBeenProved)
2728         return;
2729     
2730     // Now check all of our weak references. If all of them are live, then we
2731     // have proved liveness and so we scan our strong references. If at end of
2732     // GC we still have not proved liveness, then this code block is toast.
2733     bool allAreLiveSoFar = true;
2734     for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
2735         if (!Heap::isMarkedConcurrently(dfgCommon->weakReferences[i].get())) {
2736             allAreLiveSoFar = false;
2737             break;
2738         }
2739     }
2740     if (allAreLiveSoFar) {
2741         for (unsigned i = 0; i < dfgCommon->weakStructureReferences.size(); ++i) {
2742             if (!Heap::isMarkedConcurrently(dfgCommon->weakStructureReferences[i].get())) {
2743                 allAreLiveSoFar = false;
2744                 break;
2745             }
2746         }
2747     }
2748     
2749     // If some weak references are dead, then this fixpoint iteration was
2750     // unsuccessful.
2751     if (!allAreLiveSoFar)
2752         return;
2753     
2754     // All weak references are live. Record this information so we don't
2755     // come back here again, and scan the strong references.
2756     dfgCommon->livenessHasBeenProved = true;
2757     visitor.appendUnbarrieredReadOnlyPointer(this);
2758 #endif // ENABLE(DFG_JIT)
2759 }
2760
2761 void CodeBlock::WeakReferenceHarvester::visitWeakReferences(SlotVisitor& visitor)
2762 {
2763     CodeBlock* codeBlock =
2764         bitwise_cast<CodeBlock*>(
2765             bitwise_cast<char*>(this) - OBJECT_OFFSETOF(CodeBlock, m_weakReferenceHarvester));
2766     
2767     codeBlock->propagateTransitions(NoLockingNecessary, visitor);
2768     codeBlock->determineLiveness(NoLockingNecessary, visitor);
2769 }
2770
2771 void CodeBlock::clearLLIntGetByIdCache(Instruction* instruction)
2772 {
2773     instruction[0].u.opcode = LLInt::getOpcode(op_get_by_id);
2774     instruction[4].u.pointer = nullptr;
2775     instruction[5].u.pointer = nullptr;
2776     instruction[6].u.pointer = nullptr;
2777 }
2778
2779 void CodeBlock::finalizeLLIntInlineCaches()
2780 {
2781     Interpreter* interpreter = m_vm->interpreter;
2782     const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
2783     for (size_t size = propertyAccessInstructions.size(), i = 0; i < size; ++i) {
2784         Instruction* curInstruction = &instructions()[propertyAccessInstructions[i]];
2785         switch (interpreter->getOpcodeID(curInstruction[0].u.opcode)) {
2786         case op_get_by_id:
2787         case op_get_by_id_proto_load:
2788         case op_get_by_id_unset: {
2789             StructureID oldStructureID = curInstruction[4].u.structureID;
2790             if (!oldStructureID || Heap::isMarked(m_vm->heap.structureIDTable().get(oldStructureID)))
2791                 break;
2792             if (Options::verboseOSR())
2793                 dataLogF("Clearing LLInt property access.\n");
2794             clearLLIntGetByIdCache(curInstruction);
2795             break;
2796         }
2797         case op_put_by_id: {
2798             StructureID oldStructureID = curInstruction[4].u.structureID;
2799             StructureID newStructureID = curInstruction[6].u.structureID;
2800             StructureChain* chain = curInstruction[7].u.structureChain.get();
2801             if ((!oldStructureID || Heap::isMarked(m_vm->heap.structureIDTable().get(oldStructureID))) &&
2802                 (!newStructureID || Heap::isMarked(m_vm->heap.structureIDTable().get(newStructureID))) &&
2803                 (!chain || Heap::isMarked(chain)))
2804                 break;
2805             if (Options::verboseOSR())
2806                 dataLogF("Clearing LLInt put transition.\n");
2807             curInstruction[4].u.structureID = 0;
2808             curInstruction[5].u.operand = 0;
2809             curInstruction[6].u.structureID = 0;
2810             curInstruction[7].u.structureChain.clear();
2811             break;
2812         }
2813         case op_get_array_length:
2814             break;
2815         case op_to_this:
2816             if (!curInstruction[2].u.structure || Heap::isMarked(curInstruction[2].u.structure.get()))
2817                 break;
2818             if (Options::verboseOSR())
2819                 dataLogF("Clearing LLInt to_this with structure %p.\n", curInstruction[2].u.structure.get());
2820             curInstruction[2].u.structure.clear();
2821             curInstruction[3].u.toThisStatus = merge(
2822                 curInstruction[3].u.toThisStatus, ToThisClearedByGC);
2823             break;
2824         case op_create_this: {
2825             auto& cacheWriteBarrier = curInstruction[4].u.jsCell;
2826             if (!cacheWriteBarrier || cacheWriteBarrier.unvalidatedGet() == JSCell::seenMultipleCalleeObjects())
2827                 break;
2828             JSCell* cachedFunction = cacheWriteBarrier.get();
2829             if (Heap::isMarked(cachedFunction))
2830                 break;
2831             if (Options::verboseOSR())
2832                 dataLogF("Clearing LLInt create_this with cached callee %p.\n", cachedFunction);
2833             cacheWriteBarrier.clear();
2834             break;
2835         }
2836         case op_resolve_scope: {
2837             // Right now this isn't strictly necessary. Any symbol tables that this will refer to
2838             // are for outer functions, and we refer to those functions strongly, and they refer
2839             // to the symbol table strongly. But it's nice to be on the safe side.
2840             WriteBarrierBase<SymbolTable>& symbolTable = curInstruction[6].u.symbolTable;
2841             if (!symbolTable || Heap::isMarked(symbolTable.get()))
2842                 break;
2843             if (Options::verboseOSR())
2844                 dataLogF("Clearing dead symbolTable %p.\n", symbolTable.get());
2845             symbolTable.clear();
2846             break;
2847         }
2848         case op_get_from_scope:
2849         case op_put_to_scope: {
2850             GetPutInfo getPutInfo = GetPutInfo(curInstruction[4].u.operand);
2851             if (getPutInfo.resolveType() == GlobalVar || getPutInfo.resolveType() == GlobalVarWithVarInjectionChecks 
2852                 || getPutInfo.resolveType() == LocalClosureVar || getPutInfo.resolveType() == GlobalLexicalVar || getPutInfo.resolveType() == GlobalLexicalVarWithVarInjectionChecks)
2853                 continue;
2854             WriteBarrierBase<Structure>& structure = curInstruction[5].u.structure;
2855             if (!structure || Heap::isMarked(structure.get()))
2856                 break;
2857             if (Options::verboseOSR())
2858                 dataLogF("Clearing scope access with structure %p.\n", structure.get());
2859             structure.clear();
2860             break;
2861         }
2862         default:
2863             OpcodeID opcodeID = interpreter->getOpcodeID(curInstruction[0].u.opcode);
2864             ASSERT_WITH_MESSAGE_UNUSED(opcodeID, false, "Unhandled opcode in CodeBlock::finalizeUnconditionally, %s(%d) at bc %u", opcodeNames[opcodeID], opcodeID, propertyAccessInstructions[i]);
2865         }
2866     }
2867
2868     // We can't just remove all the sets when we clear the caches since we might have created a watchpoint set
2869     // then cleared the cache without GCing in between.
2870     m_llintGetByIdWatchpointMap.removeIf([](const StructureWatchpointMap::KeyValuePairType& pair) -> bool {
2871         return !Heap::isMarked(pair.key);
2872     });
2873
2874     for (unsigned i = 0; i < m_llintCallLinkInfos.size(); ++i) {
2875         if (m_llintCallLinkInfos[i].isLinked() && !Heap::isMarked(m_llintCallLinkInfos[i].callee.get())) {
2876             if (Options::verboseOSR())
2877                 dataLog("Clearing LLInt call from ", *this, "\n");
2878             m_llintCallLinkInfos[i].unlink();
2879         }
2880         if (!!m_llintCallLinkInfos[i].lastSeenCallee && !Heap::isMarked(m_llintCallLinkInfos[i].lastSeenCallee.get()))
2881             m_llintCallLinkInfos[i].lastSeenCallee.clear();
2882     }
2883 }
2884
2885 void CodeBlock::finalizeBaselineJITInlineCaches()
2886 {
2887 #if ENABLE(JIT)
2888     for (auto iter = callLinkInfosBegin(); !!iter; ++iter)
2889         (*iter)->visitWeak(*vm());
2890
2891     for (Bag<StructureStubInfo>::iterator iter = m_stubInfos.begin(); !!iter; ++iter) {
2892         StructureStubInfo& stubInfo = **iter;
2893         stubInfo.visitWeakReferences(this);
2894     }
2895 #endif
2896 }
2897
2898 void CodeBlock::UnconditionalFinalizer::finalizeUnconditionally()
2899 {
2900     CodeBlock* codeBlock = bitwise_cast<CodeBlock*>(
2901         bitwise_cast<char*>(this) - OBJECT_OFFSETOF(CodeBlock, m_unconditionalFinalizer));
2902     
2903     codeBlock->updateAllPredictions();
2904     
2905 #if ENABLE(DFG_JIT)
2906     if (codeBlock->shouldJettisonDueToWeakReference()) {
2907         codeBlock->jettison(Profiler::JettisonDueToWeakReference);
2908         return;
2909     }
2910 #endif // ENABLE(DFG_JIT)
2911
2912     if (codeBlock->shouldJettisonDueToOldAge(NoLockingNecessary)) {
2913         codeBlock->jettison(Profiler::JettisonDueToOldAge);
2914         return;
2915     }
2916
2917     if (JITCode::couldBeInterpreted(codeBlock->jitType()))
2918         codeBlock->finalizeLLIntInlineCaches();
2919
2920 #if ENABLE(JIT)
2921     if (!!codeBlock->jitCode())
2922         codeBlock->finalizeBaselineJITInlineCaches();
2923 #endif
2924 }
2925
2926 void CodeBlock::getStubInfoMap(const ConcurrentJSLocker&, StubInfoMap& result)
2927 {
2928 #if ENABLE(JIT)
2929     if (JITCode::isJIT(jitType()))
2930         toHashMap(m_stubInfos, getStructureStubInfoCodeOrigin, result);
2931 #else
2932     UNUSED_PARAM(result);
2933 #endif
2934 }
2935
2936 void CodeBlock::getStubInfoMap(StubInfoMap& result)
2937 {
2938     ConcurrentJSLocker locker(m_lock);
2939     getStubInfoMap(locker, result);
2940 }
2941
2942 void CodeBlock::getCallLinkInfoMap(const ConcurrentJSLocker&, CallLinkInfoMap& result)
2943 {
2944 #if ENABLE(JIT)
2945     if (JITCode::isJIT(jitType()))
2946         toHashMap(m_callLinkInfos, getCallLinkInfoCodeOrigin, result);
2947 #else
2948     UNUSED_PARAM(result);
2949 #endif
2950 }
2951
2952 void CodeBlock::getCallLinkInfoMap(CallLinkInfoMap& result)
2953 {
2954     ConcurrentJSLocker locker(m_lock);
2955     getCallLinkInfoMap(locker, result);
2956 }
2957
2958 void CodeBlock::getByValInfoMap(const ConcurrentJSLocker&, ByValInfoMap& result)
2959 {
2960 #if ENABLE(JIT)
2961     if (JITCode::isJIT(jitType())) {
2962         for (auto* byValInfo : m_byValInfos)
2963             result.add(CodeOrigin(byValInfo->bytecodeIndex), byValInfo);
2964     }
2965 #else
2966     UNUSED_PARAM(result);
2967 #endif
2968 }
2969
2970 void CodeBlock::getByValInfoMap(ByValInfoMap& result)
2971 {
2972     ConcurrentJSLocker locker(m_lock);
2973     getByValInfoMap(locker, result);
2974 }
2975
2976 #if ENABLE(JIT)
2977 StructureStubInfo* CodeBlock::addStubInfo(AccessType accessType)
2978 {
2979     ConcurrentJSLocker locker(m_lock);
2980     return m_stubInfos.add(accessType);
2981 }
2982
2983 JITAddIC* CodeBlock::addJITAddIC(ArithProfile* arithProfile)
2984 {
2985     return m_addICs.add(arithProfile);
2986 }
2987
2988 JITMulIC* CodeBlock::addJITMulIC(ArithProfile* arithProfile)
2989 {
2990     return m_mulICs.add(arithProfile);
2991 }
2992
2993 JITSubIC* CodeBlock::addJITSubIC(ArithProfile* arithProfile)
2994 {
2995     return m_subICs.add(arithProfile);
2996 }
2997
2998 JITNegIC* CodeBlock::addJITNegIC(ArithProfile* arithProfile)
2999 {
3000     return m_negICs.add(arithProfile);
3001 }
3002
3003 StructureStubInfo* CodeBlock::findStubInfo(CodeOrigin codeOrigin)
3004 {
3005     for (StructureStubInfo* stubInfo : m_stubInfos) {
3006         if (stubInfo->codeOrigin == codeOrigin)
3007             return stubInfo;
3008     }
3009     return nullptr;
3010 }
3011
3012 ByValInfo* CodeBlock::addByValInfo()
3013 {
3014     ConcurrentJSLocker locker(m_lock);
3015     return m_byValInfos.add();
3016 }
3017
3018 CallLinkInfo* CodeBlock::addCallLinkInfo()
3019 {
3020     ConcurrentJSLocker locker(m_lock);
3021     return m_callLinkInfos.add();
3022 }
3023
3024 CallLinkInfo* CodeBlock::getCallLinkInfoForBytecodeIndex(unsigned index)
3025 {
3026     for (auto iter = m_callLinkInfos.begin(); !!iter; ++iter) {
3027         if ((*iter)->codeOrigin() == CodeOrigin(index))
3028             return *iter;
3029     }
3030     return nullptr;
3031 }
3032
3033 void CodeBlock::resetJITData()
3034 {
3035     RELEASE_ASSERT(!JITCode::isJIT(jitType()));
3036     ConcurrentJSLocker locker(m_lock);
3037     
3038     // We can clear these because no other thread will have references to any stub infos, call
3039     // link infos, or by val infos if we don't have JIT code. Attempts to query these data
3040     // structures using the concurrent API (getStubInfoMap and friends) will return nothing if we
3041     // don't have JIT code.
3042     m_stubInfos.clear();
3043     m_callLinkInfos.clear();
3044     m_byValInfos.clear();
3045     
3046     // We can clear this because the DFG's queries to these data structures are guarded by whether
3047     // there is JIT code.
3048     m_rareCaseProfiles.clear();
3049 }
3050 #endif
3051
3052 void CodeBlock::visitOSRExitTargets(const ConcurrentJSLocker&, SlotVisitor& visitor)
3053 {
3054     // We strongly visit OSR exits targets because we don't want to deal with
3055     // the complexity of generating an exit target CodeBlock on demand and
3056     // guaranteeing that it matches the details of the CodeBlock we compiled
3057     // the OSR exit against.
3058
3059     visitor.append(&m_alternative);
3060
3061 #if ENABLE(DFG_JIT)
3062     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
3063     if (dfgCommon->inlineCallFrames) {
3064         for (auto* inlineCallFrame : *dfgCommon->inlineCallFrames) {
3065             ASSERT(inlineCallFrame->baselineCodeBlock);
3066             visitor.append(&inlineCallFrame->baselineCodeBlock);
3067         }
3068     }
3069 #endif
3070 }
3071
3072 void CodeBlock::stronglyVisitStrongReferences(const ConcurrentJSLocker& locker, SlotVisitor& visitor)
3073 {
3074     UNUSED_PARAM(locker);
3075     
3076     visitor.append(&m_globalObject);
3077     visitor.append(&m_ownerExecutable);
3078     visitor.append(&m_unlinkedCode);
3079     if (m_rareData)
3080         m_rareData->m_directEvalCodeCache.visitAggregate(visitor);
3081     visitor.appendValues(m_constantRegisters.data(), m_constantRegisters.size());
3082     for (size_t i = 0; i < m_functionExprs.size(); ++i)
3083         visitor.append(&m_functionExprs[i]);
3084     for (size_t i = 0; i < m_functionDecls.size(); ++i)
3085         visitor.append(&m_functionDecls[i]);
3086     for (unsigned i = 0; i < m_objectAllocationProfiles.size(); ++i)
3087         m_objectAllocationProfiles[i].visitAggregate(visitor);
3088
3089 #if ENABLE(JIT)
3090     for (ByValInfo* byValInfo : m_byValInfos)
3091         visitor.append(&byValInfo->cachedSymbol);
3092 #endif
3093
3094 #if ENABLE(DFG_JIT)
3095     if (JITCode::isOptimizingJIT(jitType()))
3096         visitOSRExitTargets(locker, visitor);
3097 #endif
3098 }
3099
3100 void CodeBlock::stronglyVisitWeakReferences(const ConcurrentJSLocker&, SlotVisitor& visitor)
3101 {
3102     UNUSED_PARAM(visitor);
3103
3104 #if ENABLE(DFG_JIT)
3105     if (!JITCode::isOptimizingJIT(jitType()))
3106         return;
3107     
3108     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
3109
3110     for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
3111         if (!!dfgCommon->transitions[i].m_codeOrigin)
3112             visitor.append(&dfgCommon->transitions[i].m_codeOrigin); // Almost certainly not necessary, since the code origin should also be a weak reference. Better to be safe, though.
3113         visitor.append(&dfgCommon->transitions[i].m_from);
3114         visitor.append(&dfgCommon->transitions[i].m_to);
3115     }
3116     
3117     for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i)
3118         visitor.append(&dfgCommon->weakReferences[i]);
3119
3120     for (unsigned i = 0; i < dfgCommon->weakStructureReferences.size(); ++i)
3121         visitor.append(&dfgCommon->weakStructureReferences[i]);
3122
3123     dfgCommon->livenessHasBeenProved = true;
3124 #endif    
3125 }
3126
3127 CodeBlock* CodeBlock::baselineAlternative()
3128 {
3129 #if ENABLE(JIT)
3130     CodeBlock* result = this;
3131     while (result->alternative())
3132         result = result->alternative();
3133     RELEASE_ASSERT(result);
3134     RELEASE_ASSERT(JITCode::isBaselineCode(result->jitType()) || result->jitType() == JITCode::None);
3135     return result;
3136 #else
3137     return this;
3138 #endif
3139 }
3140
3141 CodeBlock* CodeBlock::baselineVersion()
3142 {
3143 #if ENABLE(JIT)
3144     if (JITCode::isBaselineCode(jitType()))
3145         return this;
3146     CodeBlock* result = replacement();
3147     if (!result) {
3148         // This can happen if we're creating the original CodeBlock for an executable.
3149         // Assume that we're the baseline CodeBlock.
3150         RELEASE_ASSERT(jitType() == JITCode::None);
3151         return this;
3152     }
3153     result = result->baselineAlternative();
3154     return result;
3155 #else
3156     return this;
3157 #endif
3158 }
3159
3160 #if ENABLE(JIT)
3161 bool CodeBlock::hasOptimizedReplacement(JITCode::JITType typeToReplace)
3162 {
3163     return JITCode::isHigherTier(replacement()->jitType(), typeToReplace);
3164 }
3165
3166 bool CodeBlock::hasOptimizedReplacement()
3167 {
3168     return hasOptimizedReplacement(jitType());
3169 }
3170 #endif
3171
3172 HandlerInfo* CodeBlock::handlerForBytecodeOffset(unsigned bytecodeOffset, RequiredHandler requiredHandler)
3173 {
3174     RELEASE_ASSERT(bytecodeOffset < instructions().size());
3175     return handlerForIndex(bytecodeOffset, requiredHandler);
3176 }
3177
3178 HandlerInfo* CodeBlock::handlerForIndex(unsigned index, RequiredHandler requiredHandler)
3179 {
3180     if (!m_rareData)
3181         return 0;
3182     return HandlerInfo::handlerForIndex(m_rareData->m_exceptionHandlers, index, requiredHandler);
3183 }
3184
3185 CallSiteIndex CodeBlock::newExceptionHandlingCallSiteIndex(CallSiteIndex originalCallSite)
3186 {
3187 #if ENABLE(DFG_JIT)
3188     RELEASE_ASSERT(JITCode::isOptimizingJIT(jitType()));
3189     RELEASE_ASSERT(canGetCodeOrigin(originalCallSite));
3190     ASSERT(!!handlerForIndex(originalCallSite.bits()));
3191     CodeOrigin originalOrigin = codeOrigin(originalCallSite);
3192     return m_jitCode->dfgCommon()->addUniqueCallSiteIndex(originalOrigin);
3193 #else
3194     // We never create new on-the-fly exception handling
3195     // call sites outside the DFG/FTL inline caches.
3196     UNUSED_PARAM(originalCallSite);
3197     RELEASE_ASSERT_NOT_REACHED();
3198     return CallSiteIndex(0u);
3199 #endif
3200 }
3201
3202 void CodeBlock::removeExceptionHandlerForCallSite(CallSiteIndex callSiteIndex)
3203 {
3204     RELEASE_ASSERT(m_rareData);
3205     Vector<HandlerInfo>& exceptionHandlers = m_rareData->m_exceptionHandlers;
3206     unsigned index = callSiteIndex.bits();
3207     for (size_t i = 0; i < exceptionHandlers.size(); ++i) {
3208         HandlerInfo& handler = exceptionHandlers[i];
3209         if (handler.start <= index && handler.end > index) {
3210             exceptionHandlers.remove(i);
3211             return;
3212         }
3213     }
3214
3215     RELEASE_ASSERT_NOT_REACHED();
3216 }
3217
3218 unsigned CodeBlock::lineNumberForBytecodeOffset(unsigned bytecodeOffset)
3219 {
3220     RELEASE_ASSERT(bytecodeOffset < instructions().size());
3221     return ownerScriptExecutable()->firstLine() + m_unlinkedCode->lineNumberForBytecodeOffset(bytecodeOffset);
3222 }
3223
3224 unsigned CodeBlock::columnNumberForBytecodeOffset(unsigned bytecodeOffset)
3225 {
3226     int divot;
3227     int startOffset;
3228     int endOffset;
3229     unsigned line;
3230     unsigned column;
3231     expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
3232     return column;
3233 }
3234
3235 void CodeBlock::expressionRangeForBytecodeOffset(unsigned bytecodeOffset, int& divot, int& startOffset, int& endOffset, unsigned& line, unsigned& column) const
3236 {
3237     m_unlinkedCode->expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
3238     divot += m_sourceOffset;
3239     column += line ? 1 : firstLineColumnOffset();
3240     line += ownerScriptExecutable()->firstLine();
3241 }
3242
3243 bool CodeBlock::hasOpDebugForLineAndColumn(unsigned line, unsigned column)
3244 {
3245     Interpreter* interpreter = vm()->interpreter;
3246     const Instruction* begin = instructions().begin();
3247     const Instruction* end = instructions().end();
3248     for (const Instruction* it = begin; it != end;) {
3249         OpcodeID opcodeID = interpreter->getOpcodeID(it->u.opcode);
3250         if (opcodeID == op_debug) {
3251             unsigned bytecodeOffset = it - begin;
3252             int unused;
3253             unsigned opDebugLine;
3254             unsigned opDebugColumn;
3255             expressionRangeForBytecodeOffset(bytecodeOffset, unused, unused, unused, opDebugLine, opDebugColumn);
3256             if (line == opDebugLine && (column == Breakpoint::unspecifiedColumn || column == opDebugColumn))
3257                 return true;
3258         }
3259         it += opcodeLengths[opcodeID];
3260     }
3261     return false;
3262 }
3263
3264 void CodeBlock::shrinkToFit(ShrinkMode shrinkMode)
3265 {
3266     ConcurrentJSLocker locker(m_lock);
3267
3268     m_rareCaseProfiles.shrinkToFit();
3269     
3270     if (shrinkMode == EarlyShrink) {
3271         m_constantRegisters.shrinkToFit();
3272         m_constantsSourceCodeRepresentation.shrinkToFit();
3273         
3274         if (m_rareData) {
3275             m_rareData->m_switchJumpTables.shrinkToFit();
3276             m_rareData->m_stringSwitchJumpTables.shrinkToFit();
3277         }
3278     } // else don't shrink these, because we would have already pointed pointers into these tables.
3279 }
3280
3281 #if ENABLE(JIT)
3282 void CodeBlock::linkIncomingCall(ExecState* callerFrame, CallLinkInfo* incoming)
3283 {
3284     noticeIncomingCall(callerFrame);
3285     m_incomingCalls.push(incoming);
3286 }
3287
3288 void CodeBlock::linkIncomingPolymorphicCall(ExecState* callerFrame, PolymorphicCallNode* incoming)
3289 {
3290     noticeIncomingCall(callerFrame);
3291     m_incomingPolymorphicCalls.push(incoming);
3292 }
3293 #endif // ENABLE(JIT)
3294
3295 void CodeBlock::unlinkIncomingCalls()
3296 {
3297     while (m_incomingLLIntCalls.begin() != m_incomingLLIntCalls.end())
3298         m_incomingLLIntCalls.begin()->unlink();
3299 #if ENABLE(JIT)
3300     while (m_incomingCalls.begin() != m_incomingCalls.end())
3301         m_incomingCalls.begin()->unlink(*vm());
3302     while (m_incomingPolymorphicCalls.begin() != m_incomingPolymorphicCalls.end())
3303         m_incomingPolymorphicCalls.begin()->unlink(*vm());
3304 #endif // ENABLE(JIT)
3305 }
3306
3307 void CodeBlock::linkIncomingCall(ExecState* callerFrame, LLIntCallLinkInfo* incoming)
3308 {
3309     noticeIncomingCall(callerFrame);
3310     m_incomingLLIntCalls.push(incoming);
3311 }
3312
3313 CodeBlock* CodeBlock::newReplacement()
3314 {
3315     return ownerScriptExecutable()->newReplacementCodeBlockFor(specializationKind());
3316 }
3317
3318 #if ENABLE(JIT)
3319 CodeBlock* CodeBlock::replacement()
3320 {
3321     const ClassInfo* classInfo = this->classInfo();
3322
3323     if (classInfo == FunctionCodeBlock::info())
3324         return jsCast<FunctionExecutable*>(ownerExecutable())->codeBlockFor(m_isConstructor ? CodeForConstruct : CodeForCall);
3325
3326     if (classInfo == EvalCodeBlock::info())
3327         return jsCast<EvalExecutable*>(ownerExecutable())->codeBlock();
3328
3329     if (classInfo == ProgramCodeBlock::info())
3330         return jsCast<ProgramExecutable*>(ownerExecutable())->codeBlock();
3331
3332     if (classInfo == ModuleProgramCodeBlock::info())
3333         return jsCast<ModuleProgramExecutable*>(ownerExecutable())->codeBlock();
3334
3335     RELEASE_ASSERT_NOT_REACHED();
3336     return nullptr;
3337 }
3338
3339 DFG::CapabilityLevel CodeBlock::computeCapabilityLevel()
3340 {
3341     const ClassInfo* classInfo = this->classInfo();
3342
3343     if (classInfo == FunctionCodeBlock::info()) {
3344         if (m_isConstructor)
3345             return DFG::functionForConstructCapabilityLevel(this);
3346         return DFG::functionForCallCapabilityLevel(this);
3347     }
3348
3349     if (classInfo == EvalCodeBlock::info())
3350         return DFG::evalCapabilityLevel(this);
3351
3352     if (classInfo == ProgramCodeBlock::info())
3353         return DFG::programCapabilityLevel(this);
3354
3355     if (classInfo == ModuleProgramCodeBlock::info())
3356         return DFG::programCapabilityLevel(this);
3357
3358     RELEASE_ASSERT_NOT_REACHED();
3359     return DFG::CannotCompile;
3360 }
3361
3362 #endif // ENABLE(JIT)
3363
3364 void CodeBlock::jettison(Profiler::JettisonReason reason, ReoptimizationMode mode, const FireDetail* detail)
3365 {
3366 #if !ENABLE(DFG_JIT)
3367     UNUSED_PARAM(mode);
3368     UNUSED_PARAM(detail);
3369 #endif
3370     
3371     CODEBLOCK_LOG_EVENT(this, "jettison", ("due to ", reason, ", counting = ", mode == CountReoptimization, ", detail = ", pointerDump(detail)));
3372
3373     RELEASE_ASSERT(reason != Profiler::NotJettisoned);
3374     
3375 #if ENABLE(DFG_JIT)
3376     if (DFG::shouldDumpDisassembly()) {
3377         dataLog("Jettisoning ", *this);
3378         if (mode == CountReoptimization)
3379             dataLog(" and counting reoptimization");
3380         dataLog(" due to ", reason);
3381         if (detail)
3382             dataLog(", ", *detail);
3383         dataLog(".\n");
3384     }
3385     
3386     if (reason == Profiler::JettisonDueToWeakReference) {
3387         if (DFG::shouldDumpDisassembly()) {
3388             dataLog(*this, " will be jettisoned because of the following dead references:\n");
3389             DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
3390             for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
3391                 DFG::WeakReferenceTransition& transition = dfgCommon->transitions[i];
3392                 JSCell* origin = transition.m_codeOrigin.get();
3393                 JSCell* from = transition.m_from.get();
3394                 JSCell* to = transition.m_to.get();
3395                 if ((!origin || Heap::isMarked(origin)) && Heap::isMarked(from))
3396                     continue;
3397                 dataLog("    Transition under ", RawPointer(origin), ", ", RawPointer(from), " -> ", RawPointer(to), ".\n");
3398             }
3399             for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
3400                 JSCell* weak = dfgCommon->weakReferences[i].get();
3401                 if (Heap::isMarked(weak))
3402                     continue;
3403                 dataLog("    Weak reference ", RawPointer(weak), ".\n");
3404             }
3405         }
3406     }
3407 #endif // ENABLE(DFG_JIT)
3408
3409     DeferGCForAWhile deferGC(*heap());
3410     
3411     // We want to accomplish two things here:
3412     // 1) Make sure that if this CodeBlock is on the stack right now, then if we return to it
3413     //    we should OSR exit at the top of the next bytecode instruction after the return.
3414     // 2) Make sure that if we call the owner executable, then we shouldn't call this CodeBlock.
3415
3416 #if ENABLE(DFG_JIT)
3417     if (reason != Profiler::JettisonDueToOldAge) {
3418         if (Profiler::Compilation* compilation = jitCode()->dfgCommon()->compilation.get())
3419             compilation->setJettisonReason(reason, detail);
3420         
3421         // This accomplishes (1), and does its own book-keeping about whether it has already happened.
3422         if (!jitCode()->dfgCommon()->invalidate()) {
3423             // We've already been invalidated.
3424             RELEASE_ASSERT(this != replacement() || (m_vm->heap.isCurrentThreadBusy() && !Heap::isMarked(ownerScriptExecutable())));
3425             return;
3426         }
3427     }
3428     
3429     if (DFG::shouldDumpDisassembly())
3430         dataLog("    Did invalidate ", *this, "\n");
3431     
3432     // Count the reoptimization if that's what the user wanted.
3433     if (mode == CountReoptimization) {
3434         // FIXME: Maybe this should call alternative().
3435         // https://bugs.webkit.org/show_bug.cgi?id=123677
3436         baselineAlternative()->countReoptimization();
3437         if (DFG::shouldDumpDisassembly())
3438             dataLog("    Did count reoptimization for ", *this, "\n");
3439     }
3440     
3441     if (this != replacement()) {
3442         // This means that we were never the entrypoint. This can happen for OSR entry code
3443         // blocks.
3444         return;
3445     }
3446
3447     if (alternative())
3448         alternative()->optimizeAfterWarmUp();
3449
3450     if (reason != Profiler::JettisonDueToOldAge)
3451         tallyFrequentExitSites();
3452 #endif // ENABLE(DFG_JIT)
3453
3454     // Jettison can happen during GC. We don't want to install code to a dead executable
3455     // because that would add a dead object to the remembered set.
3456     if (m_vm->heap.isCurrentThreadBusy() && !Heap::isMarked(ownerScriptExecutable()))
3457         return;
3458
3459     // This accomplishes (2).
3460     ownerScriptExecutable()->installCode(
3461         m_globalObject->vm(), alternative(), codeType(), specializationKind());
3462
3463 #if ENABLE(DFG_JIT)
3464     if (DFG::shouldDumpDisassembly())
3465         dataLog("    Did install baseline version of ", *this, "\n");
3466 #endif // ENABLE(DFG_JIT)
3467 }
3468
3469 JSGlobalObject* CodeBlock::globalObjectFor(CodeOrigin codeOrigin)
3470 {
3471     if (!codeOrigin.inlineCallFrame)
3472         return globalObject();
3473     return codeOrigin.inlineCallFrame->baselineCodeBlock->globalObject();
3474 }
3475
3476 class RecursionCheckFunctor {
3477 public:
3478     RecursionCheckFunctor(CallFrame* startCallFrame, CodeBlock* codeBlock, unsigned depthToCheck)
3479         : m_startCallFrame(startCallFrame)
3480         , m_codeBlock(codeBlock)
3481         , m_depthToCheck(depthToCheck)
3482         , m_foundStartCallFrame(false)
3483         , m_didRecurse(false)
3484     { }
3485
3486     StackVisitor::Status operator()(StackVisitor& visitor) const
3487     {
3488         CallFrame* currentCallFrame = visitor->callFrame();
3489
3490         if (currentCallFrame == m_startCallFrame)
3491             m_foundStartCallFrame = true;
3492
3493         if (m_foundStartCallFrame) {
3494             if (visitor->callFrame()->codeBlock() == m_codeBlock) {
3495                 m_didRecurse = true;
3496                 return StackVisitor::Done;
3497             }
3498
3499             if (!m_depthToCheck--)
3500                 return StackVisitor::Done;
3501         }
3502
3503         return StackVisitor::Continue;
3504     }
3505
3506     bool didRecurse() const { return m_didRecurse; }
3507
3508 private:
3509     CallFrame* m_startCallFrame;
3510     CodeBlock* m_codeBlock;
3511     mutable unsigned m_depthToCheck;
3512     mutable bool m_foundStartCallFrame;
3513     mutable bool m_didRecurse;
3514 };
3515
3516 void CodeBlock::noticeIncomingCall(ExecState* callerFrame)
3517 {
3518     CodeBlock* callerCodeBlock = callerFrame->codeBlock();
3519     
3520     if (Options::verboseCallLink())
3521         dataLog("Noticing call link from ", pointerDump(callerCodeBlock), " to ", *this, "\n");
3522     
3523 #if ENABLE(DFG_JIT)
3524     if (!m_shouldAlwaysBeInlined)
3525         return;
3526     
3527     if (!callerCodeBlock) {
3528         m_shouldAlwaysBeInlined = false;
3529         if (Options::verboseCallLink())
3530             dataLog("    Clearing SABI because caller is native.\n");
3531         return;
3532     }
3533
3534     if (!hasBaselineJITProfiling())
3535         return;
3536
3537     if (!DFG::mightInlineFunction(this))
3538         return;
3539
3540     if (!canInline(capabilityLevelState()))
3541         return;
3542     
3543     if (!DFG::isSmallEnoughToInlineCodeInto(callerCodeBlock)) {
3544         m_shouldAlwaysBeInlined = false;
3545         if (Options::verboseCallLink())
3546             dataLog("    Clearing SABI because caller is too large.\n");
3547         return;
3548     }
3549
3550     if (callerCodeBlock->jitType() == JITCode::InterpreterThunk) {
3551         // If the caller is still in the interpreter, then we can't expect inlining to
3552         // happen anytime soon. Assume it's profitable to optimize it separately. This
3553         // ensures that a function is SABI only if it is called no more frequently than
3554         // any of its callers.
3555         m_shouldAlwaysBeInlined = false;
3556         if (Options::verboseCallLink())
3557             dataLog("    Clearing SABI because caller is in LLInt.\n");
3558         return;
3559     }
3560     
3561     if (JITCode::isOptimizingJIT(callerCodeBlock->jitType())) {
3562         m_shouldAlwaysBeInlined = false;
3563         if (Options::verboseCallLink())
3564             dataLog("    Clearing SABI bcause caller was already optimized.\n");
3565         return;
3566     }
3567     
3568     if (callerCodeBlock->codeType() != FunctionCode) {
3569         // If the caller is either eval or global code, assume that that won't be
3570         // optimized anytime soon. For eval code this is particularly true since we
3571         // delay eval optimization by a *lot*.
3572         m_shouldAlwaysBeInlined = false;
3573         if (Options::verboseCallLink())
3574             dataLog("    Clearing SABI because caller is not a function.\n");
3575         return;
3576     }
3577
3578     // Recursive calls won't be inlined.
3579     RecursionCheckFunctor functor(callerFrame, this, Options::maximumInliningDepth());
3580     vm()->topCallFrame->iterate(functor);
3581
3582     if (functor.didRecurse()) {
3583         if (Options::verboseCallLink())
3584             dataLog("    Clearing SABI because recursion was detected.\n");
3585         m_shouldAlwaysBeInlined = false;
3586         return;
3587     }
3588     
3589     if (callerCodeBlock->capabilityLevelState() == DFG::CapabilityLevelNotSet) {
3590         dataLog("In call from ", *callerCodeBlock, " ", callerFrame->codeOrigin(), " to ", *this, ": caller's DFG capability level is not set.\n");
3591         CRASH();
3592     }
3593     
3594     if (canCompile(callerCodeBlock->capabilityLevelState()))
3595         return;
3596     
3597     if (Options::verboseCallLink())
3598         dataLog("    Clearing SABI because the caller is not a DFG candidate.\n");
3599     
3600     m_shouldAlwaysBeInlined = false;
3601 #endif
3602 }
3603
3604 unsigned CodeBlock::reoptimizationRetryCounter() const
3605 {
3606 #if ENABLE(JIT)
3607     ASSERT(m_reoptimizationRetryCounter <= Options::reoptimizationRetryCounterMax());
3608     return m_reoptimizationRetryCounter;
3609 #else
3610     return 0;
3611 #endif // ENABLE(JIT)
3612 }
3613
3614 #if ENABLE(JIT)
3615 void CodeBlock::setCalleeSaveRegisters(RegisterSet calleeSaveRegisters)
3616 {
3617     m_calleeSaveRegisters = std::make_unique<RegisterAtOffsetList>(calleeSaveRegisters);
3618 }
3619
3620 void CodeBlock::setCalleeSaveRegisters(std::unique_ptr<RegisterAtOffsetList> registerAtOffsetList)
3621 {
3622     m_calleeSaveRegisters = WTFMove(registerAtOffsetList);
3623 }
3624     
3625 static size_t roundCalleeSaveSpaceAsVirtualRegisters(size_t calleeSaveRegisters)
3626 {
3627     static const unsigned cpuRegisterSize = sizeof(void*);
3628     return (WTF::roundUpToMultipleOf(sizeof(Register), calleeSaveRegisters * cpuRegisterSize) / sizeof(Register));
3629
3630 }
3631
3632 size_t CodeBlock::llintBaselineCalleeSaveSpaceAsVirtualRegisters()
3633 {
3634     return roundCalleeSaveSpaceAsVirtualRegisters(numberOfLLIntBaselineCalleeSaveRegisters());
3635 }
3636
3637 size_t CodeBlock::calleeSaveSpaceAsVirtualRegisters()
3638 {
3639     return roundCalleeSaveSpaceAsVirtualRegisters(m_calleeSaveRegisters->size());
3640 }
3641
3642 void CodeBlock::countReoptimization()
3643 {
3644     m_reoptimizationRetryCounter++;
3645     if (m_reoptimizationRetryCounter > Options::reoptimizationRetryCounterMax())
3646         m_reoptimizationRetryCounter = Options::reoptimizationRetryCounterMax();
3647 }
3648
3649 unsigned CodeBlock::numberOfDFGCompiles()
3650 {
3651     ASSERT(JITCode::isBaselineCode(jitType()));
3652     if (Options::testTheFTL()) {
3653         if (m_didFailFTLCompilation)
3654             return 1000000;
3655         return (m_hasBeenCompiledWithFTL ? 1 : 0) + m_reoptimizationRetryCounter;
3656     }
3657     return (JITCode::isOptimizingJIT(replacement()->jitType()) ? 1 : 0) + m_reoptimizationRetryCounter;
3658 }
3659
3660 int32_t CodeBlock::codeTypeThresholdMultiplier() const
3661 {
3662     if (codeType() == EvalCode)
3663         return Options::evalThresholdMultiplier();
3664     
3665     return 1;
3666 }
3667
3668 double CodeBlock::optimizationThresholdScalingFactor()
3669 {
3670     // This expression arises from doing a least-squares fit of
3671     //
3672     // F[x_] =: a * Sqrt[x + b] + Abs[c * x] + d
3673     //
3674     // against the data points:
3675     //
3676     //    x       F[x_]
3677     //    10       0.9          (smallest reasonable code block)
3678     //   200       1.0          (typical small-ish code block)
3679     //   320       1.2          (something I saw in 3d-cube that I wanted to optimize)
3680     //  1268       5.0          (something I saw in 3d-cube that I didn't want to optimize)
3681     //  4000       5.5          (random large size, used to cause the function to converge to a shallow curve of some sort)
3682     // 10000       6.0          (similar to above)
3683     //
3684     // I achieve the minimization using the following Mathematica code:
3685     //
3686     // MyFunctionTemplate[x_, a_, b_, c_, d_] := a*Sqrt[x + b] + Abs[c*x] + d
3687     //
3688     // samples = {{10, 0.9}, {200, 1}, {320, 1.2}, {1268, 5}, {4000, 5.5}, {10000, 6}}
3689     //
3690     // solution = 
3691     //     Minimize[Plus @@ ((MyFunctionTemplate[#[[1]], a, b, c, d] - #[[2]])^2 & /@ samples),
3692     //         {a, b, c, d}][[2]]
3693     //
3694     // And the code below (to initialize a, b, c, d) is generated by:
3695     //
3696     // Print["const double " <> ToString[#[[1]]] <> " = " <>
3697     //     If[#[[2]] < 0.00001, "0.0", ToString[#[[2]]]] <> ";"] & /@ solution
3698     //
3699     // We've long known the following to be true:
3700     // - Small code blocks are cheap to optimize and so we should do it sooner rather
3701     //   than later.
3702     // - Large code blocks are expensive to optimize and so we should postpone doing so,
3703     //   and sometimes have a large enough threshold that we never optimize them.
3704     // - The difference in cost is not totally linear because (a) just invoking the
3705     //   DFG incurs some base cost and (b) for large code blocks there is enough slop
3706     //   in the correlation between instruction count and the actual compilation cost
3707     //   that for those large blocks, the instruction count should not have a strong
3708     //   influence on our threshold.
3709     //
3710     // I knew the goals but I didn't know how to achieve them; so I picked an interesting
3711     // example where the heuristics were right (code block in 3d-cube with instruction
3712     // count 320, which got compiled early as it should have been) and one where they were
3713     // totally wrong (code block in 3d-cube with instruction count 1268, which was expensive
3714     // to compile and didn't run often enough to warrant compilation in my opinion), and
3715     // then threw in additional data points that represented my own guess of what our
3716     // heuristics should do for some round-numbered examples.
3717     //
3718     // The expression to which I decided to fit the data arose because I started with an
3719     // affine function, and then did two things: put the linear part in an Abs to ensure
3720     // that the fit didn't end up choosing a negative value of c (which would result in
3721     // the function turning over and going negative for large x) and I threw in a Sqrt
3722     // term because Sqrt represents my intution that the function should be more sensitive
3723     // to small changes in small values of x, but less sensitive when x gets large.
3724     
3725     // Note that the current fit essentially eliminates the linear portion of the
3726     // expression (c == 0.0).