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