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