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