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