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