Add support for Symbol.isConcatSpreadable (round 2)
[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_jsarray: {
1105             printUnaryOp(out, exec, location, it, "is_jsarray");
1106             break;
1107         }
1108         case op_is_object: {
1109             printUnaryOp(out, exec, location, it, "is_object");
1110             break;
1111         }
1112         case op_is_object_or_null: {
1113             printUnaryOp(out, exec, location, it, "is_object_or_null");
1114             break;
1115         }
1116         case op_is_function: {
1117             printUnaryOp(out, exec, location, it, "is_function");
1118             break;
1119         }
1120         case op_in: {
1121             printBinaryOp(out, exec, location, it, "in");
1122             break;
1123         }
1124         case op_try_get_by_id: {
1125             int r0 = (++it)->u.operand;
1126             int r1 = (++it)->u.operand;
1127             int id0 = (++it)->u.operand;
1128             printLocationAndOp(out, exec, location, it, "try_get_by_id");
1129             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), idName(id0, identifier(id0)).data());
1130             break;
1131         }
1132         case op_get_by_id:
1133         case op_get_by_id_proto_load:
1134         case op_get_by_id_unset:
1135         case op_get_array_length: {
1136             printGetByIdOp(out, exec, location, it);
1137             printGetByIdCacheStatus(out, exec, location, stubInfos);
1138             dumpValueProfiling(out, it, hasPrintedProfiling);
1139             break;
1140         }
1141         case op_get_by_id_with_this: {
1142             printLocationAndOp(out, exec, location, it, "get_by_id_with_this");
1143             int r0 = (++it)->u.operand;
1144             int r1 = (++it)->u.operand;
1145             int r2 = (++it)->u.operand;
1146             int id0 = (++it)->u.operand;
1147             out.printf("%s, %s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data(), idName(id0, identifier(id0)).data());
1148             break;
1149         }
1150         case op_get_by_val_with_this: {
1151             int r0 = (++it)->u.operand;
1152             int r1 = (++it)->u.operand;
1153             int r2 = (++it)->u.operand;
1154             int r3 = (++it)->u.operand;
1155             printLocationAndOp(out, exec, location, it, "get_by_val_with_this");
1156             out.printf("%s, %s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data(), registerName(r3).data());
1157             break;
1158         }
1159         case op_put_by_id: {
1160             printPutByIdOp(out, exec, location, it, "put_by_id");
1161             printPutByIdCacheStatus(out, location, stubInfos);
1162             break;
1163         }
1164         case op_put_by_id_with_this: {
1165             int r0 = (++it)->u.operand;
1166             int r1 = (++it)->u.operand;
1167             int id0 = (++it)->u.operand;
1168             int r2 = (++it)->u.operand;
1169             printLocationAndOp(out, exec, location, it, "put_by_id_with_this");
1170             out.printf("%s, %s, %s, %s", registerName(r0).data(), registerName(r1).data(), idName(id0, identifier(id0)).data(), registerName(r2).data());
1171             break;
1172         }
1173         case op_put_by_val_with_this: {
1174             int r0 = (++it)->u.operand;
1175             int r1 = (++it)->u.operand;
1176             int r2 = (++it)->u.operand;
1177             int r3 = (++it)->u.operand;
1178             printLocationAndOp(out, exec, location, it, "put_by_val_with_this");
1179             out.printf("%s, %s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data(), registerName(r3).data());
1180             break;
1181         }
1182         case op_put_getter_by_id: {
1183             int r0 = (++it)->u.operand;
1184             int id0 = (++it)->u.operand;
1185             int n0 = (++it)->u.operand;
1186             int r1 = (++it)->u.operand;
1187             printLocationAndOp(out, exec, location, it, "put_getter_by_id");
1188             out.printf("%s, %s, %d, %s", registerName(r0).data(), idName(id0, identifier(id0)).data(), n0, registerName(r1).data());
1189             break;
1190         }
1191         case op_put_setter_by_id: {
1192             int r0 = (++it)->u.operand;
1193             int id0 = (++it)->u.operand;
1194             int n0 = (++it)->u.operand;
1195             int r1 = (++it)->u.operand;
1196             printLocationAndOp(out, exec, location, it, "put_setter_by_id");
1197             out.printf("%s, %s, %d, %s", registerName(r0).data(), idName(id0, identifier(id0)).data(), n0, registerName(r1).data());
1198             break;
1199         }
1200         case op_put_getter_setter_by_id: {
1201             int r0 = (++it)->u.operand;
1202             int id0 = (++it)->u.operand;
1203             int n0 = (++it)->u.operand;
1204             int r1 = (++it)->u.operand;
1205             int r2 = (++it)->u.operand;
1206             printLocationAndOp(out, exec, location, it, "put_getter_setter_by_id");
1207             out.printf("%s, %s, %d, %s, %s", registerName(r0).data(), idName(id0, identifier(id0)).data(), n0, registerName(r1).data(), registerName(r2).data());
1208             break;
1209         }
1210         case op_put_getter_by_val: {
1211             int r0 = (++it)->u.operand;
1212             int r1 = (++it)->u.operand;
1213             int n0 = (++it)->u.operand;
1214             int r2 = (++it)->u.operand;
1215             printLocationAndOp(out, exec, location, it, "put_getter_by_val");
1216             out.printf("%s, %s, %d, %s", registerName(r0).data(), registerName(r1).data(), n0, registerName(r2).data());
1217             break;
1218         }
1219         case op_put_setter_by_val: {
1220             int r0 = (++it)->u.operand;
1221             int r1 = (++it)->u.operand;
1222             int n0 = (++it)->u.operand;
1223             int r2 = (++it)->u.operand;
1224             printLocationAndOp(out, exec, location, it, "put_setter_by_val");
1225             out.printf("%s, %s, %d, %s", registerName(r0).data(), registerName(r1).data(), n0, registerName(r2).data());
1226             break;
1227         }
1228         case op_del_by_id: {
1229             int r0 = (++it)->u.operand;
1230             int r1 = (++it)->u.operand;
1231             int id0 = (++it)->u.operand;
1232             printLocationAndOp(out, exec, location, it, "del_by_id");
1233             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), idName(id0, identifier(id0)).data());
1234             break;
1235         }
1236         case op_get_by_val: {
1237             int r0 = (++it)->u.operand;
1238             int r1 = (++it)->u.operand;
1239             int r2 = (++it)->u.operand;
1240             printLocationAndOp(out, exec, location, it, "get_by_val");
1241             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
1242             dumpArrayProfiling(out, it, hasPrintedProfiling);
1243             dumpValueProfiling(out, it, hasPrintedProfiling);
1244             break;
1245         }
1246         case op_put_by_val: {
1247             int r0 = (++it)->u.operand;
1248             int r1 = (++it)->u.operand;
1249             int r2 = (++it)->u.operand;
1250             printLocationAndOp(out, exec, location, it, "put_by_val");
1251             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
1252             dumpArrayProfiling(out, it, hasPrintedProfiling);
1253             break;
1254         }
1255         case op_put_by_val_direct: {
1256             int r0 = (++it)->u.operand;
1257             int r1 = (++it)->u.operand;
1258             int r2 = (++it)->u.operand;
1259             printLocationAndOp(out, exec, location, it, "put_by_val_direct");
1260             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
1261             dumpArrayProfiling(out, it, hasPrintedProfiling);
1262             break;
1263         }
1264         case op_del_by_val: {
1265             int r0 = (++it)->u.operand;
1266             int r1 = (++it)->u.operand;
1267             int r2 = (++it)->u.operand;
1268             printLocationAndOp(out, exec, location, it, "del_by_val");
1269             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
1270             break;
1271         }
1272         case op_put_by_index: {
1273             int r0 = (++it)->u.operand;
1274             unsigned n0 = (++it)->u.operand;
1275             int r1 = (++it)->u.operand;
1276             printLocationAndOp(out, exec, location, it, "put_by_index");
1277             out.printf("%s, %u, %s", registerName(r0).data(), n0, registerName(r1).data());
1278             break;
1279         }
1280         case op_jmp: {
1281             int offset = (++it)->u.operand;
1282             printLocationAndOp(out, exec, location, it, "jmp");
1283             out.printf("%d(->%d)", offset, location + offset);
1284             break;
1285         }
1286         case op_jtrue: {
1287             printConditionalJump(out, exec, begin, it, location, "jtrue");
1288             break;
1289         }
1290         case op_jfalse: {
1291             printConditionalJump(out, exec, begin, it, location, "jfalse");
1292             break;
1293         }
1294         case op_jeq_null: {
1295             printConditionalJump(out, exec, begin, it, location, "jeq_null");
1296             break;
1297         }
1298         case op_jneq_null: {
1299             printConditionalJump(out, exec, begin, it, location, "jneq_null");
1300             break;
1301         }
1302         case op_jneq_ptr: {
1303             int r0 = (++it)->u.operand;
1304             Special::Pointer pointer = (++it)->u.specialPointer;
1305             int offset = (++it)->u.operand;
1306             printLocationAndOp(out, exec, location, it, "jneq_ptr");
1307             out.printf("%s, %d (%p), %d(->%d)", registerName(r0).data(), pointer, m_globalObject->actualPointerFor(pointer), offset, location + offset);
1308             break;
1309         }
1310         case op_jless: {
1311             int r0 = (++it)->u.operand;
1312             int r1 = (++it)->u.operand;
1313             int offset = (++it)->u.operand;
1314             printLocationAndOp(out, exec, location, it, "jless");
1315             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1316             break;
1317         }
1318         case op_jlesseq: {
1319             int r0 = (++it)->u.operand;
1320             int r1 = (++it)->u.operand;
1321             int offset = (++it)->u.operand;
1322             printLocationAndOp(out, exec, location, it, "jlesseq");
1323             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1324             break;
1325         }
1326         case op_jgreater: {
1327             int r0 = (++it)->u.operand;
1328             int r1 = (++it)->u.operand;
1329             int offset = (++it)->u.operand;
1330             printLocationAndOp(out, exec, location, it, "jgreater");
1331             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1332             break;
1333         }
1334         case op_jgreatereq: {
1335             int r0 = (++it)->u.operand;
1336             int r1 = (++it)->u.operand;
1337             int offset = (++it)->u.operand;
1338             printLocationAndOp(out, exec, location, it, "jgreatereq");
1339             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1340             break;
1341         }
1342         case op_jnless: {
1343             int r0 = (++it)->u.operand;
1344             int r1 = (++it)->u.operand;
1345             int offset = (++it)->u.operand;
1346             printLocationAndOp(out, exec, location, it, "jnless");
1347             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1348             break;
1349         }
1350         case op_jnlesseq: {
1351             int r0 = (++it)->u.operand;
1352             int r1 = (++it)->u.operand;
1353             int offset = (++it)->u.operand;
1354             printLocationAndOp(out, exec, location, it, "jnlesseq");
1355             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1356             break;
1357         }
1358         case op_jngreater: {
1359             int r0 = (++it)->u.operand;
1360             int r1 = (++it)->u.operand;
1361             int offset = (++it)->u.operand;
1362             printLocationAndOp(out, exec, location, it, "jngreater");
1363             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1364             break;
1365         }
1366         case op_jngreatereq: {
1367             int r0 = (++it)->u.operand;
1368             int r1 = (++it)->u.operand;
1369             int offset = (++it)->u.operand;
1370             printLocationAndOp(out, exec, location, it, "jngreatereq");
1371             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1372             break;
1373         }
1374         case op_loop_hint: {
1375             printLocationAndOp(out, exec, location, it, "loop_hint");
1376             break;
1377         }
1378         case op_watchdog: {
1379             printLocationAndOp(out, exec, location, it, "watchdog");
1380             break;
1381         }
1382         case op_log_shadow_chicken_prologue: {
1383             int r0 = (++it)->u.operand;
1384             printLocationAndOp(out, exec, location, it, "log_shadow_chicken_prologue");
1385             out.printf("%s", registerName(r0).data());
1386             break;
1387         }
1388         case op_log_shadow_chicken_tail: {
1389             int r0 = (++it)->u.operand;
1390             int r1 = (++it)->u.operand;
1391             printLocationAndOp(out, exec, location, it, "log_shadow_chicken_tail");
1392             out.printf("%s, %s", registerName(r0).data(), registerName(r1).data());
1393             break;
1394         }
1395         case op_switch_imm: {
1396             int tableIndex = (++it)->u.operand;
1397             int defaultTarget = (++it)->u.operand;
1398             int scrutineeRegister = (++it)->u.operand;
1399             printLocationAndOp(out, exec, location, it, "switch_imm");
1400             out.printf("%d, %d(->%d), %s", tableIndex, defaultTarget, location + defaultTarget, registerName(scrutineeRegister).data());
1401             break;
1402         }
1403         case op_switch_char: {
1404             int tableIndex = (++it)->u.operand;
1405             int defaultTarget = (++it)->u.operand;
1406             int scrutineeRegister = (++it)->u.operand;
1407             printLocationAndOp(out, exec, location, it, "switch_char");
1408             out.printf("%d, %d(->%d), %s", tableIndex, defaultTarget, location + defaultTarget, registerName(scrutineeRegister).data());
1409             break;
1410         }
1411         case op_switch_string: {
1412             int tableIndex = (++it)->u.operand;
1413             int defaultTarget = (++it)->u.operand;
1414             int scrutineeRegister = (++it)->u.operand;
1415             printLocationAndOp(out, exec, location, it, "switch_string");
1416             out.printf("%d, %d(->%d), %s", tableIndex, defaultTarget, location + defaultTarget, registerName(scrutineeRegister).data());
1417             break;
1418         }
1419         case op_new_func: {
1420             int r0 = (++it)->u.operand;
1421             int r1 = (++it)->u.operand;
1422             int f0 = (++it)->u.operand;
1423             printLocationAndOp(out, exec, location, it, "new_func");
1424             out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1425             break;
1426         }
1427         case op_new_generator_func: {
1428             int r0 = (++it)->u.operand;
1429             int r1 = (++it)->u.operand;
1430             int f0 = (++it)->u.operand;
1431             printLocationAndOp(out, exec, location, it, "new_generator_func");
1432             out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1433             break;
1434         }
1435         case op_new_func_exp: {
1436             int r0 = (++it)->u.operand;
1437             int r1 = (++it)->u.operand;
1438             int f0 = (++it)->u.operand;
1439             printLocationAndOp(out, exec, location, it, "new_func_exp");
1440             out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1441             break;
1442         }
1443         case op_new_generator_func_exp: {
1444             int r0 = (++it)->u.operand;
1445             int r1 = (++it)->u.operand;
1446             int f0 = (++it)->u.operand;
1447             printLocationAndOp(out, exec, location, it, "new_generator_func_exp");
1448             out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1449             break;
1450         }
1451         case op_set_function_name: {
1452             int funcReg = (++it)->u.operand;
1453             int nameReg = (++it)->u.operand;
1454             printLocationAndOp(out, exec, location, it, "set_function_name");
1455             out.printf("%s, %s", registerName(funcReg).data(), registerName(nameReg).data());
1456             break;
1457         }
1458         case op_call: {
1459             printCallOp(out, exec, location, it, "call", DumpCaches, hasPrintedProfiling, callLinkInfos);
1460             break;
1461         }
1462         case op_tail_call: {
1463             printCallOp(out, exec, location, it, "tail_call", DumpCaches, hasPrintedProfiling, callLinkInfos);
1464             break;
1465         }
1466         case op_call_eval: {
1467             printCallOp(out, exec, location, it, "call_eval", DontDumpCaches, hasPrintedProfiling, callLinkInfos);
1468             break;
1469         }
1470             
1471         case op_construct_varargs:
1472         case op_call_varargs:
1473         case op_tail_call_varargs:
1474         case op_tail_call_forward_arguments: {
1475             int result = (++it)->u.operand;
1476             int callee = (++it)->u.operand;
1477             int thisValue = (++it)->u.operand;
1478             int arguments = (++it)->u.operand;
1479             int firstFreeRegister = (++it)->u.operand;
1480             int varArgOffset = (++it)->u.operand;
1481             ++it;
1482             const char* opName;
1483             if (opcode == op_call_varargs)
1484                 opName = "call_varargs";
1485             else if (opcode == op_construct_varargs)
1486                 opName = "construct_varargs";
1487             else if (opcode == op_tail_call_varargs)
1488                 opName = "tail_call_varargs";
1489             else if (opcode == op_tail_call_forward_arguments)
1490                 opName = "tail_call_forward_arguments";
1491             else
1492                 RELEASE_ASSERT_NOT_REACHED();
1493
1494             printLocationAndOp(out, exec, location, it, opName);
1495             out.printf("%s, %s, %s, %s, %d, %d", registerName(result).data(), registerName(callee).data(), registerName(thisValue).data(), registerName(arguments).data(), firstFreeRegister, varArgOffset);
1496             dumpValueProfiling(out, it, hasPrintedProfiling);
1497             break;
1498         }
1499
1500         case op_ret: {
1501             int r0 = (++it)->u.operand;
1502             printLocationOpAndRegisterOperand(out, exec, location, it, "ret", r0);
1503             break;
1504         }
1505         case op_construct: {
1506             printCallOp(out, exec, location, it, "construct", DumpCaches, hasPrintedProfiling, callLinkInfos);
1507             break;
1508         }
1509         case op_strcat: {
1510             int r0 = (++it)->u.operand;
1511             int r1 = (++it)->u.operand;
1512             int count = (++it)->u.operand;
1513             printLocationAndOp(out, exec, location, it, "strcat");
1514             out.printf("%s, %s, %d", registerName(r0).data(), registerName(r1).data(), count);
1515             break;
1516         }
1517         case op_to_primitive: {
1518             int r0 = (++it)->u.operand;
1519             int r1 = (++it)->u.operand;
1520             printLocationAndOp(out, exec, location, it, "to_primitive");
1521             out.printf("%s, %s", registerName(r0).data(), registerName(r1).data());
1522             break;
1523         }
1524         case op_get_enumerable_length: {
1525             int dst = it[1].u.operand;
1526             int base = it[2].u.operand;
1527             printLocationAndOp(out, exec, location, it, "op_get_enumerable_length");
1528             out.printf("%s, %s", registerName(dst).data(), registerName(base).data());
1529             it += OPCODE_LENGTH(op_get_enumerable_length) - 1;
1530             break;
1531         }
1532         case op_has_indexed_property: {
1533             int dst = it[1].u.operand;
1534             int base = it[2].u.operand;
1535             int propertyName = it[3].u.operand;
1536             ArrayProfile* arrayProfile = it[4].u.arrayProfile;
1537             printLocationAndOp(out, exec, location, it, "op_has_indexed_property");
1538             out.printf("%s, %s, %s, %p", registerName(dst).data(), registerName(base).data(), registerName(propertyName).data(), arrayProfile);
1539             it += OPCODE_LENGTH(op_has_indexed_property) - 1;
1540             break;
1541         }
1542         case op_has_structure_property: {
1543             int dst = it[1].u.operand;
1544             int base = it[2].u.operand;
1545             int propertyName = it[3].u.operand;
1546             int enumerator = it[4].u.operand;
1547             printLocationAndOp(out, exec, location, it, "op_has_structure_property");
1548             out.printf("%s, %s, %s, %s", registerName(dst).data(), registerName(base).data(), registerName(propertyName).data(), registerName(enumerator).data());
1549             it += OPCODE_LENGTH(op_has_structure_property) - 1;
1550             break;
1551         }
1552         case op_has_generic_property: {
1553             int dst = it[1].u.operand;
1554             int base = it[2].u.operand;
1555             int propertyName = it[3].u.operand;
1556             printLocationAndOp(out, exec, location, it, "op_has_generic_property");
1557             out.printf("%s, %s, %s", registerName(dst).data(), registerName(base).data(), registerName(propertyName).data());
1558             it += OPCODE_LENGTH(op_has_generic_property) - 1;
1559             break;
1560         }
1561         case op_get_direct_pname: {
1562             int dst = it[1].u.operand;
1563             int base = it[2].u.operand;
1564             int propertyName = it[3].u.operand;
1565             int index = it[4].u.operand;
1566             int enumerator = it[5].u.operand;
1567             ValueProfile* profile = it[6].u.profile;
1568             printLocationAndOp(out, exec, location, it, "op_get_direct_pname");
1569             out.printf("%s, %s, %s, %s, %s, %p", registerName(dst).data(), registerName(base).data(), registerName(propertyName).data(), registerName(index).data(), registerName(enumerator).data(), profile);
1570             it += OPCODE_LENGTH(op_get_direct_pname) - 1;
1571             break;
1572
1573         }
1574         case op_get_property_enumerator: {
1575             int dst = it[1].u.operand;
1576             int base = it[2].u.operand;
1577             printLocationAndOp(out, exec, location, it, "op_get_property_enumerator");
1578             out.printf("%s, %s", registerName(dst).data(), registerName(base).data());
1579             it += OPCODE_LENGTH(op_get_property_enumerator) - 1;
1580             break;
1581         }
1582         case op_enumerator_structure_pname: {
1583             int dst = it[1].u.operand;
1584             int enumerator = it[2].u.operand;
1585             int index = it[3].u.operand;
1586             printLocationAndOp(out, exec, location, it, "op_enumerator_structure_pname");
1587             out.printf("%s, %s, %s", registerName(dst).data(), registerName(enumerator).data(), registerName(index).data());
1588             it += OPCODE_LENGTH(op_enumerator_structure_pname) - 1;
1589             break;
1590         }
1591         case op_enumerator_generic_pname: {
1592             int dst = it[1].u.operand;
1593             int enumerator = it[2].u.operand;
1594             int index = it[3].u.operand;
1595             printLocationAndOp(out, exec, location, it, "op_enumerator_generic_pname");
1596             out.printf("%s, %s, %s", registerName(dst).data(), registerName(enumerator).data(), registerName(index).data());
1597             it += OPCODE_LENGTH(op_enumerator_generic_pname) - 1;
1598             break;
1599         }
1600         case op_to_index_string: {
1601             int dst = it[1].u.operand;
1602             int index = it[2].u.operand;
1603             printLocationAndOp(out, exec, location, it, "op_to_index_string");
1604             out.printf("%s, %s", registerName(dst).data(), registerName(index).data());
1605             it += OPCODE_LENGTH(op_to_index_string) - 1;
1606             break;
1607         }
1608         case op_push_with_scope: {
1609             int dst = (++it)->u.operand;
1610             int newScope = (++it)->u.operand;
1611             int currentScope = (++it)->u.operand;
1612             printLocationAndOp(out, exec, location, it, "push_with_scope");
1613             out.printf("%s, %s, %s", registerName(dst).data(), registerName(newScope).data(), registerName(currentScope).data());
1614             break;
1615         }
1616         case op_get_parent_scope: {
1617             int dst = (++it)->u.operand;
1618             int parentScope = (++it)->u.operand;
1619             printLocationAndOp(out, exec, location, it, "get_parent_scope");
1620             out.printf("%s, %s", registerName(dst).data(), registerName(parentScope).data());
1621             break;
1622         }
1623         case op_create_lexical_environment: {
1624             int dst = (++it)->u.operand;
1625             int scope = (++it)->u.operand;
1626             int symbolTable = (++it)->u.operand;
1627             int initialValue = (++it)->u.operand;
1628             printLocationAndOp(out, exec, location, it, "create_lexical_environment");
1629             out.printf("%s, %s, %s, %s", 
1630                 registerName(dst).data(), registerName(scope).data(), registerName(symbolTable).data(), registerName(initialValue).data());
1631             break;
1632         }
1633         case op_catch: {
1634             int r0 = (++it)->u.operand;
1635             int r1 = (++it)->u.operand;
1636             printLocationAndOp(out, exec, location, it, "catch");
1637             out.printf("%s, %s", registerName(r0).data(), registerName(r1).data());
1638             break;
1639         }
1640         case op_throw: {
1641             int r0 = (++it)->u.operand;
1642             printLocationOpAndRegisterOperand(out, exec, location, it, "throw", r0);
1643             break;
1644         }
1645         case op_throw_static_error: {
1646             int k0 = (++it)->u.operand;
1647             int k1 = (++it)->u.operand;
1648             printLocationAndOp(out, exec, location, it, "throw_static_error");
1649             out.printf("%s, %s", constantName(k0).data(), k1 ? "true" : "false");
1650             break;
1651         }
1652         case op_debug: {
1653             int debugHookID = (++it)->u.operand;
1654             int hasBreakpointFlag = (++it)->u.operand;
1655             printLocationAndOp(out, exec, location, it, "debug");
1656             out.printf("%s, %d", debugHookName(debugHookID), hasBreakpointFlag);
1657             break;
1658         }
1659         case op_save: {
1660             int generator = (++it)->u.operand;
1661             unsigned liveCalleeLocalsIndex = (++it)->u.unsignedValue;
1662             int offset = (++it)->u.operand;
1663             const FastBitVector& liveness = m_rareData->m_liveCalleeLocalsAtYield[liveCalleeLocalsIndex];
1664             printLocationAndOp(out, exec, location, it, "save");
1665             out.printf("%s, ", registerName(generator).data());
1666             liveness.dump(out);
1667             out.printf("(@live%1u), %d(->%d)", liveCalleeLocalsIndex, offset, location + offset);
1668             break;
1669         }
1670         case op_resume: {
1671             int generator = (++it)->u.operand;
1672             unsigned liveCalleeLocalsIndex = (++it)->u.unsignedValue;
1673             const FastBitVector& liveness = m_rareData->m_liveCalleeLocalsAtYield[liveCalleeLocalsIndex];
1674             printLocationAndOp(out, exec, location, it, "resume");
1675             out.printf("%s, ", registerName(generator).data());
1676             liveness.dump(out);
1677             out.printf("(@live%1u)", liveCalleeLocalsIndex);
1678             break;
1679         }
1680         case op_assert: {
1681             int condition = (++it)->u.operand;
1682             int line = (++it)->u.operand;
1683             printLocationAndOp(out, exec, location, it, "assert");
1684             out.printf("%s, %d", registerName(condition).data(), line);
1685             break;
1686         }
1687         case op_end: {
1688             int r0 = (++it)->u.operand;
1689             printLocationOpAndRegisterOperand(out, exec, location, it, "end", r0);
1690             break;
1691         }
1692         case op_resolve_scope: {
1693             int r0 = (++it)->u.operand;
1694             int scope = (++it)->u.operand;
1695             int id0 = (++it)->u.operand;
1696             ResolveType resolveType = static_cast<ResolveType>((++it)->u.operand);
1697             int depth = (++it)->u.operand;
1698             void* pointer = (++it)->u.pointer;
1699             printLocationAndOp(out, exec, location, it, "resolve_scope");
1700             out.printf("%s, %s, %s, <%s>, %d, %p", registerName(r0).data(), registerName(scope).data(), idName(id0, identifier(id0)).data(), resolveTypeName(resolveType), depth, pointer);
1701             break;
1702         }
1703         case op_get_from_scope: {
1704             int r0 = (++it)->u.operand;
1705             int r1 = (++it)->u.operand;
1706             int id0 = (++it)->u.operand;
1707             GetPutInfo getPutInfo = GetPutInfo((++it)->u.operand);
1708             ++it; // Structure
1709             int operand = (++it)->u.operand; // Operand
1710             printLocationAndOp(out, exec, location, it, "get_from_scope");
1711             out.print(registerName(r0), ", ", registerName(r1));
1712             if (static_cast<unsigned>(id0) == UINT_MAX)
1713                 out.print(", anonymous");
1714             else
1715                 out.print(", ", idName(id0, identifier(id0)));
1716             out.print(", ", getPutInfo.operand(), "<", resolveModeName(getPutInfo.resolveMode()), "|", resolveTypeName(getPutInfo.resolveType()), "|", initializationModeName(getPutInfo.initializationMode()), ">, ", operand);
1717             dumpValueProfiling(out, it, hasPrintedProfiling);
1718             break;
1719         }
1720         case op_put_to_scope: {
1721             int r0 = (++it)->u.operand;
1722             int id0 = (++it)->u.operand;
1723             int r1 = (++it)->u.operand;
1724             GetPutInfo getPutInfo = GetPutInfo((++it)->u.operand);
1725             ++it; // Structure
1726             int operand = (++it)->u.operand; // Operand
1727             printLocationAndOp(out, exec, location, it, "put_to_scope");
1728             out.print(registerName(r0));
1729             if (static_cast<unsigned>(id0) == UINT_MAX)
1730                 out.print(", anonymous");
1731             else
1732                 out.print(", ", idName(id0, identifier(id0)));
1733             out.print(", ", registerName(r1), ", ", getPutInfo.operand(), "<", resolveModeName(getPutInfo.resolveMode()), "|", resolveTypeName(getPutInfo.resolveType()), "|", initializationModeName(getPutInfo.initializationMode()), ">, <structure>, ", operand);
1734             break;
1735         }
1736         case op_get_from_arguments: {
1737             int r0 = (++it)->u.operand;
1738             int r1 = (++it)->u.operand;
1739             int offset = (++it)->u.operand;
1740             printLocationAndOp(out, exec, location, it, "get_from_arguments");
1741             out.printf("%s, %s, %d", registerName(r0).data(), registerName(r1).data(), offset);
1742             dumpValueProfiling(out, it, hasPrintedProfiling);
1743             break;
1744         }
1745         case op_put_to_arguments: {
1746             int r0 = (++it)->u.operand;
1747             int offset = (++it)->u.operand;
1748             int r1 = (++it)->u.operand;
1749             printLocationAndOp(out, exec, location, it, "put_to_arguments");
1750             out.printf("%s, %d, %s", registerName(r0).data(), offset, registerName(r1).data());
1751             break;
1752         }
1753         default:
1754             RELEASE_ASSERT_NOT_REACHED();
1755     }
1756
1757     dumpRareCaseProfile(out, "rare case: ", rareCaseProfileForBytecodeOffset(location), hasPrintedProfiling);
1758     dumpResultProfile(out, resultProfileForBytecodeOffset(location), hasPrintedProfiling);
1759     
1760 #if ENABLE(DFG_JIT)
1761     Vector<DFG::FrequentExitSite> exitSites = exitProfile().exitSitesFor(location);
1762     if (!exitSites.isEmpty()) {
1763         out.print(" !! frequent exits: ");
1764         CommaPrinter comma;
1765         for (unsigned i = 0; i < exitSites.size(); ++i)
1766             out.print(comma, exitSites[i].kind(), " ", exitSites[i].jitType());
1767     }
1768 #else // ENABLE(DFG_JIT)
1769     UNUSED_PARAM(location);
1770 #endif // ENABLE(DFG_JIT)
1771     out.print("\n");
1772 }
1773
1774 void CodeBlock::dumpBytecode(
1775     PrintStream& out, unsigned bytecodeOffset,
1776     const StubInfoMap& stubInfos, const CallLinkInfoMap& callLinkInfos)
1777 {
1778     ExecState* exec = m_globalObject->globalExec();
1779     const Instruction* it = instructions().begin() + bytecodeOffset;
1780     dumpBytecode(out, exec, instructions().begin(), it, stubInfos, callLinkInfos);
1781 }
1782
1783 #define FOR_EACH_MEMBER_VECTOR(macro) \
1784     macro(instructions) \
1785     macro(callLinkInfos) \
1786     macro(linkedCallerList) \
1787     macro(identifiers) \
1788     macro(functionExpressions) \
1789     macro(constantRegisters)
1790
1791 #define FOR_EACH_MEMBER_VECTOR_RARE_DATA(macro) \
1792     macro(regexps) \
1793     macro(functions) \
1794     macro(exceptionHandlers) \
1795     macro(switchJumpTables) \
1796     macro(stringSwitchJumpTables) \
1797     macro(evalCodeCache) \
1798     macro(expressionInfo) \
1799     macro(lineInfo) \
1800     macro(callReturnIndexVector)
1801
1802 template<typename T>
1803 static size_t sizeInBytes(const Vector<T>& vector)
1804 {
1805     return vector.capacity() * sizeof(T);
1806 }
1807
1808 namespace {
1809
1810 class PutToScopeFireDetail : public FireDetail {
1811 public:
1812     PutToScopeFireDetail(CodeBlock* codeBlock, const Identifier& ident)
1813         : m_codeBlock(codeBlock)
1814         , m_ident(ident)
1815     {
1816     }
1817     
1818     void dump(PrintStream& out) const override
1819     {
1820         out.print("Linking put_to_scope in ", FunctionExecutableDump(jsCast<FunctionExecutable*>(m_codeBlock->ownerExecutable())), " for ", m_ident);
1821     }
1822     
1823 private:
1824     CodeBlock* m_codeBlock;
1825     const Identifier& m_ident;
1826 };
1827
1828 } // anonymous namespace
1829
1830 CodeBlock::CodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, CodeBlock& other)
1831     : JSCell(*vm, structure)
1832     , m_globalObject(other.m_globalObject)
1833     , m_numCalleeLocals(other.m_numCalleeLocals)
1834     , m_numVars(other.m_numVars)
1835     , m_shouldAlwaysBeInlined(true)
1836 #if ENABLE(JIT)
1837     , m_capabilityLevelState(DFG::CapabilityLevelNotSet)
1838 #endif
1839     , m_didFailFTLCompilation(false)
1840     , m_hasBeenCompiledWithFTL(false)
1841     , m_isConstructor(other.m_isConstructor)
1842     , m_isStrictMode(other.m_isStrictMode)
1843     , m_codeType(other.m_codeType)
1844     , m_unlinkedCode(*other.m_vm, this, other.m_unlinkedCode.get())
1845     , m_hasDebuggerStatement(false)
1846     , m_steppingMode(SteppingModeDisabled)
1847     , m_numBreakpoints(0)
1848     , m_ownerExecutable(*other.m_vm, this, other.m_ownerExecutable.get())
1849     , m_vm(other.m_vm)
1850     , m_instructions(other.m_instructions)
1851     , m_thisRegister(other.m_thisRegister)
1852     , m_scopeRegister(other.m_scopeRegister)
1853     , m_hash(other.m_hash)
1854     , m_source(other.m_source)
1855     , m_sourceOffset(other.m_sourceOffset)
1856     , m_firstLineColumnOffset(other.m_firstLineColumnOffset)
1857     , m_constantRegisters(other.m_constantRegisters)
1858     , m_constantsSourceCodeRepresentation(other.m_constantsSourceCodeRepresentation)
1859     , m_functionDecls(other.m_functionDecls)
1860     , m_functionExprs(other.m_functionExprs)
1861     , m_osrExitCounter(0)
1862     , m_optimizationDelayCounter(0)
1863     , m_reoptimizationRetryCounter(0)
1864     , m_creationTime(std::chrono::steady_clock::now())
1865 {
1866     m_visitWeaklyHasBeenCalled.store(false, std::memory_order_relaxed);
1867
1868     ASSERT(heap()->isDeferred());
1869     ASSERT(m_scopeRegister.isLocal());
1870
1871     setNumParameters(other.numParameters());
1872 }
1873
1874 void CodeBlock::finishCreation(VM& vm, CopyParsedBlockTag, CodeBlock& other)
1875 {
1876     Base::finishCreation(vm);
1877
1878     optimizeAfterWarmUp();
1879     jitAfterWarmUp();
1880
1881     if (other.m_rareData) {
1882         createRareDataIfNecessary();
1883         
1884         m_rareData->m_exceptionHandlers = other.m_rareData->m_exceptionHandlers;
1885         m_rareData->m_constantBuffers = other.m_rareData->m_constantBuffers;
1886         m_rareData->m_switchJumpTables = other.m_rareData->m_switchJumpTables;
1887         m_rareData->m_stringSwitchJumpTables = other.m_rareData->m_stringSwitchJumpTables;
1888         m_rareData->m_liveCalleeLocalsAtYield = other.m_rareData->m_liveCalleeLocalsAtYield;
1889     }
1890     
1891     heap()->m_codeBlocks.add(this);
1892 }
1893
1894 CodeBlock::CodeBlock(VM* vm, Structure* structure, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock,
1895     JSScope* scope, PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset, unsigned firstLineColumnOffset)
1896     : JSCell(*vm, structure)
1897     , m_globalObject(scope->globalObject()->vm(), this, scope->globalObject())
1898     , m_numCalleeLocals(unlinkedCodeBlock->m_numCalleeLocals)
1899     , m_numVars(unlinkedCodeBlock->m_numVars)
1900     , m_shouldAlwaysBeInlined(true)
1901 #if ENABLE(JIT)
1902     , m_capabilityLevelState(DFG::CapabilityLevelNotSet)
1903 #endif
1904     , m_didFailFTLCompilation(false)
1905     , m_hasBeenCompiledWithFTL(false)
1906     , m_isConstructor(unlinkedCodeBlock->isConstructor())
1907     , m_isStrictMode(unlinkedCodeBlock->isStrictMode())
1908     , m_codeType(unlinkedCodeBlock->codeType())
1909     , m_unlinkedCode(m_globalObject->vm(), this, unlinkedCodeBlock)
1910     , m_hasDebuggerStatement(false)
1911     , m_steppingMode(SteppingModeDisabled)
1912     , m_numBreakpoints(0)
1913     , m_ownerExecutable(m_globalObject->vm(), this, ownerExecutable)
1914     , m_vm(unlinkedCodeBlock->vm())
1915     , m_thisRegister(unlinkedCodeBlock->thisRegister())
1916     , m_scopeRegister(unlinkedCodeBlock->scopeRegister())
1917     , m_source(sourceProvider)
1918     , m_sourceOffset(sourceOffset)
1919     , m_firstLineColumnOffset(firstLineColumnOffset)
1920     , m_osrExitCounter(0)
1921     , m_optimizationDelayCounter(0)
1922     , m_reoptimizationRetryCounter(0)
1923     , m_creationTime(std::chrono::steady_clock::now())
1924 {
1925     m_visitWeaklyHasBeenCalled.store(false, std::memory_order_relaxed);
1926
1927     ASSERT(heap()->isDeferred());
1928     ASSERT(m_scopeRegister.isLocal());
1929
1930     ASSERT(m_source);
1931     setNumParameters(unlinkedCodeBlock->numParameters());
1932 }
1933
1934 void CodeBlock::finishCreation(VM& vm, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock,
1935     JSScope* scope)
1936 {
1937     Base::finishCreation(vm);
1938
1939     if (vm.typeProfiler() || vm.controlFlowProfiler())
1940         vm.functionHasExecutedCache()->removeUnexecutedRange(ownerExecutable->sourceID(), ownerExecutable->typeProfilingStartOffset(), ownerExecutable->typeProfilingEndOffset());
1941
1942     setConstantRegisters(unlinkedCodeBlock->constantRegisters(), unlinkedCodeBlock->constantsSourceCodeRepresentation());
1943     if (unlinkedCodeBlock->usesGlobalObject())
1944         m_constantRegisters[unlinkedCodeBlock->globalObjectRegister().toConstantIndex()].set(*m_vm, this, m_globalObject.get());
1945
1946     for (unsigned i = 0; i < LinkTimeConstantCount; i++) {
1947         LinkTimeConstant type = static_cast<LinkTimeConstant>(i);
1948         if (unsigned registerIndex = unlinkedCodeBlock->registerIndexForLinkTimeConstant(type))
1949             m_constantRegisters[registerIndex].set(*m_vm, this, m_globalObject->jsCellForLinkTimeConstant(type));
1950     }
1951
1952     // We already have the cloned symbol table for the module environment since we need to instantiate
1953     // the module environments before linking the code block. We replace the stored symbol table with the already cloned one.
1954     if (UnlinkedModuleProgramCodeBlock* unlinkedModuleProgramCodeBlock = jsDynamicCast<UnlinkedModuleProgramCodeBlock*>(unlinkedCodeBlock)) {
1955         SymbolTable* clonedSymbolTable = jsCast<ModuleProgramExecutable*>(ownerExecutable)->moduleEnvironmentSymbolTable();
1956         if (m_vm->typeProfiler()) {
1957             ConcurrentJITLocker locker(clonedSymbolTable->m_lock);
1958             clonedSymbolTable->prepareForTypeProfiling(locker);
1959         }
1960         replaceConstant(unlinkedModuleProgramCodeBlock->moduleEnvironmentSymbolTableConstantRegisterOffset(), clonedSymbolTable);
1961     }
1962
1963     bool shouldUpdateFunctionHasExecutedCache = vm.typeProfiler() || vm.controlFlowProfiler();
1964     m_functionDecls = RefCountedArray<WriteBarrier<FunctionExecutable>>(unlinkedCodeBlock->numberOfFunctionDecls());
1965     for (size_t count = unlinkedCodeBlock->numberOfFunctionDecls(), i = 0; i < count; ++i) {
1966         UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionDecl(i);
1967         if (shouldUpdateFunctionHasExecutedCache)
1968             vm.functionHasExecutedCache()->insertUnexecutedRange(ownerExecutable->sourceID(), unlinkedExecutable->typeProfilingStartOffset(), unlinkedExecutable->typeProfilingEndOffset());
1969         m_functionDecls[i].set(*m_vm, this, unlinkedExecutable->link(*m_vm, ownerExecutable->source()));
1970     }
1971
1972     m_functionExprs = RefCountedArray<WriteBarrier<FunctionExecutable>>(unlinkedCodeBlock->numberOfFunctionExprs());
1973     for (size_t count = unlinkedCodeBlock->numberOfFunctionExprs(), i = 0; i < count; ++i) {
1974         UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionExpr(i);
1975         if (shouldUpdateFunctionHasExecutedCache)
1976             vm.functionHasExecutedCache()->insertUnexecutedRange(ownerExecutable->sourceID(), unlinkedExecutable->typeProfilingStartOffset(), unlinkedExecutable->typeProfilingEndOffset());
1977         m_functionExprs[i].set(*m_vm, this, unlinkedExecutable->link(*m_vm, ownerExecutable->source()));
1978     }
1979
1980     if (unlinkedCodeBlock->hasRareData()) {
1981         createRareDataIfNecessary();
1982         if (size_t count = unlinkedCodeBlock->constantBufferCount()) {
1983             m_rareData->m_constantBuffers.grow(count);
1984             for (size_t i = 0; i < count; i++) {
1985                 const UnlinkedCodeBlock::ConstantBuffer& buffer = unlinkedCodeBlock->constantBuffer(i);
1986                 m_rareData->m_constantBuffers[i] = buffer;
1987             }
1988         }
1989         if (size_t count = unlinkedCodeBlock->numberOfExceptionHandlers()) {
1990             m_rareData->m_exceptionHandlers.resizeToFit(count);
1991             for (size_t i = 0; i < count; i++) {
1992                 const UnlinkedHandlerInfo& unlinkedHandler = unlinkedCodeBlock->exceptionHandler(i);
1993                 HandlerInfo& handler = m_rareData->m_exceptionHandlers[i];
1994 #if ENABLE(JIT)
1995                 handler.initialize(unlinkedHandler, CodeLocationLabel(MacroAssemblerCodePtr::createFromExecutableAddress(LLInt::getCodePtr(op_catch))));
1996 #else
1997                 handler.initialize(unlinkedHandler);
1998 #endif
1999             }
2000         }
2001
2002         if (size_t count = unlinkedCodeBlock->numberOfStringSwitchJumpTables()) {
2003             m_rareData->m_stringSwitchJumpTables.grow(count);
2004             for (size_t i = 0; i < count; i++) {
2005                 UnlinkedStringJumpTable::StringOffsetTable::iterator ptr = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.begin();
2006                 UnlinkedStringJumpTable::StringOffsetTable::iterator end = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.end();
2007                 for (; ptr != end; ++ptr) {
2008                     OffsetLocation offset;
2009                     offset.branchOffset = ptr->value;
2010                     m_rareData->m_stringSwitchJumpTables[i].offsetTable.add(ptr->key, offset);
2011                 }
2012             }
2013         }
2014
2015         if (size_t count = unlinkedCodeBlock->numberOfSwitchJumpTables()) {
2016             m_rareData->m_switchJumpTables.grow(count);
2017             for (size_t i = 0; i < count; i++) {
2018                 UnlinkedSimpleJumpTable& sourceTable = unlinkedCodeBlock->switchJumpTable(i);
2019                 SimpleJumpTable& destTable = m_rareData->m_switchJumpTables[i];
2020                 destTable.branchOffsets = sourceTable.branchOffsets;
2021                 destTable.min = sourceTable.min;
2022             }
2023         }
2024     }
2025
2026     // Allocate metadata buffers for the bytecode
2027     if (size_t size = unlinkedCodeBlock->numberOfLLintCallLinkInfos())
2028         m_llintCallLinkInfos = RefCountedArray<LLIntCallLinkInfo>(size);
2029     if (size_t size = unlinkedCodeBlock->numberOfArrayProfiles())
2030         m_arrayProfiles.grow(size);
2031     if (size_t size = unlinkedCodeBlock->numberOfArrayAllocationProfiles())
2032         m_arrayAllocationProfiles = RefCountedArray<ArrayAllocationProfile>(size);
2033     if (size_t size = unlinkedCodeBlock->numberOfValueProfiles())
2034         m_valueProfiles = RefCountedArray<ValueProfile>(size);
2035     if (size_t size = unlinkedCodeBlock->numberOfObjectAllocationProfiles())
2036         m_objectAllocationProfiles = RefCountedArray<ObjectAllocationProfile>(size);
2037
2038 #if ENABLE(JIT)
2039     setCalleeSaveRegisters(RegisterSet::llintBaselineCalleeSaveRegisters());
2040 #endif
2041
2042     // Copy and translate the UnlinkedInstructions
2043     unsigned instructionCount = unlinkedCodeBlock->instructions().count();
2044     UnlinkedInstructionStream::Reader instructionReader(unlinkedCodeBlock->instructions());
2045
2046     // Bookkeep the strongly referenced module environments.
2047     HashSet<JSModuleEnvironment*> stronglyReferencedModuleEnvironments;
2048
2049     // Bookkeep the merge point bytecode offsets.
2050     Vector<size_t> mergePointBytecodeOffsets;
2051
2052     RefCountedArray<Instruction> instructions(instructionCount);
2053
2054     for (unsigned i = 0; !instructionReader.atEnd(); ) {
2055         const UnlinkedInstruction* pc = instructionReader.next();
2056
2057         unsigned opLength = opcodeLength(pc[0].u.opcode);
2058
2059         instructions[i] = vm.interpreter->getOpcode(pc[0].u.opcode);
2060         for (size_t j = 1; j < opLength; ++j) {
2061             if (sizeof(int32_t) != sizeof(intptr_t))
2062                 instructions[i + j].u.pointer = 0;
2063             instructions[i + j].u.operand = pc[j].u.operand;
2064         }
2065         switch (pc[0].u.opcode) {
2066         case op_has_indexed_property: {
2067             int arrayProfileIndex = pc[opLength - 1].u.operand;
2068             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
2069
2070             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
2071             break;
2072         }
2073         case op_call_varargs:
2074         case op_tail_call_varargs:
2075         case op_tail_call_forward_arguments:
2076         case op_construct_varargs:
2077         case op_get_by_val: {
2078             int arrayProfileIndex = pc[opLength - 2].u.operand;
2079             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
2080
2081             instructions[i + opLength - 2] = &m_arrayProfiles[arrayProfileIndex];
2082             FALLTHROUGH;
2083         }
2084         case op_get_direct_pname:
2085         case op_get_by_id:
2086         case op_get_from_arguments: {
2087             ValueProfile* profile = &m_valueProfiles[pc[opLength - 1].u.operand];
2088             ASSERT(profile->m_bytecodeOffset == -1);
2089             profile->m_bytecodeOffset = i;
2090             instructions[i + opLength - 1] = profile;
2091             break;
2092         }
2093         case op_put_by_val: {
2094             int arrayProfileIndex = pc[opLength - 1].u.operand;
2095             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
2096             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
2097             break;
2098         }
2099         case op_put_by_val_direct: {
2100             int arrayProfileIndex = pc[opLength - 1].u.operand;
2101             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
2102             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
2103             break;
2104         }
2105
2106         case op_new_array:
2107         case op_new_array_buffer:
2108         case op_new_array_with_size: {
2109             int arrayAllocationProfileIndex = pc[opLength - 1].u.operand;
2110             instructions[i + opLength - 1] = &m_arrayAllocationProfiles[arrayAllocationProfileIndex];
2111             break;
2112         }
2113         case op_new_object: {
2114             int objectAllocationProfileIndex = pc[opLength - 1].u.operand;
2115             ObjectAllocationProfile* objectAllocationProfile = &m_objectAllocationProfiles[objectAllocationProfileIndex];
2116             int inferredInlineCapacity = pc[opLength - 2].u.operand;
2117
2118             instructions[i + opLength - 1] = objectAllocationProfile;
2119             objectAllocationProfile->initialize(vm,
2120                 this, m_globalObject->objectPrototype(), inferredInlineCapacity);
2121             break;
2122         }
2123
2124         case op_call:
2125         case op_tail_call:
2126         case op_call_eval: {
2127             ValueProfile* profile = &m_valueProfiles[pc[opLength - 1].u.operand];
2128             ASSERT(profile->m_bytecodeOffset == -1);
2129             profile->m_bytecodeOffset = i;
2130             instructions[i + opLength - 1] = profile;
2131             int arrayProfileIndex = pc[opLength - 2].u.operand;
2132             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
2133             instructions[i + opLength - 2] = &m_arrayProfiles[arrayProfileIndex];
2134             instructions[i + 5] = &m_llintCallLinkInfos[pc[5].u.operand];
2135             break;
2136         }
2137         case op_construct: {
2138             instructions[i + 5] = &m_llintCallLinkInfos[pc[5].u.operand];
2139             ValueProfile* profile = &m_valueProfiles[pc[opLength - 1].u.operand];
2140             ASSERT(profile->m_bytecodeOffset == -1);
2141             profile->m_bytecodeOffset = i;
2142             instructions[i + opLength - 1] = profile;
2143             break;
2144         }
2145         case op_get_array_length:
2146             CRASH();
2147
2148         case op_resolve_scope: {
2149             const Identifier& ident = identifier(pc[3].u.operand);
2150             ResolveType type = static_cast<ResolveType>(pc[4].u.operand);
2151             RELEASE_ASSERT(type != LocalClosureVar);
2152             int localScopeDepth = pc[5].u.operand;
2153
2154             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Get, type, InitializationMode::NotInitialization);
2155             instructions[i + 4].u.operand = op.type;
2156             instructions[i + 5].u.operand = op.depth;
2157             if (op.lexicalEnvironment) {
2158                 if (op.type == ModuleVar) {
2159                     // Keep the linked module environment strongly referenced.
2160                     if (stronglyReferencedModuleEnvironments.add(jsCast<JSModuleEnvironment*>(op.lexicalEnvironment)).isNewEntry)
2161                         addConstant(op.lexicalEnvironment);
2162                     instructions[i + 6].u.jsCell.set(vm, this, op.lexicalEnvironment);
2163                 } else
2164                     instructions[i + 6].u.symbolTable.set(vm, this, op.lexicalEnvironment->symbolTable());
2165             } else if (JSScope* constantScope = JSScope::constantScopeForCodeBlock(op.type, this))
2166                 instructions[i + 6].u.jsCell.set(vm, this, constantScope);
2167             else
2168                 instructions[i + 6].u.pointer = nullptr;
2169             break;
2170         }
2171
2172         case op_get_from_scope: {
2173             ValueProfile* profile = &m_valueProfiles[pc[opLength - 1].u.operand];
2174             ASSERT(profile->m_bytecodeOffset == -1);
2175             profile->m_bytecodeOffset = i;
2176             instructions[i + opLength - 1] = profile;
2177
2178             // get_from_scope dst, scope, id, GetPutInfo, Structure, Operand
2179
2180             int localScopeDepth = pc[5].u.operand;
2181             instructions[i + 5].u.pointer = nullptr;
2182
2183             GetPutInfo getPutInfo = GetPutInfo(pc[4].u.operand);
2184             ASSERT(!isInitialization(getPutInfo.initializationMode()));
2185             if (getPutInfo.resolveType() == LocalClosureVar) {
2186                 instructions[i + 4] = GetPutInfo(getPutInfo.resolveMode(), ClosureVar, getPutInfo.initializationMode()).operand();
2187                 break;
2188             }
2189
2190             const Identifier& ident = identifier(pc[3].u.operand);
2191             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Get, getPutInfo.resolveType(), InitializationMode::NotInitialization);
2192
2193             instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), op.type, getPutInfo.initializationMode()).operand();
2194             if (op.type == ModuleVar)
2195                 instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), ClosureVar, getPutInfo.initializationMode()).operand();
2196             if (op.type == GlobalVar || op.type == GlobalVarWithVarInjectionChecks || op.type == GlobalLexicalVar || op.type == GlobalLexicalVarWithVarInjectionChecks)
2197                 instructions[i + 5].u.watchpointSet = op.watchpointSet;
2198             else if (op.structure)
2199                 instructions[i + 5].u.structure.set(vm, this, op.structure);
2200             instructions[i + 6].u.pointer = reinterpret_cast<void*>(op.operand);
2201             break;
2202         }
2203
2204         case op_put_to_scope: {
2205             // put_to_scope scope, id, value, GetPutInfo, Structure, Operand
2206             GetPutInfo getPutInfo = GetPutInfo(pc[4].u.operand);
2207             if (getPutInfo.resolveType() == LocalClosureVar) {
2208                 // Only do watching if the property we're putting to is not anonymous.
2209                 if (static_cast<unsigned>(pc[2].u.operand) != UINT_MAX) {
2210                     int symbolTableIndex = pc[5].u.operand;
2211                     SymbolTable* symbolTable = jsCast<SymbolTable*>(getConstant(symbolTableIndex));
2212                     const Identifier& ident = identifier(pc[2].u.operand);
2213                     ConcurrentJITLocker locker(symbolTable->m_lock);
2214                     auto iter = symbolTable->find(locker, ident.impl());
2215                     ASSERT(iter != symbolTable->end(locker));
2216                     iter->value.prepareToWatch();
2217                     instructions[i + 5].u.watchpointSet = iter->value.watchpointSet();
2218                 } else
2219                     instructions[i + 5].u.watchpointSet = nullptr;
2220                 break;
2221             }
2222
2223             const Identifier& ident = identifier(pc[2].u.operand);
2224             int localScopeDepth = pc[5].u.operand;
2225             instructions[i + 5].u.pointer = nullptr;
2226             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Put, getPutInfo.resolveType(), getPutInfo.initializationMode());
2227
2228             instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), op.type, getPutInfo.initializationMode()).operand();
2229             if (op.type == GlobalVar || op.type == GlobalVarWithVarInjectionChecks || op.type == GlobalLexicalVar || op.type == GlobalLexicalVarWithVarInjectionChecks)
2230                 instructions[i + 5].u.watchpointSet = op.watchpointSet;
2231             else if (op.type == ClosureVar || op.type == ClosureVarWithVarInjectionChecks) {
2232                 if (op.watchpointSet)
2233                     op.watchpointSet->invalidate(PutToScopeFireDetail(this, ident));
2234             } else if (op.structure)
2235                 instructions[i + 5].u.structure.set(vm, this, op.structure);
2236             instructions[i + 6].u.pointer = reinterpret_cast<void*>(op.operand);
2237
2238             break;
2239         }
2240
2241         case op_profile_type: {
2242             RELEASE_ASSERT(vm.typeProfiler());
2243             // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType?
2244             size_t instructionOffset = i + opLength - 1;
2245             unsigned divotStart, divotEnd;
2246             GlobalVariableID globalVariableID = 0;
2247             RefPtr<TypeSet> globalTypeSet;
2248             bool shouldAnalyze = m_unlinkedCode->typeProfilerExpressionInfoForBytecodeOffset(instructionOffset, divotStart, divotEnd);
2249             VirtualRegister profileRegister(pc[1].u.operand);
2250             ProfileTypeBytecodeFlag flag = static_cast<ProfileTypeBytecodeFlag>(pc[3].u.operand);
2251             SymbolTable* symbolTable = nullptr;
2252
2253             switch (flag) {
2254             case ProfileTypeBytecodeClosureVar: {
2255                 const Identifier& ident = identifier(pc[4].u.operand);
2256                 int localScopeDepth = pc[2].u.operand;
2257                 ResolveType type = static_cast<ResolveType>(pc[5].u.operand);
2258                 // Even though type profiling may be profiling either a Get or a Put, we can always claim a Get because
2259                 // we're abstractly "read"ing from a JSScope.
2260                 ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Get, type, InitializationMode::NotInitialization);
2261
2262                 if (op.type == ClosureVar || op.type == ModuleVar)
2263                     symbolTable = op.lexicalEnvironment->symbolTable();
2264                 else if (op.type == GlobalVar)
2265                     symbolTable = m_globalObject.get()->symbolTable();
2266
2267                 UniquedStringImpl* impl = (op.type == ModuleVar) ? op.importedName.get() : ident.impl();
2268                 if (symbolTable) {
2269                     ConcurrentJITLocker locker(symbolTable->m_lock);
2270                     // If our parent scope was created while profiling was disabled, it will not have prepared for profiling yet.
2271                     symbolTable->prepareForTypeProfiling(locker);
2272                     globalVariableID = symbolTable->uniqueIDForVariable(locker, impl, vm);
2273                     globalTypeSet = symbolTable->globalTypeSetForVariable(locker, impl, vm);
2274                 } else
2275                     globalVariableID = TypeProfilerNoGlobalIDExists;
2276
2277                 break;
2278             }
2279             case ProfileTypeBytecodeLocallyResolved: {
2280                 int symbolTableIndex = pc[2].u.operand;
2281                 SymbolTable* symbolTable = jsCast<SymbolTable*>(getConstant(symbolTableIndex));
2282                 const Identifier& ident = identifier(pc[4].u.operand);
2283                 ConcurrentJITLocker locker(symbolTable->m_lock);
2284                 // If our parent scope was created while profiling was disabled, it will not have prepared for profiling yet.
2285                 globalVariableID = symbolTable->uniqueIDForVariable(locker, ident.impl(), vm);
2286                 globalTypeSet = symbolTable->globalTypeSetForVariable(locker, ident.impl(), vm);
2287
2288                 break;
2289             }
2290             case ProfileTypeBytecodeDoesNotHaveGlobalID: 
2291             case ProfileTypeBytecodeFunctionArgument: {
2292                 globalVariableID = TypeProfilerNoGlobalIDExists;
2293                 break;
2294             }
2295             case ProfileTypeBytecodeFunctionReturnStatement: {
2296                 RELEASE_ASSERT(ownerExecutable->isFunctionExecutable());
2297                 globalTypeSet = jsCast<FunctionExecutable*>(ownerExecutable)->returnStatementTypeSet();
2298                 globalVariableID = TypeProfilerReturnStatement;
2299                 if (!shouldAnalyze) {
2300                     // Because a return statement can be added implicitly to return undefined at the end of a function,
2301                     // and these nodes don't emit expression ranges because they aren't in the actual source text of
2302                     // the user's program, give the type profiler some range to identify these return statements.
2303                     // Currently, the text offset that is used as identification is "f" in the function keyword
2304                     // and is stored on TypeLocation's m_divotForFunctionOffsetIfReturnStatement member variable.
2305                     divotStart = divotEnd = ownerExecutable->typeProfilingStartOffset();
2306                     shouldAnalyze = true;
2307                 }
2308                 break;
2309             }
2310             }
2311
2312             std::pair<TypeLocation*, bool> locationPair = vm.typeProfiler()->typeLocationCache()->getTypeLocation(globalVariableID,
2313                 ownerExecutable->sourceID(), divotStart, divotEnd, globalTypeSet, &vm);
2314             TypeLocation* location = locationPair.first;
2315             bool isNewLocation = locationPair.second;
2316
2317             if (flag == ProfileTypeBytecodeFunctionReturnStatement)
2318                 location->m_divotForFunctionOffsetIfReturnStatement = ownerExecutable->typeProfilingStartOffset();
2319
2320             if (shouldAnalyze && isNewLocation)
2321                 vm.typeProfiler()->insertNewLocation(location);
2322
2323             instructions[i + 2].u.location = location;
2324             break;
2325         }
2326
2327         case op_debug: {
2328             if (pc[1].u.index == DidReachBreakpoint)
2329                 m_hasDebuggerStatement = true;
2330             break;
2331         }
2332
2333         case op_save: {
2334             unsigned liveCalleeLocalsIndex = pc[2].u.index;
2335             int offset = pc[3].u.operand;
2336             if (liveCalleeLocalsIndex >= mergePointBytecodeOffsets.size())
2337                 mergePointBytecodeOffsets.resize(liveCalleeLocalsIndex + 1);
2338             mergePointBytecodeOffsets[liveCalleeLocalsIndex] = i + offset;
2339             break;
2340         }
2341
2342         default:
2343             break;
2344         }
2345         i += opLength;
2346     }
2347
2348     if (vm.controlFlowProfiler())
2349         insertBasicBlockBoundariesForControlFlowProfiler(instructions);
2350
2351     m_instructions = WTFMove(instructions);
2352
2353     // Perform bytecode liveness analysis to determine which locals are live and should be resumed when executing op_resume.
2354     if (unlinkedCodeBlock->parseMode() == SourceParseMode::GeneratorBodyMode) {
2355         if (size_t count = mergePointBytecodeOffsets.size()) {
2356             createRareDataIfNecessary();
2357             BytecodeLivenessAnalysis liveness(this);
2358             m_rareData->m_liveCalleeLocalsAtYield.grow(count);
2359             size_t liveCalleeLocalsIndex = 0;
2360             for (size_t bytecodeOffset : mergePointBytecodeOffsets) {
2361                 m_rareData->m_liveCalleeLocalsAtYield[liveCalleeLocalsIndex] = liveness.getLivenessInfoAtBytecodeOffset(bytecodeOffset);
2362                 ++liveCalleeLocalsIndex;
2363             }
2364         }
2365     }
2366
2367     // Set optimization thresholds only after m_instructions is initialized, since these
2368     // rely on the instruction count (and are in theory permitted to also inspect the
2369     // instruction stream to more accurate assess the cost of tier-up).
2370     optimizeAfterWarmUp();
2371     jitAfterWarmUp();
2372
2373     // If the concurrent thread will want the code block's hash, then compute it here
2374     // synchronously.
2375     if (Options::alwaysComputeHash())
2376         hash();
2377
2378     if (Options::dumpGeneratedBytecodes())
2379         dumpBytecode();
2380     
2381     heap()->m_codeBlocks.add(this);
2382     heap()->reportExtraMemoryAllocated(m_instructions.size() * sizeof(Instruction));
2383 }
2384
2385 #if ENABLE(WEBASSEMBLY)
2386 CodeBlock::CodeBlock(VM* vm, Structure* structure, WebAssemblyExecutable* ownerExecutable, JSGlobalObject* globalObject)
2387     : JSCell(*vm, structure)
2388     , m_globalObject(globalObject->vm(), this, globalObject)
2389     , m_numCalleeLocals(0)
2390     , m_numVars(0)
2391     , m_shouldAlwaysBeInlined(false)
2392 #if ENABLE(JIT)
2393     , m_capabilityLevelState(DFG::CannotCompile)
2394 #endif
2395     , m_didFailFTLCompilation(false)
2396     , m_hasBeenCompiledWithFTL(false)
2397     , m_isConstructor(false)
2398     , m_isStrictMode(false)
2399     , m_codeType(FunctionCode)
2400     , m_hasDebuggerStatement(false)
2401     , m_steppingMode(SteppingModeDisabled)
2402     , m_numBreakpoints(0)
2403     , m_ownerExecutable(m_globalObject->vm(), this, ownerExecutable)
2404     , m_vm(vm)
2405     , m_osrExitCounter(0)
2406     , m_optimizationDelayCounter(0)
2407     , m_reoptimizationRetryCounter(0)
2408     , m_creationTime(std::chrono::steady_clock::now())
2409 {
2410     ASSERT(heap()->isDeferred());
2411 }
2412
2413 void CodeBlock::finishCreation(VM& vm, WebAssemblyExecutable*, JSGlobalObject*)
2414 {
2415     Base::finishCreation(vm);
2416
2417     heap()->m_codeBlocks.add(this);
2418 }
2419 #endif
2420
2421 CodeBlock::~CodeBlock()
2422 {
2423     if (m_vm->m_perBytecodeProfiler)
2424         m_vm->m_perBytecodeProfiler->notifyDestruction(this);
2425
2426     if (unlinkedCodeBlock()->didOptimize() == MixedTriState)
2427         unlinkedCodeBlock()->setDidOptimize(FalseTriState);
2428
2429 #if ENABLE(VERBOSE_VALUE_PROFILE)
2430     dumpValueProfiles();
2431 #endif
2432
2433     // We may be destroyed before any CodeBlocks that refer to us are destroyed.
2434     // Consider that two CodeBlocks become unreachable at the same time. There
2435     // is no guarantee about the order in which the CodeBlocks are destroyed.
2436     // So, if we don't remove incoming calls, and get destroyed before the
2437     // CodeBlock(s) that have calls into us, then the CallLinkInfo vector's
2438     // destructor will try to remove nodes from our (no longer valid) linked list.
2439     unlinkIncomingCalls();
2440     
2441     // Note that our outgoing calls will be removed from other CodeBlocks'
2442     // m_incomingCalls linked lists through the execution of the ~CallLinkInfo
2443     // destructors.
2444
2445 #if ENABLE(JIT)
2446     for (Bag<StructureStubInfo>::iterator iter = m_stubInfos.begin(); !!iter; ++iter) {
2447         StructureStubInfo* stub = *iter;
2448         stub->aboutToDie();
2449         stub->deref();
2450     }
2451 #endif // ENABLE(JIT)
2452 }
2453
2454 void CodeBlock::setConstantRegisters(const Vector<WriteBarrier<Unknown>>& constants, const Vector<SourceCodeRepresentation>& constantsSourceCodeRepresentation)
2455 {
2456     ASSERT(constants.size() == constantsSourceCodeRepresentation.size());
2457     size_t count = constants.size();
2458     m_constantRegisters.resizeToFit(count);
2459     bool hasTypeProfiler = !!m_vm->typeProfiler();
2460     for (size_t i = 0; i < count; i++) {
2461         JSValue constant = constants[i].get();
2462
2463         if (!constant.isEmpty()) {
2464             if (SymbolTable* symbolTable = jsDynamicCast<SymbolTable*>(constant)) {
2465                 if (hasTypeProfiler) {
2466                     ConcurrentJITLocker locker(symbolTable->m_lock);
2467                     symbolTable->prepareForTypeProfiling(locker);
2468                 }
2469                 constant = symbolTable->cloneScopePart(*m_vm);
2470             }
2471         }
2472
2473         m_constantRegisters[i].set(*m_vm, this, constant);
2474     }
2475
2476     m_constantsSourceCodeRepresentation = constantsSourceCodeRepresentation;
2477 }
2478
2479 void CodeBlock::setAlternative(VM& vm, CodeBlock* alternative)
2480 {
2481     m_alternative.set(vm, this, alternative);
2482 }
2483
2484 void CodeBlock::setNumParameters(int newValue)
2485 {
2486     m_numParameters = newValue;
2487
2488     m_argumentValueProfiles = RefCountedArray<ValueProfile>(newValue);
2489 }
2490
2491 void EvalCodeCache::visitAggregate(SlotVisitor& visitor)
2492 {
2493     EvalCacheMap::iterator end = m_cacheMap.end();
2494     for (EvalCacheMap::iterator ptr = m_cacheMap.begin(); ptr != end; ++ptr)
2495         visitor.append(&ptr->value);
2496 }
2497
2498 CodeBlock* CodeBlock::specialOSREntryBlockOrNull()
2499 {
2500 #if ENABLE(FTL_JIT)
2501     if (jitType() != JITCode::DFGJIT)
2502         return 0;
2503     DFG::JITCode* jitCode = m_jitCode->dfg();
2504     return jitCode->osrEntryBlock();
2505 #else // ENABLE(FTL_JIT)
2506     return 0;
2507 #endif // ENABLE(FTL_JIT)
2508 }
2509
2510 void CodeBlock::visitWeakly(SlotVisitor& visitor)
2511 {
2512     bool setByMe = m_visitWeaklyHasBeenCalled.compareExchangeStrong(false, true);
2513     if (!setByMe)
2514         return;
2515
2516     if (Heap::isMarked(this))
2517         return;
2518
2519     if (shouldVisitStrongly()) {
2520         visitor.appendUnbarrieredReadOnlyPointer(this);
2521         return;
2522     }
2523
2524     // There are two things that may use unconditional finalizers: inline cache clearing
2525     // and jettisoning. The probability of us wanting to do at least one of those things
2526     // is probably quite close to 1. So we add one no matter what and when it runs, it
2527     // figures out whether it has any work to do.
2528     visitor.addUnconditionalFinalizer(&m_unconditionalFinalizer);
2529
2530     if (!JITCode::isOptimizingJIT(jitType()))
2531         return;
2532
2533     // If we jettison ourselves we'll install our alternative, so make sure that it
2534     // survives GC even if we don't.
2535     visitor.append(&m_alternative);
2536     
2537     // There are two things that we use weak reference harvesters for: DFG fixpoint for
2538     // jettisoning, and trying to find structures that would be live based on some
2539     // inline cache. So it makes sense to register them regardless.
2540     visitor.addWeakReferenceHarvester(&m_weakReferenceHarvester);
2541
2542 #if ENABLE(DFG_JIT)
2543     // We get here if we're live in the sense that our owner executable is live,
2544     // but we're not yet live for sure in another sense: we may yet decide that this
2545     // code block should be jettisoned based on its outgoing weak references being
2546     // stale. Set a flag to indicate that we're still assuming that we're dead, and
2547     // perform one round of determining if we're live. The GC may determine, based on
2548     // either us marking additional objects, or by other objects being marked for
2549     // other reasons, that this iteration should run again; it will notify us of this
2550     // decision by calling harvestWeakReferences().
2551
2552     m_allTransitionsHaveBeenMarked = false;
2553     propagateTransitions(visitor);
2554
2555     m_jitCode->dfgCommon()->livenessHasBeenProved = false;
2556     determineLiveness(visitor);
2557 #endif // ENABLE(DFG_JIT)
2558 }
2559
2560 size_t CodeBlock::estimatedSize(JSCell* cell)
2561 {
2562     CodeBlock* thisObject = jsCast<CodeBlock*>(cell);
2563     size_t extraMemoryAllocated = thisObject->m_instructions.size() * sizeof(Instruction);
2564     if (thisObject->m_jitCode)
2565         extraMemoryAllocated += thisObject->m_jitCode->size();
2566     return Base::estimatedSize(cell) + extraMemoryAllocated;
2567 }
2568
2569 void CodeBlock::visitChildren(JSCell* cell, SlotVisitor& visitor)
2570 {
2571     CodeBlock* thisObject = jsCast<CodeBlock*>(cell);
2572     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
2573     JSCell::visitChildren(thisObject, visitor);
2574     thisObject->visitChildren(visitor);
2575 }
2576
2577 void CodeBlock::visitChildren(SlotVisitor& visitor)
2578 {
2579     // There are two things that may use unconditional finalizers: inline cache clearing
2580     // and jettisoning. The probability of us wanting to do at least one of those things
2581     // is probably quite close to 1. So we add one no matter what and when it runs, it
2582     // figures out whether it has any work to do.
2583     visitor.addUnconditionalFinalizer(&m_unconditionalFinalizer);
2584
2585     if (CodeBlock* otherBlock = specialOSREntryBlockOrNull())
2586         visitor.appendUnbarrieredReadOnlyPointer(otherBlock);
2587
2588     if (m_jitCode)
2589         visitor.reportExtraMemoryVisited(m_jitCode->size());
2590     if (m_instructions.size())
2591         visitor.reportExtraMemoryVisited(m_instructions.size() * sizeof(Instruction) / m_instructions.refCount());
2592
2593     stronglyVisitStrongReferences(visitor);
2594     stronglyVisitWeakReferences(visitor);
2595
2596     m_allTransitionsHaveBeenMarked = false;
2597     propagateTransitions(visitor);
2598 }
2599
2600 bool CodeBlock::shouldVisitStrongly()
2601 {
2602     if (Options::forceCodeBlockLiveness())
2603         return true;
2604
2605     if (shouldJettisonDueToOldAge())
2606         return false;
2607
2608     // Interpreter and Baseline JIT CodeBlocks don't need to be jettisoned when
2609     // their weak references go stale. So if a basline JIT CodeBlock gets
2610     // scanned, we can assume that this means that it's live.
2611     if (!JITCode::isOptimizingJIT(jitType()))
2612         return true;
2613
2614     return false;
2615 }
2616
2617 bool CodeBlock::shouldJettisonDueToWeakReference()
2618 {
2619     if (!JITCode::isOptimizingJIT(jitType()))
2620         return false;
2621     return !Heap::isMarked(this);
2622 }
2623
2624 bool CodeBlock::shouldJettisonDueToOldAge()
2625 {
2626     return false;
2627 }
2628
2629 #if ENABLE(DFG_JIT)
2630 static bool shouldMarkTransition(DFG::WeakReferenceTransition& transition)
2631 {
2632     if (transition.m_codeOrigin && !Heap::isMarked(transition.m_codeOrigin.get()))
2633         return false;
2634     
2635     if (!Heap::isMarked(transition.m_from.get()))
2636         return false;
2637     
2638     return true;
2639 }
2640 #endif // ENABLE(DFG_JIT)
2641
2642 void CodeBlock::propagateTransitions(SlotVisitor& visitor)
2643 {
2644     UNUSED_PARAM(visitor);
2645
2646     if (m_allTransitionsHaveBeenMarked)
2647         return;
2648
2649     bool allAreMarkedSoFar = true;
2650         
2651     Interpreter* interpreter = m_vm->interpreter;
2652     if (jitType() == JITCode::InterpreterThunk) {
2653         const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
2654         for (size_t i = 0; i < propertyAccessInstructions.size(); ++i) {
2655             Instruction* instruction = &instructions()[propertyAccessInstructions[i]];
2656             switch (interpreter->getOpcodeID(instruction[0].u.opcode)) {
2657             case op_put_by_id: {
2658                 StructureID oldStructureID = instruction[4].u.structureID;
2659                 StructureID newStructureID = instruction[6].u.structureID;
2660                 if (!oldStructureID || !newStructureID)
2661                     break;
2662                 Structure* oldStructure =
2663                     m_vm->heap.structureIDTable().get(oldStructureID);
2664                 Structure* newStructure =
2665                     m_vm->heap.structureIDTable().get(newStructureID);
2666                 if (Heap::isMarked(oldStructure))
2667                     visitor.appendUnbarrieredReadOnlyPointer(newStructure);
2668                 else
2669                     allAreMarkedSoFar = false;
2670                 break;
2671             }
2672             default:
2673                 break;
2674             }
2675         }
2676     }
2677
2678 #if ENABLE(JIT)
2679     if (JITCode::isJIT(jitType())) {
2680         for (Bag<StructureStubInfo>::iterator iter = m_stubInfos.begin(); !!iter; ++iter)
2681             allAreMarkedSoFar &= (*iter)->propagateTransitions(visitor);
2682     }
2683 #endif // ENABLE(JIT)
2684     
2685 #if ENABLE(DFG_JIT)
2686     if (JITCode::isOptimizingJIT(jitType())) {
2687         DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2688         for (auto& weakReference : dfgCommon->weakStructureReferences)
2689             allAreMarkedSoFar &= weakReference->markIfCheap(visitor);
2690         
2691         for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
2692             if (shouldMarkTransition(dfgCommon->transitions[i])) {
2693                 // If the following three things are live, then the target of the
2694                 // transition is also live:
2695                 //
2696                 // - This code block. We know it's live already because otherwise
2697                 //   we wouldn't be scanning ourselves.
2698                 //
2699                 // - The code origin of the transition. Transitions may arise from
2700                 //   code that was inlined. They are not relevant if the user's
2701                 //   object that is required for the inlinee to run is no longer
2702                 //   live.
2703                 //
2704                 // - The source of the transition. The transition checks if some
2705                 //   heap location holds the source, and if so, stores the target.
2706                 //   Hence the source must be live for the transition to be live.
2707                 //
2708                 // We also short-circuit the liveness if the structure is harmless
2709                 // to mark (i.e. its global object and prototype are both already
2710                 // live).
2711                 
2712                 visitor.append(&dfgCommon->transitions[i].m_to);
2713             } else
2714                 allAreMarkedSoFar = false;
2715         }
2716     }
2717 #endif // ENABLE(DFG_JIT)
2718     
2719     if (allAreMarkedSoFar)
2720         m_allTransitionsHaveBeenMarked = true;
2721 }
2722
2723 void CodeBlock::determineLiveness(SlotVisitor& visitor)
2724 {
2725     UNUSED_PARAM(visitor);
2726     
2727 #if ENABLE(DFG_JIT)
2728     // Check if we have any remaining work to do.
2729     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2730     if (dfgCommon->livenessHasBeenProved)
2731         return;
2732     
2733     // Now check all of our weak references. If all of them are live, then we
2734     // have proved liveness and so we scan our strong references. If at end of
2735     // GC we still have not proved liveness, then this code block is toast.
2736     bool allAreLiveSoFar = true;
2737     for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
2738         if (!Heap::isMarked(dfgCommon->weakReferences[i].get())) {
2739             allAreLiveSoFar = false;
2740             break;
2741         }
2742     }
2743     if (allAreLiveSoFar) {
2744         for (unsigned i = 0; i < dfgCommon->weakStructureReferences.size(); ++i) {
2745             if (!Heap::isMarked(dfgCommon->weakStructureReferences[i].get())) {
2746                 allAreLiveSoFar = false;
2747                 break;
2748             }
2749         }
2750     }
2751     
2752     // If some weak references are dead, then this fixpoint iteration was
2753     // unsuccessful.
2754     if (!allAreLiveSoFar)
2755         return;
2756     
2757     // All weak references are live. Record this information so we don't
2758     // come back here again, and scan the strong references.
2759     dfgCommon->livenessHasBeenProved = true;
2760     visitor.appendUnbarrieredReadOnlyPointer(this);
2761 #endif // ENABLE(DFG_JIT)
2762 }
2763
2764 void CodeBlock::WeakReferenceHarvester::visitWeakReferences(SlotVisitor& visitor)
2765 {
2766     CodeBlock* codeBlock =
2767         bitwise_cast<CodeBlock*>(
2768             bitwise_cast<char*>(this) - OBJECT_OFFSETOF(CodeBlock, m_weakReferenceHarvester));
2769
2770     codeBlock->propagateTransitions(visitor);
2771     codeBlock->determineLiveness(visitor);
2772 }
2773
2774 void CodeBlock::finalizeLLIntInlineCaches()
2775 {
2776 #if ENABLE(WEBASSEMBLY)
2777     if (m_ownerExecutable->isWebAssemblyExecutable())
2778         return;
2779 #endif
2780
2781     Interpreter* interpreter = m_vm->interpreter;
2782     const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
2783     for (size_t size = propertyAccessInstructions.size(), i = 0; i < size; ++i) {
2784         Instruction* curInstruction = &instructions()[propertyAccessInstructions[i]];
2785         switch (interpreter->getOpcodeID(curInstruction[0].u.opcode)) {
2786         case op_get_by_id:
2787         case op_get_by_id_proto_load:
2788         case op_get_by_id_unset: {
2789             StructureID oldStructureID = curInstruction[4].u.structureID;
2790             if (!oldStructureID || Heap::isMarked(m_vm->heap.structureIDTable().get(oldStructureID)))
2791                 break;
2792             if (Options::verboseOSR())
2793                 dataLogF("Clearing LLInt property access.\n");
2794             clearLLIntGetByIdCache(curInstruction);
2795             break;
2796         }
2797         case op_put_by_id: {
2798             StructureID oldStructureID = curInstruction[4].u.structureID;
2799             StructureID newStructureID = curInstruction[6].u.structureID;
2800             StructureChain* chain = curInstruction[7].u.structureChain.get();
2801             if ((!oldStructureID || Heap::isMarked(m_vm->heap.structureIDTable().get(oldStructureID))) &&
2802                 (!newStructureID || Heap::isMarked(m_vm->heap.structureIDTable().get(newStructureID))) &&
2803                 (!chain || Heap::isMarked(chain)))
2804                 break;
2805             if (Options::verboseOSR())
2806                 dataLogF("Clearing LLInt put transition.\n");
2807             curInstruction[4].u.structureID = 0;
2808             curInstruction[5].u.operand = 0;
2809             curInstruction[6].u.structureID = 0;
2810             curInstruction[7].u.structureChain.clear();
2811             break;
2812         }
2813         case op_get_array_length:
2814             break;
2815         case op_to_this:
2816             if (!curInstruction[2].u.structure || Heap::isMarked(curInstruction[2].u.structure.get()))
2817                 break;
2818             if (Options::verboseOSR())
2819                 dataLogF("Clearing LLInt to_this with structure %p.\n", curInstruction[2].u.structure.get());
2820             curInstruction[2].u.structure.clear();
2821             curInstruction[3].u.toThisStatus = merge(
2822                 curInstruction[3].u.toThisStatus, ToThisClearedByGC);
2823             break;
2824         case op_create_this: {
2825             auto& cacheWriteBarrier = curInstruction[4].u.jsCell;
2826             if (!cacheWriteBarrier || cacheWriteBarrier.unvalidatedGet() == JSCell::seenMultipleCalleeObjects())
2827                 break;
2828             JSCell* cachedFunction = cacheWriteBarrier.get();
2829             if (Heap::isMarked(cachedFunction))
2830                 break;
2831             if (Options::verboseOSR())
2832                 dataLogF("Clearing LLInt create_this with cached callee %p.\n", cachedFunction);
2833             cacheWriteBarrier.clear();
2834             break;
2835         }
2836         case op_resolve_scope: {
2837             // Right now this isn't strictly necessary. Any symbol tables that this will refer to
2838             // are for outer functions, and we refer to those functions strongly, and they refer
2839             // to the symbol table strongly. But it's nice to be on the safe side.
2840             WriteBarrierBase<SymbolTable>& symbolTable = curInstruction[6].u.symbolTable;
2841             if (!symbolTable || Heap::isMarked(symbolTable.get()))
2842                 break;
2843             if (Options::verboseOSR())
2844                 dataLogF("Clearing dead symbolTable %p.\n", symbolTable.get());
2845             symbolTable.clear();
2846             break;
2847         }
2848         case op_get_from_scope:
2849         case op_put_to_scope: {
2850             GetPutInfo getPutInfo = GetPutInfo(curInstruction[4].u.operand);
2851             if (getPutInfo.resolveType() == GlobalVar || getPutInfo.resolveType() == GlobalVarWithVarInjectionChecks 
2852                 || getPutInfo.resolveType() == LocalClosureVar || getPutInfo.resolveType() == GlobalLexicalVar || getPutInfo.resolveType() == GlobalLexicalVarWithVarInjectionChecks)
2853                 continue;
2854             WriteBarrierBase<Structure>& structure = curInstruction[5].u.structure;
2855             if (!structure || Heap::isMarked(structure.get()))
2856                 break;
2857             if (Options::verboseOSR())
2858                 dataLogF("Clearing scope access with structure %p.\n", structure.get());
2859             structure.clear();
2860             break;
2861         }
2862         default:
2863             OpcodeID opcodeID = interpreter->getOpcodeID(curInstruction[0].u.opcode);
2864             ASSERT_WITH_MESSAGE_UNUSED(opcodeID, false, "Unhandled opcode in CodeBlock::finalizeUnconditionally, %s(%d) at bc %u", opcodeNames[opcodeID], opcodeID, propertyAccessInstructions[i]);
2865         }
2866     }
2867
2868     // We can't just remove all the sets when we clear the caches since we might have created a watchpoint set
2869     // then cleared the cache without GCing in between.
2870     m_llintGetByIdWatchpointMap.removeIf([](const StructureWatchpointMap::KeyValuePairType& pair) -> bool {
2871         return !Heap::isMarked(pair.key);
2872     });
2873
2874     for (unsigned i = 0; i < m_llintCallLinkInfos.size(); ++i) {
2875         if (m_llintCallLinkInfos[i].isLinked() && !Heap::isMarked(m_llintCallLinkInfos[i].callee.get())) {
2876             if (Options::verboseOSR())
2877                 dataLog("Clearing LLInt call from ", *this, "\n");
2878             m_llintCallLinkInfos[i].unlink();
2879         }
2880         if (!!m_llintCallLinkInfos[i].lastSeenCallee && !Heap::isMarked(m_llintCallLinkInfos[i].lastSeenCallee.get()))
2881             m_llintCallLinkInfos[i].lastSeenCallee.clear();
2882     }
2883 }
2884
2885 void CodeBlock::finalizeBaselineJITInlineCaches()
2886 {
2887 #if ENABLE(JIT)
2888     for (auto iter = callLinkInfosBegin(); !!iter; ++iter)
2889         (*iter)->visitWeak(*vm());
2890
2891     for (Bag<StructureStubInfo>::iterator iter = m_stubInfos.begin(); !!iter; ++iter) {
2892         StructureStubInfo& stubInfo = **iter;
2893         stubInfo.visitWeakReferences(this);
2894     }
2895 #endif
2896 }
2897
2898 void CodeBlock::UnconditionalFinalizer::finalizeUnconditionally()
2899 {
2900     CodeBlock* codeBlock = bitwise_cast<CodeBlock*>(
2901         bitwise_cast<char*>(this) - OBJECT_OFFSETOF(CodeBlock, m_unconditionalFinalizer));
2902
2903 #if ENABLE(DFG_JIT)
2904     if (codeBlock->shouldJettisonDueToWeakReference()) {
2905         codeBlock->jettison(Profiler::JettisonDueToWeakReference);
2906         return;
2907     }
2908 #endif // ENABLE(DFG_JIT)
2909
2910     if (codeBlock->shouldJettisonDueToOldAge()) {
2911         codeBlock->jettison(Profiler::JettisonDueToOldAge);
2912         return;
2913     }
2914
2915     if (JITCode::couldBeInterpreted(codeBlock->jitType()))
2916         codeBlock->finalizeLLIntInlineCaches();
2917
2918 #if ENABLE(JIT)
2919     if (!!codeBlock->jitCode())
2920         codeBlock->finalizeBaselineJITInlineCaches();
2921 #endif
2922 }
2923
2924 void CodeBlock::getStubInfoMap(const ConcurrentJITLocker&, StubInfoMap& result)
2925 {
2926 #if ENABLE(JIT)
2927     toHashMap(m_stubInfos, getStructureStubInfoCodeOrigin, result);
2928 #else
2929     UNUSED_PARAM(result);
2930 #endif
2931 }
2932
2933 void CodeBlock::getStubInfoMap(StubInfoMap& result)
2934 {
2935     ConcurrentJITLocker locker(m_lock);
2936     getStubInfoMap(locker, result);
2937 }
2938
2939 void CodeBlock::getCallLinkInfoMap(const ConcurrentJITLocker&, CallLinkInfoMap& result)
2940 {
2941 #if ENABLE(JIT)
2942     toHashMap(m_callLinkInfos, getCallLinkInfoCodeOrigin, result);
2943 #else
2944     UNUSED_PARAM(result);
2945 #endif
2946 }
2947
2948 void CodeBlock::getCallLinkInfoMap(CallLinkInfoMap& result)
2949 {
2950     ConcurrentJITLocker locker(m_lock);
2951     getCallLinkInfoMap(locker, result);
2952 }
2953
2954 void CodeBlock::getByValInfoMap(const ConcurrentJITLocker&, ByValInfoMap& result)
2955 {
2956 #if ENABLE(JIT)
2957     for (auto* byValInfo : m_byValInfos)
2958         result.add(CodeOrigin(byValInfo->bytecodeIndex), byValInfo);
2959 #else
2960     UNUSED_PARAM(result);
2961 #endif
2962 }
2963
2964 void CodeBlock::getByValInfoMap(ByValInfoMap& result)
2965 {
2966     ConcurrentJITLocker locker(m_lock);
2967     getByValInfoMap(locker, result);
2968 }
2969
2970 #if ENABLE(JIT)
2971 StructureStubInfo* CodeBlock::addStubInfo(AccessType accessType)
2972 {
2973     ConcurrentJITLocker locker(m_lock);
2974     return m_stubInfos.add(accessType);
2975 }
2976
2977 StructureStubInfo* CodeBlock::findStubInfo(CodeOrigin codeOrigin)
2978 {
2979     for (StructureStubInfo* stubInfo : m_stubInfos) {
2980         if (stubInfo->codeOrigin == codeOrigin)
2981             return stubInfo;
2982     }
2983     return nullptr;
2984 }
2985
2986 ByValInfo* CodeBlock::addByValInfo()
2987 {
2988     ConcurrentJITLocker locker(m_lock);
2989     return m_byValInfos.add();
2990 }
2991
2992 CallLinkInfo* CodeBlock::addCallLinkInfo()
2993 {
2994     ConcurrentJITLocker locker(m_lock);
2995     return m_callLinkInfos.add();
2996 }
2997
2998 CallLinkInfo* CodeBlock::getCallLinkInfoForBytecodeIndex(unsigned index)
2999 {
3000     for (auto iter = m_callLinkInfos.begin(); !!iter; ++iter) {
3001         if ((*iter)->codeOrigin() == CodeOrigin(index))
3002             return *iter;
3003     }
3004     return nullptr;
3005 }
3006 #endif
3007
3008 void CodeBlock::visitOSRExitTargets(SlotVisitor& visitor)
3009 {
3010     // We strongly visit OSR exits targets because we don't want to deal with
3011     // the complexity of generating an exit target CodeBlock on demand and
3012     // guaranteeing that it matches the details of the CodeBlock we compiled
3013     // the OSR exit against.
3014
3015     visitor.append(&m_alternative);
3016
3017 #if ENABLE(DFG_JIT)
3018     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
3019     if (dfgCommon->inlineCallFrames) {
3020         for (auto* inlineCallFrame : *dfgCommon->inlineCallFrames) {
3021             ASSERT(inlineCallFrame->baselineCodeBlock);
3022             visitor.append(&inlineCallFrame->baselineCodeBlock);
3023         }
3024     }
3025 #endif
3026 }
3027
3028 void CodeBlock::stronglyVisitStrongReferences(SlotVisitor& visitor)
3029 {
3030     visitor.append(&m_globalObject);
3031     visitor.append(&m_ownerExecutable);
3032     visitor.append(&m_unlinkedCode);
3033     if (m_rareData)
3034         m_rareData->m_evalCodeCache.visitAggregate(visitor);
3035     visitor.appendValues(m_constantRegisters.data(), m_constantRegisters.size());
3036     for (size_t i = 0; i < m_functionExprs.size(); ++i)
3037         visitor.append(&m_functionExprs[i]);
3038     for (size_t i = 0; i < m_functionDecls.size(); ++i)
3039         visitor.append(&m_functionDecls[i]);
3040     for (unsigned i = 0; i < m_objectAllocationProfiles.size(); ++i)
3041         m_objectAllocationProfiles[i].visitAggregate(visitor);
3042
3043 #if ENABLE(DFG_JIT)
3044     if (JITCode::isOptimizingJIT(jitType()))
3045         visitOSRExitTargets(visitor);
3046 #endif
3047
3048     updateAllPredictions();
3049 }
3050
3051 void CodeBlock::stronglyVisitWeakReferences(SlotVisitor& visitor)
3052 {
3053     UNUSED_PARAM(visitor);
3054
3055 #if ENABLE(DFG_JIT)
3056     if (!JITCode::isOptimizingJIT(jitType()))
3057         return;
3058     
3059     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
3060
3061     for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
3062         if (!!dfgCommon->transitions[i].m_codeOrigin)
3063             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.
3064         visitor.append(&dfgCommon->transitions[i].m_from);
3065         visitor.append(&dfgCommon->transitions[i].m_to);
3066     }
3067     
3068     for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i)
3069         visitor.append(&dfgCommon->weakReferences[i]);
3070
3071     for (unsigned i = 0; i < dfgCommon->weakStructureReferences.size(); ++i)
3072         visitor.append(&dfgCommon->weakStructureReferences[i]);
3073
3074     dfgCommon->livenessHasBeenProved = true;
3075 #endif    
3076 }
3077
3078 CodeBlock* CodeBlock::baselineAlternative()
3079 {
3080 #if ENABLE(JIT)
3081     CodeBlock* result = this;
3082     while (result->alternative())
3083         result = result->alternative();
3084     RELEASE_ASSERT(result);
3085     RELEASE_ASSERT(JITCode::isBaselineCode(result->jitType()) || result->jitType() == JITCode::None);
3086     return result;
3087 #else
3088     return this;
3089 #endif
3090 }
3091
3092 CodeBlock* CodeBlock::baselineVersion()
3093 {
3094 #if ENABLE(JIT)
3095     if (JITCode::isBaselineCode(jitType()))
3096         return this;
3097     CodeBlock* result = replacement();
3098     if (!result) {
3099         // This can happen if we're creating the original CodeBlock for an executable.
3100         // Assume that we're the baseline CodeBlock.
3101         RELEASE_ASSERT(jitType() == JITCode::None);
3102         return this;
3103     }
3104     result = result->baselineAlternative();
3105     return result;
3106 #else
3107     return this;
3108 #endif
3109 }
3110
3111 #if ENABLE(JIT)
3112 bool CodeBlock::hasOptimizedReplacement(JITCode::JITType typeToReplace)
3113 {
3114     return JITCode::isHigherTier(replacement()->jitType(), typeToReplace);
3115 }
3116
3117 bool CodeBlock::hasOptimizedReplacement()
3118 {
3119     return hasOptimizedReplacement(jitType());
3120 }
3121 #endif
3122
3123 HandlerInfo* CodeBlock::handlerForBytecodeOffset(unsigned bytecodeOffset, RequiredHandler requiredHandler)
3124 {
3125     RELEASE_ASSERT(bytecodeOffset < instructions().size());
3126     return handlerForIndex(bytecodeOffset, requiredHandler);
3127 }
3128
3129 HandlerInfo* CodeBlock::handlerForIndex(unsigned index, RequiredHandler requiredHandler)
3130 {
3131     if (!m_rareData)
3132         return 0;
3133     
3134     Vector<HandlerInfo>& exceptionHandlers = m_rareData->m_exceptionHandlers;
3135     for (size_t i = 0; i < exceptionHandlers.size(); ++i) {
3136         HandlerInfo& handler = exceptionHandlers[i];
3137         if ((requiredHandler == RequiredHandler::CatchHandler) && !handler.isCatchHandler())
3138             continue;
3139
3140         // Handlers are ordered innermost first, so the first handler we encounter
3141         // that contains the source address is the correct handler to use.
3142         // This index used is either the BytecodeOffset or a CallSiteIndex.
3143         if (handler.start <= index && handler.end > index)
3144             return &handler;
3145     }
3146
3147     return 0;
3148 }
3149
3150 CallSiteIndex CodeBlock::newExceptionHandlingCallSiteIndex(CallSiteIndex originalCallSite)
3151 {
3152 #if ENABLE(DFG_JIT)
3153     RELEASE_ASSERT(JITCode::isOptimizingJIT(jitType()));
3154     RELEASE_ASSERT(canGetCodeOrigin(originalCallSite));
3155     ASSERT(!!handlerForIndex(originalCallSite.bits()));
3156     CodeOrigin originalOrigin = codeOrigin(originalCallSite);
3157     return m_jitCode->dfgCommon()->addUniqueCallSiteIndex(originalOrigin);
3158 #else
3159     // We never create new on-the-fly exception handling
3160     // call sites outside the DFG/FTL inline caches.
3161     UNUSED_PARAM(originalCallSite);
3162     RELEASE_ASSERT_NOT_REACHED();
3163     return CallSiteIndex(0u);
3164 #endif
3165 }
3166
3167 void CodeBlock::removeExceptionHandlerForCallSite(CallSiteIndex callSiteIndex)
3168 {
3169     RELEASE_ASSERT(m_rareData);
3170     Vector<HandlerInfo>& exceptionHandlers = m_rareData->m_exceptionHandlers;
3171     unsigned index = callSiteIndex.bits();
3172     for (size_t i = 0; i < exceptionHandlers.size(); ++i) {
3173         HandlerInfo& handler = exceptionHandlers[i];
3174         if (handler.start <= index && handler.end > index) {
3175             exceptionHandlers.remove(i);
3176             return;
3177         }
3178     }
3179
3180     RELEASE_ASSERT_NOT_REACHED();
3181 }
3182
3183 unsigned CodeBlock::lineNumberForBytecodeOffset(unsigned bytecodeOffset)
3184 {
3185     RELEASE_ASSERT(bytecodeOffset < instructions().size());
3186     return ownerScriptExecutable()->firstLine() + m_unlinkedCode->lineNumberForBytecodeOffset(bytecodeOffset);
3187 }
3188
3189 unsigned CodeBlock::columnNumberForBytecodeOffset(unsigned bytecodeOffset)
3190 {
3191     int divot;
3192     int startOffset;
3193     int endOffset;
3194     unsigned line;
3195     unsigned column;
3196     expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
3197     return column;
3198 }
3199
3200 void CodeBlock::expressionRangeForBytecodeOffset(unsigned bytecodeOffset, int& divot, int& startOffset, int& endOffset, unsigned& line, unsigned& column) const
3201 {
3202     m_unlinkedCode->expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
3203     divot += m_sourceOffset;
3204     column += line ? 1 : firstLineColumnOffset();
3205     line += ownerScriptExecutable()->firstLine();
3206 }
3207
3208 bool CodeBlock::hasOpDebugForLineAndColumn(unsigned line, unsigned column)
3209 {
3210     Interpreter* interpreter = vm()->interpreter;
3211     const Instruction* begin = instructions().begin();
3212     const Instruction* end = instructions().end();
3213     for (const Instruction* it = begin; it != end;) {
3214         OpcodeID opcodeID = interpreter->getOpcodeID(it->u.opcode);
3215         if (opcodeID == op_debug) {
3216             unsigned bytecodeOffset = it - begin;
3217             int unused;
3218             unsigned opDebugLine;
3219             unsigned opDebugColumn;
3220             expressionRangeForBytecodeOffset(bytecodeOffset, unused, unused, unused, opDebugLine, opDebugColumn);
3221             if (line == opDebugLine && (column == Breakpoint::unspecifiedColumn || column == opDebugColumn))
3222                 return true;
3223         }
3224         it += opcodeLengths[opcodeID];
3225     }
3226     return false;
3227 }
3228
3229 void CodeBlock::shrinkToFit(ShrinkMode shrinkMode)
3230 {
3231     m_rareCaseProfiles.shrinkToFit();
3232     m_resultProfiles.shrinkToFit();
3233     
3234     if (shrinkMode == EarlyShrink) {
3235         m_constantRegisters.shrinkToFit();
3236         m_constantsSourceCodeRepresentation.shrinkToFit();
3237         
3238         if (m_rareData) {
3239             m_rareData->m_switchJumpTables.shrinkToFit();
3240             m_rareData->m_stringSwitchJumpTables.shrinkToFit();
3241             m_rareData->m_liveCalleeLocalsAtYield.shrinkToFit();
3242         }
3243     } // else don't shrink these, because we would have already pointed pointers into these tables.
3244 }
3245
3246 #if ENABLE(JIT)
3247 void CodeBlock::linkIncomingCall(ExecState* callerFrame, CallLinkInfo* incoming)
3248 {
3249     noticeIncomingCall(callerFrame);
3250     m_incomingCalls.push(incoming);
3251 }
3252
3253 void CodeBlock::linkIncomingPolymorphicCall(ExecState* callerFrame, PolymorphicCallNode* incoming)
3254 {
3255     noticeIncomingCall(callerFrame);
3256     m_incomingPolymorphicCalls.push(incoming);
3257 }
3258 #endif // ENABLE(JIT)
3259
3260 void CodeBlock::unlinkIncomingCalls()
3261 {
3262     while (m_incomingLLIntCalls.begin() != m_incomingLLIntCalls.end())
3263         m_incomingLLIntCalls.begin()->unlink();
3264 #if ENABLE(JIT)
3265     while (m_incomingCalls.begin() != m_incomingCalls.end())
3266         m_incomingCalls.begin()->unlink(*vm());
3267     while (m_incomingPolymorphicCalls.begin() != m_incomingPolymorphicCalls.end())
3268         m_incomingPolymorphicCalls.begin()->unlink(*vm());
3269 #endif // ENABLE(JIT)
3270 }
3271
3272 void CodeBlock::linkIncomingCall(ExecState* callerFrame, LLIntCallLinkInfo* incoming)
3273 {
3274     noticeIncomingCall(callerFrame);
3275     m_incomingLLIntCalls.push(incoming);
3276 }
3277
3278 CodeBlock* CodeBlock::newReplacement()
3279 {
3280     return ownerScriptExecutable()->newReplacementCodeBlockFor(specializationKind());
3281 }
3282
3283 #if ENABLE(JIT)
3284 CodeBlock* CodeBlock::replacement()
3285 {
3286     const ClassInfo* classInfo = this->classInfo();
3287
3288     if (classInfo == FunctionCodeBlock::info())
3289         return jsCast<FunctionExecutable*>(ownerExecutable())->codeBlockFor(m_isConstructor ? CodeForConstruct : CodeForCall);
3290
3291     if (classInfo == EvalCodeBlock::info())
3292         return jsCast<EvalExecutable*>(ownerExecutable())->codeBlock();
3293
3294     if (classInfo == ProgramCodeBlock::info())
3295         return jsCast<ProgramExecutable*>(ownerExecutable())->codeBlock();
3296
3297     if (classInfo == ModuleProgramCodeBlock::info())
3298         return jsCast<ModuleProgramExecutable*>(ownerExecutable())->codeBlock();
3299
3300 #if ENABLE(WEBASSEMBLY)
3301     if (classInfo == WebAssemblyCodeBlock::info())
3302         return nullptr;
3303 #endif
3304
3305     RELEASE_ASSERT_NOT_REACHED();
3306     return nullptr;
3307 }
3308
3309 DFG::CapabilityLevel CodeBlock::computeCapabilityLevel()
3310 {
3311     const ClassInfo* classInfo = this->classInfo();
3312
3313     if (classInfo == FunctionCodeBlock::info()) {
3314         if (m_isConstructor)
3315             return DFG::functionForConstructCapabilityLevel(this);
3316         return DFG::functionForCallCapabilityLevel(this);
3317     }
3318
3319     if (classInfo == EvalCodeBlock::info())
3320         return DFG::evalCapabilityLevel(this);
3321
3322     if (classInfo == ProgramCodeBlock::info())
3323         return DFG::programCapabilityLevel(this);
3324
3325     if (classInfo == ModuleProgramCodeBlock::info())
3326         return DFG::programCapabilityLevel(this);
3327
3328 #if ENABLE(WEBASSEMBLY)
3329     if (classInfo == WebAssemblyCodeBlock::info())
3330         return DFG::CannotCompile;
3331 #endif
3332
3333     RELEASE_ASSERT_NOT_REACHED();
3334     return DFG::CannotCompile;
3335 }
3336
3337 #endif // ENABLE(JIT)
3338
3339 void CodeBlock::jettison(Profiler::JettisonReason reason, ReoptimizationMode mode, const FireDetail* detail)
3340 {
3341 #if !ENABLE(DFG_JIT)
3342     UNUSED_PARAM(mode);
3343     UNUSED_PARAM(detail);
3344 #endif
3345     
3346     CODEBLOCK_LOG_EVENT(this, "jettison", ("due to ", reason, ", counting = ", mode == CountReoptimization, ", detail = ", pointerDump(detail)));
3347
3348     RELEASE_ASSERT(reason != Profiler::NotJettisoned);
3349     
3350 #if ENABLE(DFG_JIT)
3351     if (DFG::shouldDumpDisassembly()) {
3352         dataLog("Jettisoning ", *this);
3353         if (mode == CountReoptimization)
3354             dataLog(" and counting reoptimization");
3355         dataLog(" due to ", reason);
3356         if (detail)
3357             dataLog(", ", *detail);
3358         dataLog(".\n");
3359     }
3360     
3361     if (reason == Profiler::JettisonDueToWeakReference) {
3362         if (DFG::shouldDumpDisassembly()) {
3363             dataLog(*this, " will be jettisoned because of the following dead references:\n");
3364             DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
3365             for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
3366                 DFG::WeakReferenceTransition& transition = dfgCommon->transitions[i];
3367                 JSCell* origin = transition.m_codeOrigin.get();
3368                 JSCell* from = transition.m_from.get();
3369                 JSCell* to = transition.m_to.get();
3370                 if ((!origin || Heap::isMarked(origin)) && Heap::isMarked(from))
3371                     continue;
3372                 dataLog("    Transition under ", RawPointer(origin), ", ", RawPointer(from), " -> ", RawPointer(to), ".\n");
3373             }
3374             for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
3375                 JSCell* weak = dfgCommon->weakReferences[i].get();
3376                 if (Heap::isMarked(weak))
3377                     continue;
3378                 dataLog("    Weak reference ", RawPointer(weak), ".\n");
3379             }
3380         }
3381     }
3382 #endif // ENABLE(DFG_JIT)
3383
3384     DeferGCForAWhile deferGC(*heap());
3385     
3386     // We want to accomplish two things here:
3387     // 1) Make sure that if this CodeBlock is on the stack right now, then if we return to it
3388     //    we should OSR exit at the top of the next bytecode instruction after the return.
3389     // 2) Make sure that if we call the owner executable, then we shouldn't call this CodeBlock.
3390
3391 #if ENABLE(DFG_JIT)
3392     if (reason != Profiler::JettisonDueToOldAge) {
3393         if (Profiler::Compilation* compilation = jitCode()->dfgCommon()->compilation.get())
3394             compilation->setJettisonReason(reason, detail);
3395         
3396         // This accomplishes (1), and does its own book-keeping about whether it has already happened.
3397         if (!jitCode()->dfgCommon()->invalidate()) {
3398             // We've already been invalidated.
3399             RELEASE_ASSERT(this != replacement());
3400             return;
3401         }
3402     }
3403     
3404     if (DFG::shouldDumpDisassembly())
3405         dataLog("    Did invalidate ", *this, "\n");
3406     
3407     // Count the reoptimization if that's what the user wanted.
3408     if (mode == CountReoptimization) {
3409         // FIXME: Maybe this should call alternative().
3410         // https://bugs.webkit.org/show_bug.cgi?id=123677
3411         baselineAlternative()->countReoptimization();
3412         if (DFG::shouldDumpDisassembly())
3413             dataLog("    Did count reoptimization for ", *this, "\n");
3414     }
3415     
3416     if (this != replacement()) {
3417         // This means that we were never the entrypoint. This can happen for OSR entry code
3418         // blocks.
3419         return;
3420     }
3421
3422     if (alternative())
3423         alternative()->optimizeAfterWarmUp();
3424
3425     if (reason != Profiler::JettisonDueToOldAge)
3426         tallyFrequentExitSites();
3427 #endif // ENABLE(DFG_JIT)
3428
3429     // This accomplishes (2).
3430     ownerScriptExecutable()->installCode(
3431         m_globalObject->vm(), alternative(), codeType(), specializationKind());
3432
3433 #if ENABLE(DFG_JIT)
3434     if (DFG::shouldDumpDisassembly())
3435         dataLog("    Did install baseline version of ", *this, "\n");
3436 #endif // ENABLE(DFG_JIT)
3437 }
3438
3439 JSGlobalObject* CodeBlock::globalObjectFor(CodeOrigin codeOrigin)
3440 {
3441     if (!codeOrigin.inlineCallFrame)
3442         return globalObject();
3443     return codeOrigin.inlineCallFrame->baselineCodeBlock->globalObject();
3444 }
3445
3446 class RecursionCheckFunctor {
3447 public:
3448     RecursionCheckFunctor(CallFrame* startCallFrame, CodeBlock* codeBlock, unsigned depthToCheck)
3449         : m_startCallFrame(startCallFrame)
3450         , m_codeBlock(codeBlock)
3451         , m_depthToCheck(depthToCheck)
3452         , m_foundStartCallFrame(false)
3453         , m_didRecurse(false)
3454     { }
3455
3456     StackVisitor::Status operator()(StackVisitor& visitor) const
3457     {
3458         CallFrame* currentCallFrame = visitor->callFrame();
3459
3460         if (currentCallFrame == m_startCallFrame)
3461             m_foundStartCallFrame = true;
3462
3463         if (m_foundStartCallFrame) {
3464             if (visitor->callFrame()->codeBlock() == m_codeBlock) {
3465                 m_didRecurse = true;
3466                 return StackVisitor::Done;
3467             }
3468
3469             if (!m_depthToCheck--)
3470                 return StackVisitor::Done;
3471         }
3472
3473         return StackVisitor::Continue;
3474     }
3475
3476     bool didRecurse() const { return m_didRecurse; }
3477
3478 private:
3479     CallFrame* m_startCallFrame;
3480     CodeBlock* m_codeBlock;
3481     mutable unsigned m_depthToCheck;
3482     mutable bool m_foundStartCallFrame;
3483     mutable bool m_didRecurse;
3484 };
3485
3486 void CodeBlock::noticeIncomingCall(ExecState* callerFrame)
3487 {
3488     CodeBlock* callerCodeBlock = callerFrame->codeBlock();
3489     
3490     if (Options::verboseCallLink())
3491         dataLog("Noticing call link from ", pointerDump(callerCodeBlock), " to ", *this, "\n");
3492     
3493 #if ENABLE(DFG_JIT)
3494     if (!m_shouldAlwaysBeInlined)
3495         return;
3496     
3497     if (!callerCodeBlock) {
3498         m_shouldAlwaysBeInlined = false;
3499         if (Options::verboseCallLink())
3500             dataLog("    Clearing SABI because caller is native.\n");
3501         return;
3502     }
3503
3504     if (!hasBaselineJITProfiling())
3505         return;
3506
3507     if (!DFG::mightInlineFunction(this))
3508         return;
3509
3510     if (!canInline(capabilityLevelState()))
3511         return;
3512     
3513     if (!DFG::isSmallEnoughToInlineCodeInto(callerCodeBlock)) {
3514         m_shouldAlwaysBeInlined = false;
3515         if (Options::verboseCallLink())
3516             dataLog("    Clearing SABI because caller is too large.\n");
3517         return;
3518     }
3519
3520     if (callerCodeBlock->jitType() == JITCode::InterpreterThunk) {
3521         // If the caller is still in the interpreter, then we can't expect inlining to
3522         // happen anytime soon. Assume it's profitable to optimize it separately. This
3523         // ensures that a function is SABI only if it is called no more frequently than
3524         // any of its callers.
3525         m_shouldAlwaysBeInlined = false;
3526         if (Options::verboseCallLink())
3527             dataLog("    Clearing SABI because caller is in LLInt.\n");
3528         return;
3529     }
3530     
3531     if (JITCode::isOptimizingJIT(callerCodeBlock->jitType())) {
3532         m_shouldAlwaysBeInlined = false;
3533         if (Options::verboseCallLink())
3534             dataLog("    Clearing SABI bcause caller was already optimized.\n");
3535         return;
3536     }
3537     
3538     if (callerCodeBlock->codeType() != FunctionCode) {
3539         // If the caller is either eval or global code, assume that that won't be
3540         // optimized anytime soon. For eval code this is particularly true since we
3541         // delay eval optimization by a *lot*.
3542         m_shouldAlwaysBeInlined = false;
3543         if (Options::verboseCallLink())
3544             dataLog("    Clearing SABI because caller is not a function.\n");
3545         return;
3546     }
3547
3548     // Recursive calls won't be inlined.
3549     RecursionCheckFunctor functor(callerFrame, this, Options::maximumInliningDepth());
3550     vm()->topCallFrame->iterate(functor);
3551
3552     if (functor.didRecurse()) {
3553         if (Options::verboseCallLink())
3554             dataLog("    Clearing SABI because recursion was detected.\n");
3555         m_shouldAlwaysBeInlined = false;
3556         return;
3557     }
3558     
3559     if (callerCodeBlock->capabilityLevelState() == DFG::CapabilityLevelNotSet) {
3560         dataLog("In call from ", *callerCodeBlock, " ", callerFrame->codeOrigin(), " to ", *this, ": caller's DFG capability level is not set.\n");
3561         CRASH();
3562     }
3563     
3564     if (canCompile(callerCodeBlock->capabilityLevelState()))
3565         return;
3566     
3567     if (Options::verboseCallLink())
3568         dataLog("    Clearing SABI because the caller is not a DFG candidate.\n");
3569     
3570     m_shouldAlwaysBeInlined = false;
3571 #endif
3572 }
3573
3574 unsigned CodeBlock::reoptimizationRetryCounter() const
3575 {
3576 #if ENABLE(JIT)
3577     ASSERT(m_reoptimizationRetryCounter <= Options::reoptimizationRetryCounterMax());
3578     return m_reoptimizationRetryCounter;
3579 #else
3580     return 0;
3581 #endif // ENABLE(JIT)
3582 }
3583
3584 #if ENABLE(JIT)
3585 void CodeBlock::setCalleeSaveRegisters(RegisterSet calleeSaveRegisters)
3586 {
3587     m_calleeSaveRegisters = std::make_unique<RegisterAtOffsetList>(calleeSaveRegisters);
3588 }
3589
3590 void CodeBlock::setCalleeSaveRegisters(std::unique_ptr<RegisterAtOffsetList> registerAtOffsetList)
3591 {
3592     m_calleeSaveRegisters = WTFMove(registerAtOffsetList);
3593 }
3594     
3595 static size_t roundCalleeSaveSpaceAsVirtualRegisters(size_t calleeSaveRegisters)
3596 {
3597     static const unsigned cpuRegisterSize = sizeof(void*);
3598     return (WTF::roundUpToMultipleOf(sizeof(Register), calleeSaveRegisters * cpuRegisterSize) / sizeof(Register));
3599
3600 }
3601
3602 size_t CodeBlock::llintBaselineCalleeSaveSpaceAsVirtualRegisters()
3603 {
3604     return roundCalleeSaveSpaceAsVirtualRegisters(numberOfLLIntBaselineCalleeSaveRegisters());
3605 }
3606
3607 size_t CodeBlock::calleeSaveSpaceAsVirtualRegisters()
3608 {
3609     return roundCalleeSaveSpaceAsVirtualRegisters(m_calleeSaveRegisters->size());
3610 }
3611
3612 void CodeBlock::countReoptimization()
3613 {
3614     m_reoptimizationRetryCounter++;
3615     if (m_reoptimizationRetryCounter > Options::reoptimizationRetryCounterMax())
3616         m_reoptimizationRetryCounter = Options::reoptimizationRetryCounterMax();
3617 }
3618
3619 unsigned CodeBlock::numberOfDFGCompiles()
3620 {
3621     ASSERT(JITCode::isBaselineCode(jitType()));
3622     if (Options::testTheFTL()) {
3623         if (m_didFailFTLCompilation)
3624             return 1000000;
3625         return (m_hasBeenCompiledWithFTL ? 1 : 0) + m_reoptimizationRetryCounter;
3626     }
3627     return (JITCode::isOptimizingJIT(replacement()->jitType()) ? 1 : 0) + m_reoptimizationRetryCounter;
3628 }
3629
3630 int32_t CodeBlock::codeTypeThresholdMultiplier() const
3631 {
3632     if (codeType() == EvalCode)
3633         return Options::evalThresholdMultiplier();
3634     
3635     return 1;
3636 }
3637
3638 double CodeBlock::optimizationThresholdScalingFactor()
3639 {
3640     // This expression arises from doing a least-squares fit of
3641     //
3642     // F[x_] =: a * Sqrt[x + b] + Abs[c * x] + d
3643     //
3644     // against the data points:
3645     //
3646     //    x       F[x_]
3647     //    10       0.9          (smallest reasonable code block)
3648     //   200       1.0          (typical small-ish code block)
3649     //   320       1.2          (something I saw in 3d-cube that I wanted to optimize)
3650     //  1268       5.0          (something I saw in 3d-cube that I didn't want to optimize)
3651     //  4000       5.5          (random large size, used to cause the function to converge to a shallow curve of some sort)
3652     // 10000       6.0          (similar to above)
3653     //
3654     // I achieve the minimization using the following Mathematica code:
3655     //
3656     // MyFunctionTemplate[x_, a_, b_, c_, d_] := a*Sqrt[x + b] + Abs[c*x] + d
3657     //
3658     // samples = {{10, 0.9}, {200, 1}, {320, 1.2}, {1268, 5}, {4000, 5.5}, {10000, 6}}
3659     //
3660     // solution = 
3661     //     Minimize[Plus @@ ((MyFunctionTemplate[#[[1]], a, b, c, d] - #[[2]])^2 & /@ samples),
3662     //         {a, b, c, d}][[2]]
3663     //
3664     // And the code below (to initialize a, b, c, d) is generated by:
3665     //
3666     // Print["const double " <> ToString[#[[1]]] <> " = " <>
3667     //     If[#[[2]] < 0.00001, "0.0", ToString[#[[2]]]] <> ";"] & /@ solution
3668     //
3669     // We've long known the following to be true:
3670     // - Small code blocks are cheap to optimize and so we should do it sooner rather
3671     //   than later.
3672     // - Large code blocks are expensive to optimize and so we should postpone doing so,
3673     //   and sometimes have a large enough threshold that we never optimize them.
3674     // - The difference in cost is not totally linear because (a) just invoking the
3675     //   DFG incurs some base cost and (b) for large code blocks there is enough slop
3676     //   in the correlation between instruction count and the actual compilation cost
3677     //   that for those large blocks, the instruction count should not have a strong
3678     //   influence on our threshold.
3679     //
3680     // I knew the goals but I didn't know how to achieve them; so I picked an interesting
3681     // example where the heuristics were right (code block in 3d-cube with instruction
3682     // count 320, which got compiled early as it should have been) and one where they were
3683     // totally wrong (code block in 3d-cube with instruction count 1268, which was expensive
3684     // to compile and didn't run often enough to warrant compilation in my opinion), and
3685     // then threw in additional data points that represented my own guess of what our
3686     // heuristics should do for some round-numbered examples.
3687     //
3688     // The expression to which I decided to fit the data arose because I started with an
3689     // affine function, and then did two things: put the linear part in an Abs to ensure
3690     // that the fit didn't end up choosing a negative value of c (which would result in
3691     // the function turning over and going negative for large x) and I threw in a Sqrt
3692     // term because Sqrt represents my intution that the function should be more sensitive
3693     // to small changes in small values of x, but less sensitive when x gets large.
3694     
3695     // Note that the current fit essentially eliminates the linear portion of the
3696     // expression (c == 0.0).
3697     const double a = 0.061504;
3698     const double b = 1.02406;
3699     const double c = 0.0;
3700     const double d = 0.825914;
3701     
3702     double instructionCount = this->instructionCount();
3703     
3704     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.
3705     
3706     double result = d + a * sqrt(instructionCount + b) + c * instructionCount;
3707     
3708     result *= codeTypeThresholdMultiplier();
3709     
3710     if (Options::verboseOSR()) {
3711         dataLog(
3712             *this, ": instruction count is ", instructionCount,
3713             ", scaling execution counter by ", result, " * ", codeTypeThresholdMultiplier(),
3714             "\n");
3715     }
3716     return result;
3717 }
3718
3719 static int32_t clipThreshold(double threshold)
3720 {
3721     if (threshold < 1.0)
3722         return 1;
3723     
3724     if (threshold > static_cast<double>(std::numeric_limits<int32_t>::max()))
3725         return std::numeric_limits<int32_t>::max();
3726     
3727     return static_cast<int32_t>(threshold);
3728 }
3729
3730 int32_t CodeBlock::adjustedCounterValue(int32_t desiredThreshold)
3731 {
3732     return clipThreshold(
3733         static_cast<double>(desiredThreshold) *
3734         optimizationThresholdScalingFactor() *
3735         (1 << reoptimizationRetryCounter()));
3736 }
3737
3738 bool CodeBlock::checkIfOptimizationThresholdReached()
3739 {
3740 #if ENABLE(DFG_JIT)
3741     if (DFG::Worklist* worklist = DFG::existingGlobalDFGWorklistOrNull()) {
3742         if (worklist->compilationState(DFG::CompilationKey(this, DFG::DFGMode))
3743             == DFG::Worklist::Compiled) {
3744             optimizeNextInvocation();
3745             return true;
3746         }
3747     }
3748 #endif
3749     
3750     return m_jitExecuteCounter.checkIfThresholdCrossedAndSet(this);
3751 }
3752
3753 void CodeBlock::optimizeNextInvocation()
3754 {
3755     if (Options::verboseOSR())
3756         dataLog(*this, ": Optimizing next invocation.\n");
3757     m_jitExecuteCounter.setNewThreshold(0, this);
3758 }
3759
3760 void CodeBlock::dontOptimizeAnytimeSoon()
3761 {
3762     if (Options::verboseOSR())
3763         dataLog(*this, ": Not optimizing anytime soon.\n");
3764     m_jitExecuteCounter.deferIndefinitely();
3765 }
3766
3767 void CodeBlock::optimizeAfterWarmUp()
3768 {
3769     if (Options::verboseOSR())
3770         dataLog(*this, ": Optimizing after warm-up.\n");
3771 #if ENABLE(DFG_JIT)
3772     m_jitExecuteCounter.setNewThreshold(
3773         adjustedCounterValue(Options::thresholdForOptimizeAfterWarmUp()), this);
3774 #endif
3775 }
3776
3777 void CodeBlock::optimizeAfterLongWarmUp()
3778 {
3779     if (Options::verboseOSR())
3780         dataLog(*this, ": Optimizing after long warm-up.\n");
3781 #if ENABLE(DFG_JIT)
3782     m_jitExecuteCounter.setNewThreshold(
3783         adjustedCounterValue(Options::thresholdForOptimizeAfterLongWarmUp()), this);
3784 #endif
3785 }
3786
3787 void CodeBlock::optimizeSoon()
3788 {
3789     if (Options::verboseOSR())
3790         dataLog(*this, ": Optimizing soon.\n");
3791 #if ENABLE(DFG_JIT)
3792     m_jitExecuteCounter.setNewThreshold(
3793         adjustedCounterValue(Options::thresholdForOptimizeSoon()), this);
3794 #endif
3795 }
3796
3797 void CodeBlock::forceOptimizationSlowPathConcurrently()
3798 {
3799     if (Options::verboseOSR())
3800         dataLog(*this, ": Forcing slow path concurrently.\n");
3801     m_jitExecuteCounter.forceSlowPathConcurrently();
3802 }
3803
3804 #if ENABLE(DFG_JIT)
3805 void CodeBlock::setOptimizationThresholdBasedOnCompilationResult(CompilationResult result)
3806 {
3807     JITCode::JITType type = jitType();
3808     if (type != JITCode::BaselineJIT) {
3809         dataLog(*this, ": expected to have baseline code but have ", type, "\n");
3810         RELEASE_ASSERT_NOT_REACHED();
3811     }
3812     
3813     CodeBlock* theReplacement = replacement();
3814     if ((result == CompilationSuccessful) != (theReplacement != this)) {
3815         dataLog(*this, ": we have result = ", result, " but ");
3816         if (theReplacement == this)
3817             dataLog("we are our own replacement.\n");
3818         else
3819             dataLog("our replacement is ", pointerDump(theReplacement), "\n");
3820         RELEASE_ASSERT_NOT_REACHED();
3821     }
3822     
3823     switch (result) {
3824     case CompilationSuccessful:
3825         RELEASE_ASSERT(JITCode::isOptimizingJIT(replacement()->jitType()));
3826         optimizeNextInvocation();
3827         return;
3828     case CompilationFailed:
3829         dontOptimizeAnytimeSoon();
3830         return;
3831     case CompilationDeferred:
3832         // We'd like to do dontOptimizeAnytimeSoon() but we cannot because
3833         // forceOptimizationSlowPathConcurrently() is inherently racy. It won't
3834         // necessarily guarantee anything. So, we make sure that even if that
3835