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