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