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