Rename op_put_getter_setter to op_put_getter_setter_by_id
[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_profile_will_call: {
1495             int function = (++it)->u.operand;
1496             printLocationOpAndRegisterOperand(out, exec, location, it, "profile_will_call", function);
1497             break;
1498         }
1499         case op_profile_did_call: {
1500             int function = (++it)->u.operand;
1501             printLocationOpAndRegisterOperand(out, exec, location, it, "profile_did_call", function);
1502             break;
1503         }
1504         case op_end: {
1505             int r0 = (++it)->u.operand;
1506             printLocationOpAndRegisterOperand(out, exec, location, it, "end", r0);
1507             break;
1508         }
1509         case op_resolve_scope: {
1510             int r0 = (++it)->u.operand;
1511             int scope = (++it)->u.operand;
1512             int id0 = (++it)->u.operand;
1513             ResolveType resolveType = static_cast<ResolveType>((++it)->u.operand);
1514             int depth = (++it)->u.operand;
1515             void* pointer = (++it)->u.pointer;
1516             printLocationAndOp(out, exec, location, it, "resolve_scope");
1517             out.printf("%s, %s, %s, <%s>, %d, %p", registerName(r0).data(), registerName(scope).data(), idName(id0, identifier(id0)).data(), resolveTypeName(resolveType), depth, pointer);
1518             break;
1519         }
1520         case op_get_from_scope: {
1521             int r0 = (++it)->u.operand;
1522             int r1 = (++it)->u.operand;
1523             int id0 = (++it)->u.operand;
1524             GetPutInfo getPutInfo = GetPutInfo((++it)->u.operand);
1525             ++it; // Structure
1526             int operand = (++it)->u.operand; // Operand
1527             printLocationAndOp(out, exec, location, it, "get_from_scope");
1528             out.print(registerName(r0), ", ", registerName(r1));
1529             if (static_cast<unsigned>(id0) == UINT_MAX)
1530                 out.print(", anonymous");
1531             else
1532                 out.print(", ", idName(id0, identifier(id0)));
1533             out.print(", ", getPutInfo.operand(), "<", resolveModeName(getPutInfo.resolveMode()), "|", resolveTypeName(getPutInfo.resolveType()), "|", initializationModeName(getPutInfo.initializationMode()), ">, ", operand);
1534             dumpValueProfiling(out, it, hasPrintedProfiling);
1535             break;
1536         }
1537         case op_put_to_scope: {
1538             int r0 = (++it)->u.operand;
1539             int id0 = (++it)->u.operand;
1540             int r1 = (++it)->u.operand;
1541             GetPutInfo getPutInfo = GetPutInfo((++it)->u.operand);
1542             ++it; // Structure
1543             int operand = (++it)->u.operand; // Operand
1544             printLocationAndOp(out, exec, location, it, "put_to_scope");
1545             out.print(registerName(r0));
1546             if (static_cast<unsigned>(id0) == UINT_MAX)
1547                 out.print(", anonymous");
1548             else
1549                 out.print(", ", idName(id0, identifier(id0)));
1550             out.print(", ", registerName(r1), ", ", getPutInfo.operand(), "<", resolveModeName(getPutInfo.resolveMode()), "|", resolveTypeName(getPutInfo.resolveType()), "|", initializationModeName(getPutInfo.initializationMode()), ">, <structure>, ", operand);
1551             break;
1552         }
1553         case op_get_from_arguments: {
1554             int r0 = (++it)->u.operand;
1555             int r1 = (++it)->u.operand;
1556             int offset = (++it)->u.operand;
1557             printLocationAndOp(out, exec, location, it, "get_from_arguments");
1558             out.printf("%s, %s, %d", registerName(r0).data(), registerName(r1).data(), offset);
1559             dumpValueProfiling(out, it, hasPrintedProfiling);
1560             break;
1561         }
1562         case op_put_to_arguments: {
1563             int r0 = (++it)->u.operand;
1564             int offset = (++it)->u.operand;
1565             int r1 = (++it)->u.operand;
1566             printLocationAndOp(out, exec, location, it, "put_to_arguments");
1567             out.printf("%s, %d, %s", registerName(r0).data(), offset, registerName(r1).data());
1568             break;
1569         }
1570         default:
1571             RELEASE_ASSERT_NOT_REACHED();
1572     }
1573
1574     dumpRareCaseProfile(out, "rare case: ", rareCaseProfileForBytecodeOffset(location), hasPrintedProfiling);
1575     dumpRareCaseProfile(out, "special fast case: ", specialFastCaseProfileForBytecodeOffset(location), hasPrintedProfiling);
1576     
1577 #if ENABLE(DFG_JIT)
1578     Vector<DFG::FrequentExitSite> exitSites = exitProfile().exitSitesFor(location);
1579     if (!exitSites.isEmpty()) {
1580         out.print(" !! frequent exits: ");
1581         CommaPrinter comma;
1582         for (unsigned i = 0; i < exitSites.size(); ++i)
1583             out.print(comma, exitSites[i].kind(), " ", exitSites[i].jitType());
1584     }
1585 #else // ENABLE(DFG_JIT)
1586     UNUSED_PARAM(location);
1587 #endif // ENABLE(DFG_JIT)
1588     out.print("\n");
1589 }
1590
1591 void CodeBlock::dumpBytecode(
1592     PrintStream& out, unsigned bytecodeOffset,
1593     const StubInfoMap& stubInfos, const CallLinkInfoMap& callLinkInfos)
1594 {
1595     ExecState* exec = m_globalObject->globalExec();
1596     const Instruction* it = instructions().begin() + bytecodeOffset;
1597     dumpBytecode(out, exec, instructions().begin(), it, stubInfos, callLinkInfos);
1598 }
1599
1600 #define FOR_EACH_MEMBER_VECTOR(macro) \
1601     macro(instructions) \
1602     macro(callLinkInfos) \
1603     macro(linkedCallerList) \
1604     macro(identifiers) \
1605     macro(functionExpressions) \
1606     macro(constantRegisters)
1607
1608 #define FOR_EACH_MEMBER_VECTOR_RARE_DATA(macro) \
1609     macro(regexps) \
1610     macro(functions) \
1611     macro(exceptionHandlers) \
1612     macro(switchJumpTables) \
1613     macro(stringSwitchJumpTables) \
1614     macro(evalCodeCache) \
1615     macro(expressionInfo) \
1616     macro(lineInfo) \
1617     macro(callReturnIndexVector)
1618
1619 template<typename T>
1620 static size_t sizeInBytes(const Vector<T>& vector)
1621 {
1622     return vector.capacity() * sizeof(T);
1623 }
1624
1625 namespace {
1626
1627 class PutToScopeFireDetail : public FireDetail {
1628 public:
1629     PutToScopeFireDetail(CodeBlock* codeBlock, const Identifier& ident)
1630         : m_codeBlock(codeBlock)
1631         , m_ident(ident)
1632     {
1633     }
1634     
1635     virtual void dump(PrintStream& out) const override
1636     {
1637         out.print("Linking put_to_scope in ", FunctionExecutableDump(jsCast<FunctionExecutable*>(m_codeBlock->ownerExecutable())), " for ", m_ident);
1638     }
1639     
1640 private:
1641     CodeBlock* m_codeBlock;
1642     const Identifier& m_ident;
1643 };
1644
1645 } // anonymous namespace
1646
1647 CodeBlock::CodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, CodeBlock& other)
1648     : JSCell(*vm, structure)
1649     , m_globalObject(other.m_globalObject)
1650     , m_heap(other.m_heap)
1651     , m_numCalleeRegisters(other.m_numCalleeRegisters)
1652     , m_numVars(other.m_numVars)
1653     , m_isConstructor(other.m_isConstructor)
1654     , m_shouldAlwaysBeInlined(true)
1655     , m_didFailFTLCompilation(false)
1656     , m_hasBeenCompiledWithFTL(false)
1657     , m_unlinkedCode(*other.m_vm, this, other.m_unlinkedCode.get())
1658     , m_hasDebuggerStatement(false)
1659     , m_steppingMode(SteppingModeDisabled)
1660     , m_numBreakpoints(0)
1661     , m_ownerExecutable(*other.m_vm, this, other.m_ownerExecutable.get())
1662     , m_vm(other.m_vm)
1663     , m_instructions(other.m_instructions)
1664     , m_thisRegister(other.m_thisRegister)
1665     , m_scopeRegister(other.m_scopeRegister)
1666     , m_lexicalEnvironmentRegister(other.m_lexicalEnvironmentRegister)
1667     , m_isStrictMode(other.m_isStrictMode)
1668     , m_needsActivation(other.m_needsActivation)
1669     , m_source(other.m_source)
1670     , m_sourceOffset(other.m_sourceOffset)
1671     , m_firstLineColumnOffset(other.m_firstLineColumnOffset)
1672     , m_codeType(other.m_codeType)
1673     , m_constantRegisters(other.m_constantRegisters)
1674     , m_constantsSourceCodeRepresentation(other.m_constantsSourceCodeRepresentation)
1675     , m_functionDecls(other.m_functionDecls)
1676     , m_functionExprs(other.m_functionExprs)
1677     , m_osrExitCounter(0)
1678     , m_optimizationDelayCounter(0)
1679     , m_reoptimizationRetryCounter(0)
1680     , m_creationTime(std::chrono::steady_clock::now())
1681     , m_hash(other.m_hash)
1682 #if ENABLE(JIT)
1683     , m_capabilityLevelState(DFG::CapabilityLevelNotSet)
1684 #endif
1685 {
1686     m_visitWeaklyHasBeenCalled.store(false, std::memory_order_relaxed);
1687
1688     ASSERT(m_heap->isDeferred());
1689     ASSERT(m_scopeRegister.isLocal());
1690
1691     setNumParameters(other.numParameters());
1692 }
1693
1694 void CodeBlock::finishCreation(VM& vm, CopyParsedBlockTag, CodeBlock& other)
1695 {
1696     Base::finishCreation(vm);
1697
1698     optimizeAfterWarmUp();
1699     jitAfterWarmUp();
1700
1701     if (other.m_rareData) {
1702         createRareDataIfNecessary();
1703         
1704         m_rareData->m_exceptionHandlers = other.m_rareData->m_exceptionHandlers;
1705         m_rareData->m_constantBuffers = other.m_rareData->m_constantBuffers;
1706         m_rareData->m_switchJumpTables = other.m_rareData->m_switchJumpTables;
1707         m_rareData->m_stringSwitchJumpTables = other.m_rareData->m_stringSwitchJumpTables;
1708     }
1709     
1710     m_heap->m_codeBlocks.add(this);
1711 }
1712
1713 CodeBlock::CodeBlock(VM* vm, Structure* structure, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock,
1714     JSScope* scope, PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset, unsigned firstLineColumnOffset)
1715     : JSCell(*vm, structure)
1716     , m_globalObject(scope->globalObject()->vm(), this, scope->globalObject())
1717     , m_heap(&m_globalObject->vm().heap)
1718     , m_numCalleeRegisters(unlinkedCodeBlock->m_numCalleeRegisters)
1719     , m_numVars(unlinkedCodeBlock->m_numVars)
1720     , m_isConstructor(unlinkedCodeBlock->isConstructor())
1721     , m_shouldAlwaysBeInlined(true)
1722     , m_didFailFTLCompilation(false)
1723     , m_hasBeenCompiledWithFTL(false)
1724     , m_unlinkedCode(m_globalObject->vm(), this, unlinkedCodeBlock)
1725     , m_hasDebuggerStatement(false)
1726     , m_steppingMode(SteppingModeDisabled)
1727     , m_numBreakpoints(0)
1728     , m_ownerExecutable(m_globalObject->vm(), this, ownerExecutable)
1729     , m_vm(unlinkedCodeBlock->vm())
1730     , m_thisRegister(unlinkedCodeBlock->thisRegister())
1731     , m_scopeRegister(unlinkedCodeBlock->scopeRegister())
1732     , m_lexicalEnvironmentRegister(unlinkedCodeBlock->activationRegister())
1733     , m_isStrictMode(unlinkedCodeBlock->isStrictMode())
1734     , m_needsActivation(unlinkedCodeBlock->hasActivationRegister() && unlinkedCodeBlock->codeType() == FunctionCode)
1735     , m_source(sourceProvider)
1736     , m_sourceOffset(sourceOffset)
1737     , m_firstLineColumnOffset(firstLineColumnOffset)
1738     , m_codeType(unlinkedCodeBlock->codeType())
1739     , m_osrExitCounter(0)
1740     , m_optimizationDelayCounter(0)
1741     , m_reoptimizationRetryCounter(0)
1742     , m_creationTime(std::chrono::steady_clock::now())
1743 #if ENABLE(JIT)
1744     , m_capabilityLevelState(DFG::CapabilityLevelNotSet)
1745 #endif
1746 {
1747     m_visitWeaklyHasBeenCalled.store(false, std::memory_order_relaxed);
1748
1749     ASSERT(m_heap->isDeferred());
1750     ASSERT(m_scopeRegister.isLocal());
1751
1752     ASSERT(m_source);
1753     setNumParameters(unlinkedCodeBlock->numParameters());
1754 }
1755
1756 void CodeBlock::finishCreation(VM& vm, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock,
1757     JSScope* scope)
1758 {
1759     Base::finishCreation(vm);
1760
1761     if (vm.typeProfiler() || vm.controlFlowProfiler())
1762         vm.functionHasExecutedCache()->removeUnexecutedRange(ownerExecutable->sourceID(), ownerExecutable->typeProfilingStartOffset(), ownerExecutable->typeProfilingEndOffset());
1763
1764     setConstantRegisters(unlinkedCodeBlock->constantRegisters(), unlinkedCodeBlock->constantsSourceCodeRepresentation());
1765     if (unlinkedCodeBlock->usesGlobalObject())
1766         m_constantRegisters[unlinkedCodeBlock->globalObjectRegister().toConstantIndex()].set(*m_vm, this, m_globalObject.get());
1767
1768     for (unsigned i = 0; i < LinkTimeConstantCount; i++) {
1769         LinkTimeConstant type = static_cast<LinkTimeConstant>(i);
1770         if (unsigned registerIndex = unlinkedCodeBlock->registerIndexForLinkTimeConstant(type))
1771             m_constantRegisters[registerIndex].set(*m_vm, this, m_globalObject->jsCellForLinkTimeConstant(type));
1772     }
1773
1774     HashSet<int, WTF::IntHash<int>, WTF::UnsignedWithZeroKeyHashTraits<int>> clonedConstantSymbolTables;
1775     {
1776         HashSet<SymbolTable*> clonedSymbolTables;
1777         for (unsigned i = 0; i < m_constantRegisters.size(); i++) {
1778             if (m_constantRegisters[i].get().isEmpty())
1779                 continue;
1780             if (SymbolTable* symbolTable = jsDynamicCast<SymbolTable*>(m_constantRegisters[i].get())) {
1781                 RELEASE_ASSERT(clonedSymbolTables.add(symbolTable).isNewEntry);
1782                 if (m_vm->typeProfiler()) {
1783                     ConcurrentJITLocker locker(symbolTable->m_lock);
1784                     symbolTable->prepareForTypeProfiling(locker);
1785                 }
1786                 m_constantRegisters[i].set(*m_vm, this, symbolTable->cloneScopePart(*m_vm));
1787                 clonedConstantSymbolTables.add(i + FirstConstantRegisterIndex);
1788             }
1789         }
1790     }
1791
1792     // We already have the cloned symbol table for the module environment since we need to instantiate
1793     // the module environments before linking the code block. We replace the stored symbol table with the already cloned one.
1794     if (UnlinkedModuleProgramCodeBlock* unlinkedModuleProgramCodeBlock = jsDynamicCast<UnlinkedModuleProgramCodeBlock*>(unlinkedCodeBlock)) {
1795         SymbolTable* clonedSymbolTable = jsCast<ModuleProgramExecutable*>(ownerExecutable)->moduleEnvironmentSymbolTable();
1796         if (m_vm->typeProfiler()) {
1797             ConcurrentJITLocker locker(clonedSymbolTable->m_lock);
1798             clonedSymbolTable->prepareForTypeProfiling(locker);
1799         }
1800         replaceConstant(unlinkedModuleProgramCodeBlock->moduleEnvironmentSymbolTableConstantRegisterOffset(), clonedSymbolTable);
1801     }
1802
1803     m_functionDecls.resizeToFit(unlinkedCodeBlock->numberOfFunctionDecls());
1804     for (size_t count = unlinkedCodeBlock->numberOfFunctionDecls(), i = 0; i < count; ++i) {
1805         UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionDecl(i);
1806         if (vm.typeProfiler() || vm.controlFlowProfiler())
1807             vm.functionHasExecutedCache()->insertUnexecutedRange(ownerExecutable->sourceID(), unlinkedExecutable->typeProfilingStartOffset(), unlinkedExecutable->typeProfilingEndOffset());
1808         m_functionDecls[i].set(*m_vm, this, unlinkedExecutable->link(*m_vm, ownerExecutable->source()));
1809     }
1810
1811     m_functionExprs.resizeToFit(unlinkedCodeBlock->numberOfFunctionExprs());
1812     for (size_t count = unlinkedCodeBlock->numberOfFunctionExprs(), i = 0; i < count; ++i) {
1813         UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionExpr(i);
1814         if (vm.typeProfiler() || vm.controlFlowProfiler())
1815             vm.functionHasExecutedCache()->insertUnexecutedRange(ownerExecutable->sourceID(), unlinkedExecutable->typeProfilingStartOffset(), unlinkedExecutable->typeProfilingEndOffset());
1816         m_functionExprs[i].set(*m_vm, this, unlinkedExecutable->link(*m_vm, ownerExecutable->source()));
1817     }
1818
1819     if (unlinkedCodeBlock->hasRareData()) {
1820         createRareDataIfNecessary();
1821         if (size_t count = unlinkedCodeBlock->constantBufferCount()) {
1822             m_rareData->m_constantBuffers.grow(count);
1823             for (size_t i = 0; i < count; i++) {
1824                 const UnlinkedCodeBlock::ConstantBuffer& buffer = unlinkedCodeBlock->constantBuffer(i);
1825                 m_rareData->m_constantBuffers[i] = buffer;
1826             }
1827         }
1828         if (size_t count = unlinkedCodeBlock->numberOfExceptionHandlers()) {
1829             m_rareData->m_exceptionHandlers.resizeToFit(count);
1830             for (size_t i = 0; i < count; i++) {
1831                 const UnlinkedHandlerInfo& unlinkedHandler = unlinkedCodeBlock->exceptionHandler(i);
1832                 HandlerInfo& handler = m_rareData->m_exceptionHandlers[i];
1833 #if ENABLE(JIT)
1834                 handler.initialize(unlinkedHandler, CodeLocationLabel(MacroAssemblerCodePtr::createFromExecutableAddress(LLInt::getCodePtr(op_catch))));
1835 #else
1836                 handler.initialize(unlinkedHandler);
1837 #endif
1838             }
1839         }
1840
1841         if (size_t count = unlinkedCodeBlock->numberOfStringSwitchJumpTables()) {
1842             m_rareData->m_stringSwitchJumpTables.grow(count);
1843             for (size_t i = 0; i < count; i++) {
1844                 UnlinkedStringJumpTable::StringOffsetTable::iterator ptr = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.begin();
1845                 UnlinkedStringJumpTable::StringOffsetTable::iterator end = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.end();
1846                 for (; ptr != end; ++ptr) {
1847                     OffsetLocation offset;
1848                     offset.branchOffset = ptr->value;
1849                     m_rareData->m_stringSwitchJumpTables[i].offsetTable.add(ptr->key, offset);
1850                 }
1851             }
1852         }
1853
1854         if (size_t count = unlinkedCodeBlock->numberOfSwitchJumpTables()) {
1855             m_rareData->m_switchJumpTables.grow(count);
1856             for (size_t i = 0; i < count; i++) {
1857                 UnlinkedSimpleJumpTable& sourceTable = unlinkedCodeBlock->switchJumpTable(i);
1858                 SimpleJumpTable& destTable = m_rareData->m_switchJumpTables[i];
1859                 destTable.branchOffsets = sourceTable.branchOffsets;
1860                 destTable.min = sourceTable.min;
1861             }
1862         }
1863     }
1864
1865     // Allocate metadata buffers for the bytecode
1866     if (size_t size = unlinkedCodeBlock->numberOfLLintCallLinkInfos())
1867         m_llintCallLinkInfos.resizeToFit(size);
1868     if (size_t size = unlinkedCodeBlock->numberOfArrayProfiles())
1869         m_arrayProfiles.grow(size);
1870     if (size_t size = unlinkedCodeBlock->numberOfArrayAllocationProfiles())
1871         m_arrayAllocationProfiles.resizeToFit(size);
1872     if (size_t size = unlinkedCodeBlock->numberOfValueProfiles())
1873         m_valueProfiles.resizeToFit(size);
1874     if (size_t size = unlinkedCodeBlock->numberOfObjectAllocationProfiles())
1875         m_objectAllocationProfiles.resizeToFit(size);
1876
1877 #if ENABLE(JIT)
1878     setCalleeSaveRegisters(RegisterSet::llintBaselineCalleeSaveRegisters());
1879 #endif
1880
1881     // Copy and translate the UnlinkedInstructions
1882     unsigned instructionCount = unlinkedCodeBlock->instructions().count();
1883     UnlinkedInstructionStream::Reader instructionReader(unlinkedCodeBlock->instructions());
1884
1885     // Bookkeep the strongly referenced module environments.
1886     HashSet<JSModuleEnvironment*> stronglyReferencedModuleEnvironments;
1887
1888     RefCountedArray<Instruction> instructions(instructionCount);
1889
1890     for (unsigned i = 0; !instructionReader.atEnd(); ) {
1891         const UnlinkedInstruction* pc = instructionReader.next();
1892
1893         unsigned opLength = opcodeLength(pc[0].u.opcode);
1894
1895         instructions[i] = vm.interpreter->getOpcode(pc[0].u.opcode);
1896         for (size_t j = 1; j < opLength; ++j) {
1897             if (sizeof(int32_t) != sizeof(intptr_t))
1898                 instructions[i + j].u.pointer = 0;
1899             instructions[i + j].u.operand = pc[j].u.operand;
1900         }
1901         switch (pc[0].u.opcode) {
1902         case op_has_indexed_property: {
1903             int arrayProfileIndex = pc[opLength - 1].u.operand;
1904             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
1905
1906             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
1907             break;
1908         }
1909         case op_call_varargs:
1910         case op_tail_call_varargs:
1911         case op_construct_varargs:
1912         case op_get_by_val: {
1913             int arrayProfileIndex = pc[opLength - 2].u.operand;
1914             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
1915
1916             instructions[i + opLength - 2] = &m_arrayProfiles[arrayProfileIndex];
1917             FALLTHROUGH;
1918         }
1919         case op_get_direct_pname:
1920         case op_get_by_id:
1921         case op_get_from_arguments: {
1922             ValueProfile* profile = &m_valueProfiles[pc[opLength - 1].u.operand];
1923             ASSERT(profile->m_bytecodeOffset == -1);
1924             profile->m_bytecodeOffset = i;
1925             instructions[i + opLength - 1] = profile;
1926             break;
1927         }
1928         case op_put_by_val: {
1929             int arrayProfileIndex = pc[opLength - 1].u.operand;
1930             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
1931             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
1932             break;
1933         }
1934         case op_put_by_val_direct: {
1935             int arrayProfileIndex = pc[opLength - 1].u.operand;
1936             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
1937             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
1938             break;
1939         }
1940
1941         case op_new_array:
1942         case op_new_array_buffer:
1943         case op_new_array_with_size: {
1944             int arrayAllocationProfileIndex = pc[opLength - 1].u.operand;
1945             instructions[i + opLength - 1] = &m_arrayAllocationProfiles[arrayAllocationProfileIndex];
1946             break;
1947         }
1948         case op_new_object: {
1949             int objectAllocationProfileIndex = pc[opLength - 1].u.operand;
1950             ObjectAllocationProfile* objectAllocationProfile = &m_objectAllocationProfiles[objectAllocationProfileIndex];
1951             int inferredInlineCapacity = pc[opLength - 2].u.operand;
1952
1953             instructions[i + opLength - 1] = objectAllocationProfile;
1954             objectAllocationProfile->initialize(vm,
1955                 this, m_globalObject->objectPrototype(), inferredInlineCapacity);
1956             break;
1957         }
1958
1959         case op_call:
1960         case op_tail_call:
1961         case op_call_eval: {
1962             ValueProfile* profile = &m_valueProfiles[pc[opLength - 1].u.operand];
1963             ASSERT(profile->m_bytecodeOffset == -1);
1964             profile->m_bytecodeOffset = i;
1965             instructions[i + opLength - 1] = profile;
1966             int arrayProfileIndex = pc[opLength - 2].u.operand;
1967             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
1968             instructions[i + opLength - 2] = &m_arrayProfiles[arrayProfileIndex];
1969             instructions[i + 5] = &m_llintCallLinkInfos[pc[5].u.operand];
1970             break;
1971         }
1972         case op_construct: {
1973             instructions[i + 5] = &m_llintCallLinkInfos[pc[5].u.operand];
1974             ValueProfile* profile = &m_valueProfiles[pc[opLength - 1].u.operand];
1975             ASSERT(profile->m_bytecodeOffset == -1);
1976             profile->m_bytecodeOffset = i;
1977             instructions[i + opLength - 1] = profile;
1978             break;
1979         }
1980         case op_get_array_length:
1981             CRASH();
1982
1983         case op_create_lexical_environment: {
1984             int symbolTableIndex = pc[3].u.operand;
1985             RELEASE_ASSERT(clonedConstantSymbolTables.contains(symbolTableIndex));
1986             break;
1987         }
1988
1989         case op_resolve_scope: {
1990             const Identifier& ident = identifier(pc[3].u.operand);
1991             ResolveType type = static_cast<ResolveType>(pc[4].u.operand);
1992             RELEASE_ASSERT(type != LocalClosureVar);
1993             int localScopeDepth = pc[5].u.operand;
1994
1995             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Get, type, NotInitialization);
1996             instructions[i + 4].u.operand = op.type;
1997             instructions[i + 5].u.operand = op.depth;
1998             if (op.lexicalEnvironment) {
1999                 if (op.type == ModuleVar) {
2000                     // Keep the linked module environment strongly referenced.
2001                     if (stronglyReferencedModuleEnvironments.add(jsCast<JSModuleEnvironment*>(op.lexicalEnvironment)).isNewEntry)
2002                         addConstant(op.lexicalEnvironment);
2003                     instructions[i + 6].u.jsCell.set(vm, this, op.lexicalEnvironment);
2004                 } else
2005                     instructions[i + 6].u.symbolTable.set(vm, this, op.lexicalEnvironment->symbolTable());
2006             } else if (JSScope* constantScope = JSScope::constantScopeForCodeBlock(op.type, this))
2007                 instructions[i + 6].u.jsCell.set(vm, this, constantScope);
2008             else
2009                 instructions[i + 6].u.pointer = nullptr;
2010             break;
2011         }
2012
2013         case op_get_from_scope: {
2014             ValueProfile* profile = &m_valueProfiles[pc[opLength - 1].u.operand];
2015             ASSERT(profile->m_bytecodeOffset == -1);
2016             profile->m_bytecodeOffset = i;
2017             instructions[i + opLength - 1] = profile;
2018
2019             // get_from_scope dst, scope, id, GetPutInfo, Structure, Operand
2020
2021             int localScopeDepth = pc[5].u.operand;
2022             instructions[i + 5].u.pointer = nullptr;
2023
2024             GetPutInfo getPutInfo = GetPutInfo(pc[4].u.operand);
2025             ASSERT(getPutInfo.initializationMode() == NotInitialization);
2026             if (getPutInfo.resolveType() == LocalClosureVar) {
2027                 instructions[i + 4] = GetPutInfo(getPutInfo.resolveMode(), ClosureVar, getPutInfo.initializationMode()).operand();
2028                 break;
2029             }
2030
2031             const Identifier& ident = identifier(pc[3].u.operand);
2032             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Get, getPutInfo.resolveType(), NotInitialization);
2033
2034             instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), op.type, getPutInfo.initializationMode()).operand();
2035             if (op.type == ModuleVar)
2036                 instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), ClosureVar, getPutInfo.initializationMode()).operand();
2037             if (op.type == GlobalVar || op.type == GlobalVarWithVarInjectionChecks || op.type == GlobalLexicalVar || op.type == GlobalLexicalVarWithVarInjectionChecks)
2038                 instructions[i + 5].u.watchpointSet = op.watchpointSet;
2039             else if (op.structure)
2040                 instructions[i + 5].u.structure.set(vm, this, op.structure);
2041             instructions[i + 6].u.pointer = reinterpret_cast<void*>(op.operand);
2042             break;
2043         }
2044
2045         case op_put_to_scope: {
2046             // put_to_scope scope, id, value, GetPutInfo, Structure, Operand
2047             GetPutInfo getPutInfo = GetPutInfo(pc[4].u.operand);
2048             if (getPutInfo.resolveType() == LocalClosureVar) {
2049                 // Only do watching if the property we're putting to is not anonymous.
2050                 if (static_cast<unsigned>(pc[2].u.operand) != UINT_MAX) {
2051                     int symbolTableIndex = pc[5].u.operand;
2052                     RELEASE_ASSERT(clonedConstantSymbolTables.contains(symbolTableIndex));
2053                     SymbolTable* symbolTable = jsCast<SymbolTable*>(getConstant(symbolTableIndex));
2054                     const Identifier& ident = identifier(pc[2].u.operand);
2055                     ConcurrentJITLocker locker(symbolTable->m_lock);
2056                     auto iter = symbolTable->find(locker, ident.impl());
2057                     RELEASE_ASSERT(iter != symbolTable->end(locker));
2058                     iter->value.prepareToWatch();
2059                     instructions[i + 5].u.watchpointSet = iter->value.watchpointSet();
2060                 } else
2061                     instructions[i + 5].u.watchpointSet = nullptr;
2062                 break;
2063             }
2064
2065             const Identifier& ident = identifier(pc[2].u.operand);
2066             int localScopeDepth = pc[5].u.operand;
2067             instructions[i + 5].u.pointer = nullptr;
2068             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Put, getPutInfo.resolveType(), getPutInfo.initializationMode());
2069
2070             instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), op.type, getPutInfo.initializationMode()).operand();
2071             if (op.type == GlobalVar || op.type == GlobalVarWithVarInjectionChecks || op.type == GlobalLexicalVar || op.type == GlobalLexicalVarWithVarInjectionChecks)
2072                 instructions[i + 5].u.watchpointSet = op.watchpointSet;
2073             else if (op.type == ClosureVar || op.type == ClosureVarWithVarInjectionChecks) {
2074                 if (op.watchpointSet)
2075                     op.watchpointSet->invalidate(PutToScopeFireDetail(this, ident));
2076             } else if (op.structure)
2077                 instructions[i + 5].u.structure.set(vm, this, op.structure);
2078             instructions[i + 6].u.pointer = reinterpret_cast<void*>(op.operand);
2079
2080             break;
2081         }
2082
2083         case op_profile_type: {
2084             RELEASE_ASSERT(vm.typeProfiler());
2085             // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType?
2086             size_t instructionOffset = i + opLength - 1;
2087             unsigned divotStart, divotEnd;
2088             GlobalVariableID globalVariableID = 0;
2089             RefPtr<TypeSet> globalTypeSet;
2090             bool shouldAnalyze = m_unlinkedCode->typeProfilerExpressionInfoForBytecodeOffset(instructionOffset, divotStart, divotEnd);
2091             VirtualRegister profileRegister(pc[1].u.operand);
2092             ProfileTypeBytecodeFlag flag = static_cast<ProfileTypeBytecodeFlag>(pc[3].u.operand);
2093             SymbolTable* symbolTable = nullptr;
2094
2095             switch (flag) {
2096             case ProfileTypeBytecodeClosureVar: {
2097                 const Identifier& ident = identifier(pc[4].u.operand);
2098                 int localScopeDepth = pc[2].u.operand;
2099                 ResolveType type = static_cast<ResolveType>(pc[5].u.operand);
2100                 // Even though type profiling may be profiling either a Get or a Put, we can always claim a Get because
2101                 // we're abstractly "read"ing from a JSScope.
2102                 ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Get, type, NotInitialization);
2103
2104                 if (op.type == ClosureVar || op.type == ModuleVar)
2105                     symbolTable = op.lexicalEnvironment->symbolTable();
2106                 else if (op.type == GlobalVar)
2107                     symbolTable = m_globalObject.get()->symbolTable();
2108
2109                 UniquedStringImpl* impl = (op.type == ModuleVar) ? op.importedName.get() : ident.impl();
2110                 if (symbolTable) {
2111                     ConcurrentJITLocker locker(symbolTable->m_lock);
2112                     // If our parent scope was created while profiling was disabled, it will not have prepared for profiling yet.
2113                     symbolTable->prepareForTypeProfiling(locker);
2114                     globalVariableID = symbolTable->uniqueIDForVariable(locker, impl, vm);
2115                     globalTypeSet = symbolTable->globalTypeSetForVariable(locker, impl, vm);
2116                 } else
2117                     globalVariableID = TypeProfilerNoGlobalIDExists;
2118
2119                 break;
2120             }
2121             case ProfileTypeBytecodeLocallyResolved: {
2122                 int symbolTableIndex = pc[2].u.operand;
2123                 RELEASE_ASSERT(clonedConstantSymbolTables.contains(symbolTableIndex));
2124                 SymbolTable* symbolTable = jsCast<SymbolTable*>(getConstant(symbolTableIndex));
2125                 const Identifier& ident = identifier(pc[4].u.operand);
2126                 ConcurrentJITLocker locker(symbolTable->m_lock);
2127                 // If our parent scope was created while profiling was disabled, it will not have prepared for profiling yet.
2128                 globalVariableID = symbolTable->uniqueIDForVariable(locker, ident.impl(), vm);
2129                 globalTypeSet = symbolTable->globalTypeSetForVariable(locker, ident.impl(), vm);
2130
2131                 break;
2132             }
2133             case ProfileTypeBytecodeDoesNotHaveGlobalID: 
2134             case ProfileTypeBytecodeFunctionArgument: {
2135                 globalVariableID = TypeProfilerNoGlobalIDExists;
2136                 break;
2137             }
2138             case ProfileTypeBytecodeFunctionReturnStatement: {
2139                 RELEASE_ASSERT(ownerExecutable->isFunctionExecutable());
2140                 globalTypeSet = jsCast<FunctionExecutable*>(ownerExecutable)->returnStatementTypeSet();
2141                 globalVariableID = TypeProfilerReturnStatement;
2142                 if (!shouldAnalyze) {
2143                     // Because a return statement can be added implicitly to return undefined at the end of a function,
2144                     // and these nodes don't emit expression ranges because they aren't in the actual source text of
2145                     // the user's program, give the type profiler some range to identify these return statements.
2146                     // Currently, the text offset that is used as identification is "f" in the function keyword
2147                     // and is stored on TypeLocation's m_divotForFunctionOffsetIfReturnStatement member variable.
2148                     divotStart = divotEnd = ownerExecutable->typeProfilingStartOffset();
2149                     shouldAnalyze = true;
2150                 }
2151                 break;
2152             }
2153             }
2154
2155             std::pair<TypeLocation*, bool> locationPair = vm.typeProfiler()->typeLocationCache()->getTypeLocation(globalVariableID,
2156                 ownerExecutable->sourceID(), divotStart, divotEnd, globalTypeSet, &vm);
2157             TypeLocation* location = locationPair.first;
2158             bool isNewLocation = locationPair.second;
2159
2160             if (flag == ProfileTypeBytecodeFunctionReturnStatement)
2161                 location->m_divotForFunctionOffsetIfReturnStatement = ownerExecutable->typeProfilingStartOffset();
2162
2163             if (shouldAnalyze && isNewLocation)
2164                 vm.typeProfiler()->insertNewLocation(location);
2165
2166             instructions[i + 2].u.location = location;
2167             break;
2168         }
2169
2170         case op_debug: {
2171             if (pc[1].u.index == DidReachBreakpoint)
2172                 m_hasDebuggerStatement = true;
2173             break;
2174         }
2175
2176         default:
2177             break;
2178         }
2179         i += opLength;
2180     }
2181
2182     if (vm.controlFlowProfiler())
2183         insertBasicBlockBoundariesForControlFlowProfiler(instructions);
2184
2185     m_instructions = WTF::move(instructions);
2186
2187     // Set optimization thresholds only after m_instructions is initialized, since these
2188     // rely on the instruction count (and are in theory permitted to also inspect the
2189     // instruction stream to more accurate assess the cost of tier-up).
2190     optimizeAfterWarmUp();
2191     jitAfterWarmUp();
2192
2193     // If the concurrent thread will want the code block's hash, then compute it here
2194     // synchronously.
2195     if (Options::alwaysComputeHash())
2196         hash();
2197
2198     if (Options::dumpGeneratedBytecodes())
2199         dumpBytecode();
2200     
2201     m_heap->m_codeBlocks.add(this);
2202     m_heap->reportExtraMemoryAllocated(m_instructions.size() * sizeof(Instruction));
2203 }
2204
2205 #if ENABLE(WEBASSEMBLY)
2206 CodeBlock::CodeBlock(VM* vm, Structure* structure, WebAssemblyExecutable* ownerExecutable, JSGlobalObject* globalObject)
2207     : JSCell(*vm, structure)
2208     , m_globalObject(globalObject->vm(), this, globalObject)
2209     , m_heap(&m_globalObject->vm().heap)
2210     , m_numCalleeRegisters(0)
2211     , m_numVars(0)
2212     , m_isConstructor(false)
2213     , m_shouldAlwaysBeInlined(false)
2214     , m_didFailFTLCompilation(false)
2215     , m_hasBeenCompiledWithFTL(false)
2216     , m_hasDebuggerStatement(false)
2217     , m_steppingMode(SteppingModeDisabled)
2218     , m_numBreakpoints(0)
2219     , m_ownerExecutable(m_globalObject->vm(), this, ownerExecutable)
2220     , m_vm(vm)
2221     , m_isStrictMode(false)
2222     , m_needsActivation(false)
2223     , m_codeType(FunctionCode)
2224     , m_osrExitCounter(0)
2225     , m_optimizationDelayCounter(0)
2226     , m_reoptimizationRetryCounter(0)
2227     , m_creationTime(std::chrono::steady_clock::now())
2228 #if ENABLE(JIT)
2229     , m_capabilityLevelState(DFG::CannotCompile)
2230 #endif
2231 {
2232     ASSERT(m_heap->isDeferred());
2233 }
2234
2235 void CodeBlock::finishCreation(VM& vm, WebAssemblyExecutable*, JSGlobalObject*)
2236 {
2237     Base::finishCreation(vm);
2238
2239     m_heap->m_codeBlocks.add(this);
2240 }
2241 #endif
2242
2243 CodeBlock::~CodeBlock()
2244 {
2245     if (m_vm->m_perBytecodeProfiler)
2246         m_vm->m_perBytecodeProfiler->notifyDestruction(this);
2247     
2248 #if ENABLE(VERBOSE_VALUE_PROFILE)
2249     dumpValueProfiles();
2250 #endif
2251
2252     // We may be destroyed before any CodeBlocks that refer to us are destroyed.
2253     // Consider that two CodeBlocks become unreachable at the same time. There
2254     // is no guarantee about the order in which the CodeBlocks are destroyed.
2255     // So, if we don't remove incoming calls, and get destroyed before the
2256     // CodeBlock(s) that have calls into us, then the CallLinkInfo vector's
2257     // destructor will try to remove nodes from our (no longer valid) linked list.
2258     unlinkIncomingCalls();
2259     
2260     // Note that our outgoing calls will be removed from other CodeBlocks'
2261     // m_incomingCalls linked lists through the execution of the ~CallLinkInfo
2262     // destructors.
2263
2264 #if ENABLE(JIT)
2265     for (Bag<StructureStubInfo>::iterator iter = m_stubInfos.begin(); !!iter; ++iter) {
2266         StructureStubInfo* stub = *iter;
2267         stub->aboutToDie();
2268         stub->deref();
2269     }
2270 #endif // ENABLE(JIT)
2271 }
2272
2273 void CodeBlock::setAlternative(VM& vm, CodeBlock* alternative)
2274 {
2275     m_alternative.set(vm, this, alternative);
2276 }
2277
2278 void CodeBlock::setNumParameters(int newValue)
2279 {
2280     m_numParameters = newValue;
2281
2282     m_argumentValueProfiles.resizeToFit(newValue);
2283 }
2284
2285 void EvalCodeCache::visitAggregate(SlotVisitor& visitor)
2286 {
2287     EvalCacheMap::iterator end = m_cacheMap.end();
2288     for (EvalCacheMap::iterator ptr = m_cacheMap.begin(); ptr != end; ++ptr)
2289         visitor.append(&ptr->value);
2290 }
2291
2292 CodeBlock* CodeBlock::specialOSREntryBlockOrNull()
2293 {
2294 #if ENABLE(FTL_JIT)
2295     if (jitType() != JITCode::DFGJIT)
2296         return 0;
2297     DFG::JITCode* jitCode = m_jitCode->dfg();
2298     return jitCode->osrEntryBlock();
2299 #else // ENABLE(FTL_JIT)
2300     return 0;
2301 #endif // ENABLE(FTL_JIT)
2302 }
2303
2304 void CodeBlock::visitWeakly(SlotVisitor& visitor)
2305 {
2306     bool setByMe = m_visitWeaklyHasBeenCalled.compareExchangeStrong(false, true);
2307     if (!setByMe)
2308         return;
2309
2310     if (Heap::isMarked(this))
2311         return;
2312
2313     if (shouldVisitStrongly()) {
2314         visitor.appendUnbarrieredReadOnlyPointer(this);
2315         return;
2316     }
2317
2318     // There are two things that may use unconditional finalizers: inline cache clearing
2319     // and jettisoning. The probability of us wanting to do at least one of those things
2320     // is probably quite close to 1. So we add one no matter what and when it runs, it
2321     // figures out whether it has any work to do.
2322     visitor.addUnconditionalFinalizer(&m_unconditionalFinalizer);
2323
2324     if (!JITCode::isOptimizingJIT(jitType()))
2325         return;
2326
2327     // If we jettison ourselves we'll install our alternative, so make sure that it
2328     // survives GC even if we don't.
2329     visitor.append(&m_alternative);
2330     
2331     // There are two things that we use weak reference harvesters for: DFG fixpoint for
2332     // jettisoning, and trying to find structures that would be live based on some
2333     // inline cache. So it makes sense to register them regardless.
2334     visitor.addWeakReferenceHarvester(&m_weakReferenceHarvester);
2335
2336 #if ENABLE(DFG_JIT)
2337     // We get here if we're live in the sense that our owner executable is live,
2338     // but we're not yet live for sure in another sense: we may yet decide that this
2339     // code block should be jettisoned based on its outgoing weak references being
2340     // stale. Set a flag to indicate that we're still assuming that we're dead, and
2341     // perform one round of determining if we're live. The GC may determine, based on
2342     // either us marking additional objects, or by other objects being marked for
2343     // other reasons, that this iteration should run again; it will notify us of this
2344     // decision by calling harvestWeakReferences().
2345
2346     m_allTransitionsHaveBeenMarked = false;
2347     propagateTransitions(visitor);
2348
2349     m_jitCode->dfgCommon()->livenessHasBeenProved = false;
2350     determineLiveness(visitor);
2351 #endif // ENABLE(DFG_JIT)
2352 }
2353
2354 void CodeBlock::visitChildren(JSCell* cell, SlotVisitor& visitor)
2355 {
2356     CodeBlock* thisObject = jsCast<CodeBlock*>(cell);
2357     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
2358     JSCell::visitChildren(thisObject, visitor);
2359     thisObject->visitChildren(visitor);
2360 }
2361
2362 void CodeBlock::visitChildren(SlotVisitor& visitor)
2363 {
2364     // There are two things that may use unconditional finalizers: inline cache clearing
2365     // and jettisoning. The probability of us wanting to do at least one of those things
2366     // is probably quite close to 1. So we add one no matter what and when it runs, it
2367     // figures out whether it has any work to do.
2368     visitor.addUnconditionalFinalizer(&m_unconditionalFinalizer);
2369
2370     if (CodeBlock* otherBlock = specialOSREntryBlockOrNull())
2371         visitor.appendUnbarrieredReadOnlyPointer(otherBlock);
2372
2373     if (m_jitCode)
2374         visitor.reportExtraMemoryVisited(m_jitCode->size());
2375     if (m_instructions.size())
2376         visitor.reportExtraMemoryVisited(m_instructions.size() * sizeof(Instruction) / m_instructions.refCount());
2377
2378     visitor.append(&m_unlinkedCode);
2379
2380     stronglyVisitStrongReferences(visitor);
2381     stronglyVisitWeakReferences(visitor);
2382
2383     m_allTransitionsHaveBeenMarked = false;
2384     propagateTransitions(visitor);
2385 }
2386
2387 bool CodeBlock::shouldVisitStrongly()
2388 {
2389     if (Options::forceCodeBlockLiveness())
2390         return true;
2391
2392     if (shouldJettisonDueToOldAge())
2393         return false;
2394
2395     // Interpreter and Baseline JIT CodeBlocks don't need to be jettisoned when
2396     // their weak references go stale. So if a basline JIT CodeBlock gets
2397     // scanned, we can assume that this means that it's live.
2398     if (!JITCode::isOptimizingJIT(jitType()))
2399         return true;
2400
2401     return false;
2402 }
2403
2404 bool CodeBlock::shouldJettisonDueToWeakReference()
2405 {
2406     if (!JITCode::isOptimizingJIT(jitType()))
2407         return false;
2408     return !Heap::isMarked(this);
2409 }
2410
2411 bool CodeBlock::shouldJettisonDueToOldAge()
2412 {
2413     return false;
2414 }
2415
2416 #if ENABLE(DFG_JIT)
2417 static bool shouldMarkTransition(DFG::WeakReferenceTransition& transition)
2418 {
2419     if (transition.m_codeOrigin && !Heap::isMarked(transition.m_codeOrigin.get()))
2420         return false;
2421     
2422     if (!Heap::isMarked(transition.m_from.get()))
2423         return false;
2424     
2425     return true;
2426 }
2427 #endif // ENABLE(DFG_JIT)
2428
2429 void CodeBlock::propagateTransitions(SlotVisitor& visitor)
2430 {
2431     UNUSED_PARAM(visitor);
2432
2433     if (m_allTransitionsHaveBeenMarked)
2434         return;
2435
2436     bool allAreMarkedSoFar = true;
2437         
2438     Interpreter* interpreter = m_vm->interpreter;
2439     if (jitType() == JITCode::InterpreterThunk) {
2440         const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
2441         for (size_t i = 0; i < propertyAccessInstructions.size(); ++i) {
2442             Instruction* instruction = &instructions()[propertyAccessInstructions[i]];
2443             switch (interpreter->getOpcodeID(instruction[0].u.opcode)) {
2444             case op_put_by_id: {
2445                 StructureID oldStructureID = instruction[4].u.structureID;
2446                 StructureID newStructureID = instruction[6].u.structureID;
2447                 if (!oldStructureID || !newStructureID)
2448                     break;
2449                 Structure* oldStructure =
2450                     m_vm->heap.structureIDTable().get(oldStructureID);
2451                 Structure* newStructure =
2452                     m_vm->heap.structureIDTable().get(newStructureID);
2453                 if (Heap::isMarked(oldStructure))
2454                     visitor.appendUnbarrieredReadOnlyPointer(newStructure);
2455                 else
2456                     allAreMarkedSoFar = false;
2457                 break;
2458             }
2459             default:
2460                 break;
2461             }
2462         }
2463     }
2464
2465 #if ENABLE(JIT)
2466     if (JITCode::isJIT(jitType())) {
2467         for (Bag<StructureStubInfo>::iterator iter = m_stubInfos.begin(); !!iter; ++iter) {
2468             StructureStubInfo& stubInfo = **iter;
2469             if (stubInfo.cacheType != CacheType::Stub)
2470                 continue;
2471             PolymorphicAccess* list = stubInfo.u.stub;
2472             JSCell* origin = stubInfo.codeOrigin.codeOriginOwner();
2473             if (origin && !Heap::isMarked(origin)) {
2474                 allAreMarkedSoFar = false;
2475                 continue;
2476             }
2477             for (unsigned j = list->size(); j--;) {
2478                 const AccessCase& access = list->at(j);
2479                 if (access.type() != AccessCase::Transition)
2480                     continue;
2481                 if (Heap::isMarked(access.structure()))
2482                     visitor.appendUnbarrieredReadOnlyPointer(access.newStructure());
2483                 else
2484                     allAreMarkedSoFar = false;
2485             }
2486         }
2487     }
2488 #endif // ENABLE(JIT)
2489     
2490 #if ENABLE(DFG_JIT)
2491     if (JITCode::isOptimizingJIT(jitType())) {
2492         DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2493         
2494         for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
2495             if (shouldMarkTransition(dfgCommon->transitions[i])) {
2496                 // If the following three things are live, then the target of the
2497                 // transition is also live:
2498                 //
2499                 // - This code block. We know it's live already because otherwise
2500                 //   we wouldn't be scanning ourselves.
2501                 //
2502                 // - The code origin of the transition. Transitions may arise from
2503                 //   code that was inlined. They are not relevant if the user's
2504                 //   object that is required for the inlinee to run is no longer
2505                 //   live.
2506                 //
2507                 // - The source of the transition. The transition checks if some
2508                 //   heap location holds the source, and if so, stores the target.
2509                 //   Hence the source must be live for the transition to be live.
2510                 //
2511                 // We also short-circuit the liveness if the structure is harmless
2512                 // to mark (i.e. its global object and prototype are both already
2513                 // live).
2514                 
2515                 visitor.append(&dfgCommon->transitions[i].m_to);
2516             } else
2517                 allAreMarkedSoFar = false;
2518         }
2519     }
2520 #endif // ENABLE(DFG_JIT)
2521     
2522     if (allAreMarkedSoFar)
2523         m_allTransitionsHaveBeenMarked = true;
2524 }
2525
2526 void CodeBlock::determineLiveness(SlotVisitor& visitor)
2527 {
2528     UNUSED_PARAM(visitor);
2529     
2530 #if ENABLE(DFG_JIT)
2531     // Check if we have any remaining work to do.
2532     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2533     if (dfgCommon->livenessHasBeenProved)
2534         return;
2535     
2536     // Now check all of our weak references. If all of them are live, then we
2537     // have proved liveness and so we scan our strong references. If at end of
2538     // GC we still have not proved liveness, then this code block is toast.
2539     bool allAreLiveSoFar = true;
2540     for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
2541         if (!Heap::isMarked(dfgCommon->weakReferences[i].get())) {
2542             allAreLiveSoFar = false;
2543             break;
2544         }
2545     }
2546     if (allAreLiveSoFar) {
2547         for (unsigned i = 0; i < dfgCommon->weakStructureReferences.size(); ++i) {
2548             if (!Heap::isMarked(dfgCommon->weakStructureReferences[i].get())) {
2549                 allAreLiveSoFar = false;
2550                 break;
2551             }
2552         }
2553     }
2554     
2555     // If some weak references are dead, then this fixpoint iteration was
2556     // unsuccessful.
2557     if (!allAreLiveSoFar)
2558         return;
2559     
2560     // All weak references are live. Record this information so we don't
2561     // come back here again, and scan the strong references.
2562     dfgCommon->livenessHasBeenProved = true;
2563     visitor.appendUnbarrieredReadOnlyPointer(this);
2564 #endif // ENABLE(DFG_JIT)
2565 }
2566
2567 void CodeBlock::WeakReferenceHarvester::visitWeakReferences(SlotVisitor& visitor)
2568 {
2569     CodeBlock* codeBlock =
2570         bitwise_cast<CodeBlock*>(
2571             bitwise_cast<char*>(this) - OBJECT_OFFSETOF(CodeBlock, m_weakReferenceHarvester));
2572
2573     codeBlock->propagateTransitions(visitor);
2574     codeBlock->determineLiveness(visitor);
2575 }
2576
2577 void CodeBlock::finalizeLLIntInlineCaches()
2578 {
2579 #if ENABLE(WEBASSEMBLY)
2580     if (m_ownerExecutable->isWebAssemblyExecutable())
2581         return;
2582 #endif
2583
2584     Interpreter* interpreter = m_vm->interpreter;
2585     const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
2586     for (size_t size = propertyAccessInstructions.size(), i = 0; i < size; ++i) {
2587         Instruction* curInstruction = &instructions()[propertyAccessInstructions[i]];
2588         switch (interpreter->getOpcodeID(curInstruction[0].u.opcode)) {
2589         case op_get_by_id: {
2590             StructureID oldStructureID = curInstruction[4].u.structureID;
2591             if (!oldStructureID || Heap::isMarked(m_vm->heap.structureIDTable().get(oldStructureID)))
2592                 break;
2593             if (Options::verboseOSR())
2594                 dataLogF("Clearing LLInt property access.\n");
2595             curInstruction[4].u.structureID = 0;
2596             curInstruction[5].u.operand = 0;
2597             break;
2598         }
2599         case op_put_by_id: {
2600             StructureID oldStructureID = curInstruction[4].u.structureID;
2601             StructureID newStructureID = curInstruction[6].u.structureID;
2602             StructureChain* chain = curInstruction[7].u.structureChain.get();
2603             if ((!oldStructureID || Heap::isMarked(m_vm->heap.structureIDTable().get(oldStructureID))) &&
2604                 (!newStructureID || Heap::isMarked(m_vm->heap.structureIDTable().get(newStructureID))) &&
2605                 (!chain || Heap::isMarked(chain)))
2606                 break;
2607             if (Options::verboseOSR())
2608                 dataLogF("Clearing LLInt put transition.\n");
2609             curInstruction[4].u.structureID = 0;
2610             curInstruction[5].u.operand = 0;
2611             curInstruction[6].u.structureID = 0;
2612             curInstruction[7].u.structureChain.clear();
2613             break;
2614         }
2615         case op_get_array_length:
2616             break;
2617         case op_to_this:
2618             if (!curInstruction[2].u.structure || Heap::isMarked(curInstruction[2].u.structure.get()))
2619                 break;
2620             if (Options::verboseOSR())
2621                 dataLogF("Clearing LLInt to_this with structure %p.\n", curInstruction[2].u.structure.get());
2622             curInstruction[2].u.structure.clear();
2623             curInstruction[3].u.toThisStatus = merge(
2624                 curInstruction[3].u.toThisStatus, ToThisClearedByGC);
2625             break;
2626         case op_create_this: {
2627             auto& cacheWriteBarrier = curInstruction[4].u.jsCell;
2628             if (!cacheWriteBarrier || cacheWriteBarrier.unvalidatedGet() == JSCell::seenMultipleCalleeObjects())
2629                 break;
2630             JSCell* cachedFunction = cacheWriteBarrier.get();
2631             if (Heap::isMarked(cachedFunction))
2632                 break;
2633             if (Options::verboseOSR())
2634                 dataLogF("Clearing LLInt create_this with cached callee %p.\n", cachedFunction);
2635             cacheWriteBarrier.clear();
2636             break;
2637         }
2638         case op_resolve_scope: {
2639             // Right now this isn't strictly necessary. Any symbol tables that this will refer to
2640             // are for outer functions, and we refer to those functions strongly, and they refer
2641             // to the symbol table strongly. But it's nice to be on the safe side.
2642             WriteBarrierBase<SymbolTable>& symbolTable = curInstruction[6].u.symbolTable;
2643             if (!symbolTable || Heap::isMarked(symbolTable.get()))
2644                 break;
2645             if (Options::verboseOSR())
2646                 dataLogF("Clearing dead symbolTable %p.\n", symbolTable.get());
2647             symbolTable.clear();
2648             break;
2649         }
2650         case op_get_from_scope:
2651         case op_put_to_scope: {
2652             GetPutInfo getPutInfo = GetPutInfo(curInstruction[4].u.operand);
2653             if (getPutInfo.resolveType() == GlobalVar || getPutInfo.resolveType() == GlobalVarWithVarInjectionChecks 
2654                 || getPutInfo.resolveType() == LocalClosureVar || getPutInfo.resolveType() == GlobalLexicalVar || getPutInfo.resolveType() == GlobalLexicalVarWithVarInjectionChecks)
2655                 continue;
2656             WriteBarrierBase<Structure>& structure = curInstruction[5].u.structure;
2657             if (!structure || Heap::isMarked(structure.get()))
2658                 break;
2659             if (Options::verboseOSR())
2660                 dataLogF("Clearing scope access with structure %p.\n", structure.get());
2661             structure.clear();
2662             break;
2663         }
2664         default:
2665             OpcodeID opcodeID = interpreter->getOpcodeID(curInstruction[0].u.opcode);
2666             ASSERT_WITH_MESSAGE_UNUSED(opcodeID, false, "Unhandled opcode in CodeBlock::finalizeUnconditionally, %s(%d) at bc %u", opcodeNames[opcodeID], opcodeID, propertyAccessInstructions[i]);
2667         }
2668     }
2669
2670     for (unsigned i = 0; i < m_llintCallLinkInfos.size(); ++i) {
2671         if (m_llintCallLinkInfos[i].isLinked() && !Heap::isMarked(m_llintCallLinkInfos[i].callee.get())) {
2672             if (Options::verboseOSR())
2673                 dataLog("Clearing LLInt call from ", *this, "\n");
2674             m_llintCallLinkInfos[i].unlink();
2675         }
2676         if (!!m_llintCallLinkInfos[i].lastSeenCallee && !Heap::isMarked(m_llintCallLinkInfos[i].lastSeenCallee.get()))
2677             m_llintCallLinkInfos[i].lastSeenCallee.clear();
2678     }
2679 }
2680
2681 void CodeBlock::finalizeBaselineJITInlineCaches()
2682 {
2683 #if ENABLE(JIT)
2684     for (auto iter = callLinkInfosBegin(); !!iter; ++iter)
2685         (*iter)->visitWeak(*vm());
2686
2687     for (Bag<StructureStubInfo>::iterator iter = m_stubInfos.begin(); !!iter; ++iter) {
2688         StructureStubInfo& stubInfo = **iter;
2689         stubInfo.visitWeakReferences(this);
2690     }
2691 #endif
2692 }
2693
2694 void CodeBlock::UnconditionalFinalizer::finalizeUnconditionally()
2695 {
2696     CodeBlock* codeBlock = bitwise_cast<CodeBlock*>(
2697         bitwise_cast<char*>(this) - OBJECT_OFFSETOF(CodeBlock, m_unconditionalFinalizer));
2698
2699 #if ENABLE(DFG_JIT)
2700     if (codeBlock->shouldJettisonDueToWeakReference()) {
2701         codeBlock->jettison(Profiler::JettisonDueToWeakReference);
2702         return;
2703     }
2704 #endif // ENABLE(DFG_JIT)
2705
2706     if (codeBlock->shouldJettisonDueToOldAge()) {
2707         codeBlock->jettison(Profiler::JettisonDueToOldAge);
2708         return;
2709     }
2710
2711     if (JITCode::couldBeInterpreted(codeBlock->jitType()))
2712         codeBlock->finalizeLLIntInlineCaches();
2713
2714 #if ENABLE(JIT)
2715     if (!!codeBlock->jitCode())
2716         codeBlock->finalizeBaselineJITInlineCaches();
2717 #endif
2718 }
2719
2720 void CodeBlock::getStubInfoMap(const ConcurrentJITLocker&, StubInfoMap& result)
2721 {
2722 #if ENABLE(JIT)
2723     toHashMap(m_stubInfos, getStructureStubInfoCodeOrigin, result);
2724 #else
2725     UNUSED_PARAM(result);
2726 #endif
2727 }
2728
2729 void CodeBlock::getStubInfoMap(StubInfoMap& result)
2730 {
2731     ConcurrentJITLocker locker(m_lock);
2732     getStubInfoMap(locker, result);
2733 }
2734
2735 void CodeBlock::getCallLinkInfoMap(const ConcurrentJITLocker&, CallLinkInfoMap& result)
2736 {
2737 #if ENABLE(JIT)
2738     toHashMap(m_callLinkInfos, getCallLinkInfoCodeOrigin, result);
2739 #else
2740     UNUSED_PARAM(result);
2741 #endif
2742 }
2743
2744 void CodeBlock::getCallLinkInfoMap(CallLinkInfoMap& result)
2745 {
2746     ConcurrentJITLocker locker(m_lock);
2747     getCallLinkInfoMap(locker, result);
2748 }
2749
2750 void CodeBlock::getByValInfoMap(const ConcurrentJITLocker&, ByValInfoMap& result)
2751 {
2752 #if ENABLE(JIT)
2753     for (auto* byValInfo : m_byValInfos)
2754         result.add(CodeOrigin(byValInfo->bytecodeIndex), byValInfo);
2755 #else
2756     UNUSED_PARAM(result);
2757 #endif
2758 }
2759
2760 void CodeBlock::getByValInfoMap(ByValInfoMap& result)
2761 {
2762     ConcurrentJITLocker locker(m_lock);
2763     getByValInfoMap(locker, result);
2764 }
2765
2766 #if ENABLE(JIT)
2767 StructureStubInfo* CodeBlock::addStubInfo(AccessType accessType)
2768 {
2769     ConcurrentJITLocker locker(m_lock);
2770     return m_stubInfos.add(accessType);
2771 }
2772
2773 StructureStubInfo* CodeBlock::findStubInfo(CodeOrigin codeOrigin)
2774 {
2775     for (StructureStubInfo* stubInfo : m_stubInfos) {
2776         if (stubInfo->codeOrigin == codeOrigin)
2777             return stubInfo;
2778     }
2779     return nullptr;
2780 }
2781
2782 ByValInfo* CodeBlock::addByValInfo()
2783 {
2784     ConcurrentJITLocker locker(m_lock);
2785     return m_byValInfos.add();
2786 }
2787
2788 CallLinkInfo* CodeBlock::addCallLinkInfo()
2789 {
2790     ConcurrentJITLocker locker(m_lock);
2791     return m_callLinkInfos.add();
2792 }
2793
2794 CallLinkInfo* CodeBlock::getCallLinkInfoForBytecodeIndex(unsigned index)
2795 {
2796     for (auto iter = m_callLinkInfos.begin(); !!iter; ++iter) {
2797         if ((*iter)->codeOrigin() == CodeOrigin(index))
2798             return *iter;
2799     }
2800     return nullptr;
2801 }
2802 #endif
2803
2804 void CodeBlock::visitOSRExitTargets(SlotVisitor& visitor)
2805 {
2806     // We strongly visit OSR exits targets because we don't want to deal with
2807     // the complexity of generating an exit target CodeBlock on demand and
2808     // guaranteeing that it matches the details of the CodeBlock we compiled
2809     // the OSR exit against.
2810
2811     visitor.append(&m_alternative);
2812
2813 #if ENABLE(DFG_JIT)
2814     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2815     if (dfgCommon->inlineCallFrames) {
2816         for (auto* inlineCallFrame : *dfgCommon->inlineCallFrames) {
2817             ASSERT(inlineCallFrame->baselineCodeBlock);
2818             visitor.append(&inlineCallFrame->baselineCodeBlock);
2819         }
2820     }
2821 #endif
2822 }
2823
2824 void CodeBlock::stronglyVisitStrongReferences(SlotVisitor& visitor)
2825 {
2826     visitor.append(&m_globalObject);
2827     visitor.append(&m_ownerExecutable);
2828     visitor.append(&m_unlinkedCode);
2829     if (m_rareData)
2830         m_rareData->m_evalCodeCache.visitAggregate(visitor);
2831     visitor.appendValues(m_constantRegisters.data(), m_constantRegisters.size());
2832     for (size_t i = 0; i < m_functionExprs.size(); ++i)
2833         visitor.append(&m_functionExprs[i]);
2834     for (size_t i = 0; i < m_functionDecls.size(); ++i)
2835         visitor.append(&m_functionDecls[i]);
2836     for (unsigned i = 0; i < m_objectAllocationProfiles.size(); ++i)
2837         m_objectAllocationProfiles[i].visitAggregate(visitor);
2838
2839 #if ENABLE(DFG_JIT)
2840     if (JITCode::isOptimizingJIT(jitType()))
2841         visitOSRExitTargets(visitor);
2842 #endif
2843
2844     updateAllPredictions();
2845 }
2846
2847 void CodeBlock::stronglyVisitWeakReferences(SlotVisitor& visitor)
2848 {
2849     UNUSED_PARAM(visitor);
2850
2851 #if ENABLE(DFG_JIT)
2852     if (!JITCode::isOptimizingJIT(jitType()))
2853         return;
2854     
2855     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2856
2857     for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
2858         if (!!dfgCommon->transitions[i].m_codeOrigin)
2859             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.
2860         visitor.append(&dfgCommon->transitions[i].m_from);
2861         visitor.append(&dfgCommon->transitions[i].m_to);
2862     }
2863     
2864     for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i)
2865         visitor.append(&dfgCommon->weakReferences[i]);
2866
2867     for (unsigned i = 0; i < dfgCommon->weakStructureReferences.size(); ++i)
2868         visitor.append(&dfgCommon->weakStructureReferences[i]);
2869
2870     dfgCommon->livenessHasBeenProved = true;
2871 #endif    
2872 }
2873
2874 CodeBlock* CodeBlock::baselineAlternative()
2875 {
2876 #if ENABLE(JIT)
2877     CodeBlock* result = this;
2878     while (result->alternative())
2879         result = result->alternative();
2880     RELEASE_ASSERT(result);
2881     RELEASE_ASSERT(JITCode::isBaselineCode(result->jitType()) || result->jitType() == JITCode::None);
2882     return result;
2883 #else
2884     return this;
2885 #endif
2886 }
2887
2888 CodeBlock* CodeBlock::baselineVersion()
2889 {
2890 #if ENABLE(JIT)
2891     if (JITCode::isBaselineCode(jitType()))
2892         return this;
2893     CodeBlock* result = replacement();
2894     if (!result) {
2895         // This can happen if we're creating the original CodeBlock for an executable.
2896         // Assume that we're the baseline CodeBlock.
2897         RELEASE_ASSERT(jitType() == JITCode::None);
2898         return this;
2899     }
2900     result = result->baselineAlternative();
2901     return result;
2902 #else
2903     return this;
2904 #endif
2905 }
2906
2907 #if ENABLE(JIT)
2908 bool CodeBlock::hasOptimizedReplacement(JITCode::JITType typeToReplace)
2909 {
2910     return JITCode::isHigherTier(replacement()->jitType(), typeToReplace);
2911 }
2912
2913 bool CodeBlock::hasOptimizedReplacement()
2914 {
2915     return hasOptimizedReplacement(jitType());
2916 }
2917 #endif
2918
2919 HandlerInfo* CodeBlock::handlerForBytecodeOffset(unsigned bytecodeOffset, RequiredHandler requiredHandler)
2920 {
2921     RELEASE_ASSERT(bytecodeOffset < instructions().size());
2922     return handlerForIndex(bytecodeOffset, requiredHandler);
2923 }
2924
2925 HandlerInfo* CodeBlock::handlerForIndex(unsigned index, RequiredHandler requiredHandler)
2926 {
2927     if (!m_rareData)
2928         return 0;
2929     
2930     Vector<HandlerInfo>& exceptionHandlers = m_rareData->m_exceptionHandlers;
2931     for (size_t i = 0; i < exceptionHandlers.size(); ++i) {
2932         HandlerInfo& handler = exceptionHandlers[i];
2933         if ((requiredHandler == RequiredHandler::CatchHandler) && !handler.isCatchHandler())
2934             continue;
2935
2936         // Handlers are ordered innermost first, so the first handler we encounter
2937         // that contains the source address is the correct handler to use.
2938         // This index used is either the BytecodeOffset or a CallSiteIndex.
2939         if (handler.start <= index && handler.end > index)
2940             return &handler;
2941     }
2942
2943     return 0;
2944 }
2945
2946 CallSiteIndex CodeBlock::newExceptionHandlingCallSiteIndex(CallSiteIndex originalCallSite)
2947 {
2948 #if ENABLE(DFG_JIT)
2949     RELEASE_ASSERT(jitType() == JITCode::DFGJIT); // FIXME: When implementing FTL try/catch we should include that JITType here as well: https://bugs.webkit.org/show_bug.cgi?id=149409
2950     RELEASE_ASSERT(canGetCodeOrigin(originalCallSite));
2951     ASSERT(!!handlerForIndex(originalCallSite.bits()));
2952     CodeOrigin originalOrigin = codeOrigin(originalCallSite);
2953     return m_jitCode->dfgCommon()->addUniqueCallSiteIndex(originalOrigin);
2954 #else
2955     // We never create new on-the-fly exception handling
2956     // call sites outside the DFG/FTL inline caches.
2957     UNUSED_PARAM(originalCallSite);
2958     RELEASE_ASSERT_NOT_REACHED();
2959     return CallSiteIndex(0u);
2960 #endif
2961 }
2962
2963 void CodeBlock::removeExceptionHandlerForCallSite(CallSiteIndex callSiteIndex)
2964 {
2965     RELEASE_ASSERT(m_rareData);
2966     Vector<HandlerInfo>& exceptionHandlers = m_rareData->m_exceptionHandlers;
2967     unsigned index = callSiteIndex.bits();
2968     for (size_t i = 0; i < exceptionHandlers.size(); ++i) {
2969         HandlerInfo& handler = exceptionHandlers[i];
2970         if (handler.start <= index && handler.end > index) {
2971             exceptionHandlers.remove(i);
2972             return;
2973         }
2974     }
2975
2976     RELEASE_ASSERT_NOT_REACHED();
2977 }
2978
2979 unsigned CodeBlock::lineNumberForBytecodeOffset(unsigned bytecodeOffset)
2980 {
2981     RELEASE_ASSERT(bytecodeOffset < instructions().size());
2982     return ownerScriptExecutable()->firstLine() + m_unlinkedCode->lineNumberForBytecodeOffset(bytecodeOffset);
2983 }
2984
2985 unsigned CodeBlock::columnNumberForBytecodeOffset(unsigned bytecodeOffset)
2986 {
2987     int divot;
2988     int startOffset;
2989     int endOffset;
2990     unsigned line;
2991     unsigned column;
2992     expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
2993     return column;
2994 }
2995
2996 void CodeBlock::expressionRangeForBytecodeOffset(unsigned bytecodeOffset, int& divot, int& startOffset, int& endOffset, unsigned& line, unsigned& column)
2997 {
2998     m_unlinkedCode->expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
2999     divot += m_sourceOffset;
3000     column += line ? 1 : firstLineColumnOffset();
3001     line += ownerScriptExecutable()->firstLine();
3002 }
3003
3004 bool CodeBlock::hasOpDebugForLineAndColumn(unsigned line, unsigned column)
3005 {
3006     Interpreter* interpreter = vm()->interpreter;
3007     const Instruction* begin = instructions().begin();
3008     const Instruction* end = instructions().end();
3009     for (const Instruction* it = begin; it != end;) {
3010         OpcodeID opcodeID = interpreter->getOpcodeID(it->u.opcode);
3011         if (opcodeID == op_debug) {
3012             unsigned bytecodeOffset = it - begin;
3013             int unused;
3014             unsigned opDebugLine;
3015             unsigned opDebugColumn;
3016             expressionRangeForBytecodeOffset(bytecodeOffset, unused, unused, unused, opDebugLine, opDebugColumn);
3017             if (line == opDebugLine && (column == Breakpoint::unspecifiedColumn || column == opDebugColumn))
3018                 return true;
3019         }
3020         it += opcodeLengths[opcodeID];
3021     }
3022     return false;
3023 }
3024
3025 void CodeBlock::shrinkToFit(ShrinkMode shrinkMode)
3026 {
3027     m_rareCaseProfiles.shrinkToFit();
3028     m_specialFastCaseProfiles.shrinkToFit();
3029     
3030     if (shrinkMode == EarlyShrink) {
3031         m_constantRegisters.shrinkToFit();
3032         m_constantsSourceCodeRepresentation.shrinkToFit();
3033         
3034         if (m_rareData) {
3035             m_rareData->m_switchJumpTables.shrinkToFit();
3036             m_rareData->m_stringSwitchJumpTables.shrinkToFit();
3037         }
3038     } // else don't shrink these, because we would have already pointed pointers into these tables.
3039 }
3040
3041 #if ENABLE(JIT)
3042 void CodeBlock::linkIncomingCall(ExecState* callerFrame, CallLinkInfo* incoming)
3043 {
3044     noticeIncomingCall(callerFrame);
3045     m_incomingCalls.push(incoming);
3046 }
3047
3048 void CodeBlock::linkIncomingPolymorphicCall(ExecState* callerFrame, PolymorphicCallNode* incoming)
3049 {
3050     noticeIncomingCall(callerFrame);
3051     m_incomingPolymorphicCalls.push(incoming);
3052 }
3053 #endif // ENABLE(JIT)
3054
3055 void CodeBlock::unlinkIncomingCalls()
3056 {
3057     while (m_incomingLLIntCalls.begin() != m_incomingLLIntCalls.end())
3058         m_incomingLLIntCalls.begin()->unlink();
3059 #if ENABLE(JIT)
3060     while (m_incomingCalls.begin() != m_incomingCalls.end())
3061         m_incomingCalls.begin()->unlink(*vm());
3062     while (m_incomingPolymorphicCalls.begin() != m_incomingPolymorphicCalls.end())
3063         m_incomingPolymorphicCalls.begin()->unlink(*vm());
3064 #endif // ENABLE(JIT)
3065 }
3066
3067 void CodeBlock::linkIncomingCall(ExecState* callerFrame, LLIntCallLinkInfo* incoming)
3068 {
3069     noticeIncomingCall(callerFrame);
3070     m_incomingLLIntCalls.push(incoming);
3071 }
3072
3073 CodeBlock* CodeBlock::newReplacement()
3074 {
3075     return ownerScriptExecutable()->newReplacementCodeBlockFor(specializationKind());
3076 }
3077
3078 #if ENABLE(JIT)
3079 CodeBlock* CodeBlock::replacement()
3080 {
3081     const ClassInfo* classInfo = this->classInfo();
3082
3083     if (classInfo == FunctionCodeBlock::info())
3084         return jsCast<FunctionExecutable*>(ownerExecutable())->codeBlockFor(m_isConstructor ? CodeForConstruct : CodeForCall);
3085
3086     if (classInfo == EvalCodeBlock::info())
3087         return jsCast<EvalExecutable*>(ownerExecutable())->codeBlock();
3088
3089     if (classInfo == ProgramCodeBlock::info())
3090         return jsCast<ProgramExecutable*>(ownerExecutable())->codeBlock();
3091
3092     if (classInfo == ModuleProgramCodeBlock::info())
3093         return jsCast<ModuleProgramExecutable*>(ownerExecutable())->codeBlock();
3094
3095 #if ENABLE(WEBASSEMBLY)
3096     if (classInfo == WebAssemblyCodeBlock::info())
3097         return nullptr;
3098 #endif
3099
3100     RELEASE_ASSERT_NOT_REACHED();
3101     return nullptr;
3102 }
3103
3104 DFG::CapabilityLevel CodeBlock::computeCapabilityLevel()
3105 {
3106     const ClassInfo* classInfo = this->classInfo();
3107
3108     if (classInfo == FunctionCodeBlock::info()) {
3109         if (m_isConstructor)
3110             return DFG::functionForConstructCapabilityLevel(this);
3111         return DFG::functionForCallCapabilityLevel(this);
3112     }
3113
3114     if (classInfo == EvalCodeBlock::info())
3115         return DFG::evalCapabilityLevel(this);
3116
3117     if (classInfo == ProgramCodeBlock::info())
3118         return DFG::programCapabilityLevel(this);
3119
3120     if (classInfo == ModuleProgramCodeBlock::info())
3121         return DFG::programCapabilityLevel(this);
3122
3123 #if ENABLE(WEBASSEMBLY)
3124     if (classInfo == WebAssemblyCodeBlock::info())
3125         return DFG::CannotCompile;
3126 #endif
3127
3128     RELEASE_ASSERT_NOT_REACHED();
3129     return DFG::CannotCompile;
3130 }
3131
3132 #endif // ENABLE(JIT)
3133
3134 void CodeBlock::jettison(Profiler::JettisonReason reason, ReoptimizationMode mode, const FireDetail* detail)
3135 {
3136 #if !ENABLE(DFG_JIT)
3137     UNUSED_PARAM(mode);
3138     UNUSED_PARAM(detail);
3139 #endif
3140
3141     RELEASE_ASSERT(reason != Profiler::NotJettisoned);
3142     
3143 #if ENABLE(DFG_JIT)
3144     if (DFG::shouldDumpDisassembly()) {
3145         dataLog("Jettisoning ", *this);
3146         if (mode == CountReoptimization)
3147             dataLog(" and counting reoptimization");
3148         dataLog(" due to ", reason);
3149         if (detail)
3150             dataLog(", ", *detail);
3151         dataLog(".\n");
3152     }
3153     
3154     if (reason == Profiler::JettisonDueToWeakReference) {
3155         if (DFG::shouldDumpDisassembly()) {
3156             dataLog(*this, " will be jettisoned because of the following dead references:\n");
3157             DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
3158             for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
3159                 DFG::WeakReferenceTransition& transition = dfgCommon->transitions[i];
3160                 JSCell* origin = transition.m_codeOrigin.get();
3161                 JSCell* from = transition.m_from.get();
3162                 JSCell* to = transition.m_to.get();
3163                 if ((!origin || Heap::isMarked(origin)) && Heap::isMarked(from))
3164                     continue;
3165                 dataLog("    Transition under ", RawPointer(origin), ", ", RawPointer(from), " -> ", RawPointer(to), ".\n");
3166             }
3167             for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
3168                 JSCell* weak = dfgCommon->weakReferences[i].get();
3169                 if (Heap::isMarked(weak))
3170                     continue;
3171                 dataLog("    Weak reference ", RawPointer(weak), ".\n");
3172             }
3173         }
3174     }
3175 #endif // ENABLE(DFG_JIT)
3176
3177     DeferGCForAWhile deferGC(*m_heap);
3178     
3179     // We want to accomplish two things here:
3180     // 1) Make sure that if this CodeBlock is on the stack right now, then if we return to it
3181     //    we should OSR exit at the top of the next bytecode instruction after the return.
3182     // 2) Make sure that if we call the owner executable, then we shouldn't call this CodeBlock.
3183
3184 #if ENABLE(DFG_JIT)
3185     if (reason != Profiler::JettisonDueToOldAge) {
3186         if (Profiler::Compilation* compilation = jitCode()->dfgCommon()->compilation.get())
3187             compilation->setJettisonReason(reason, detail);
3188         
3189         // This accomplishes (1), and does its own book-keeping about whether it has already happened.
3190         if (!jitCode()->dfgCommon()->invalidate()) {
3191             // We've already been invalidated.
3192             RELEASE_ASSERT(this != replacement());
3193             return;
3194         }
3195     }
3196     
3197     if (DFG::shouldDumpDisassembly())
3198         dataLog("    Did invalidate ", *this, "\n");
3199     
3200     // Count the reoptimization if that's what the user wanted.
3201     if (mode == CountReoptimization) {
3202         // FIXME: Maybe this should call alternative().
3203         // https://bugs.webkit.org/show_bug.cgi?id=123677
3204         baselineAlternative()->countReoptimization();
3205         if (DFG::shouldDumpDisassembly())
3206             dataLog("    Did count reoptimization for ", *this, "\n");
3207     }
3208     
3209     if (this != replacement()) {
3210         // This means that we were never the entrypoint. This can happen for OSR entry code
3211         // blocks.
3212         return;
3213     }
3214
3215     if (alternative())
3216         alternative()->optimizeAfterWarmUp();
3217
3218     if (reason != Profiler::JettisonDueToOldAge)
3219         tallyFrequentExitSites();
3220 #endif // ENABLE(DFG_JIT)
3221
3222     // This accomplishes (2).
3223     ownerScriptExecutable()->installCode(
3224         m_globalObject->vm(), alternative(), codeType(), specializationKind());
3225
3226 #if ENABLE(DFG_JIT)
3227     if (DFG::shouldDumpDisassembly())
3228         dataLog("    Did install baseline version of ", *this, "\n");
3229 #endif // ENABLE(DFG_JIT)
3230 }
3231
3232 JSGlobalObject* CodeBlock::globalObjectFor(CodeOrigin codeOrigin)
3233 {
3234     if (!codeOrigin.inlineCallFrame)
3235         return globalObject();
3236     return codeOrigin.inlineCallFrame->baselineCodeBlock->globalObject();
3237 }
3238
3239 class RecursionCheckFunctor {
3240 public:
3241     RecursionCheckFunctor(CallFrame* startCallFrame, CodeBlock* codeBlock, unsigned depthToCheck)
3242         : m_startCallFrame(startCallFrame)
3243         , m_codeBlock(