ac402e8fad176837ad2c26167e8257c465022a3f
[WebKit-https.git] / Source / JavaScriptCore / bytecode / CodeBlock.cpp
1 /*
2  * Copyright (C) 2008-2010, 2012-2016 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_cloned_arguments: {
803             int r0 = (++it)->u.operand;
804             printLocationAndOp(out, exec, location, it, "create_cloned_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_log_shadow_chicken_prologue: {
1311             printLocationAndOp(out, exec, location, it, "log_shadow_chicken_prologue");
1312             break;
1313         }
1314         case op_log_shadow_chicken_tail: {
1315             printLocationAndOp(out, exec, location, it, "log_shadow_chicken_tail");
1316             break;
1317         }
1318         case op_switch_imm: {
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_imm");
1323             out.printf("%d, %d(->%d), %s", tableIndex, defaultTarget, location + defaultTarget, registerName(scrutineeRegister).data());
1324             break;
1325         }
1326         case op_switch_char: {
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_char");
1331             out.printf("%d, %d(->%d), %s", tableIndex, defaultTarget, location + defaultTarget, registerName(scrutineeRegister).data());
1332             break;
1333         }
1334         case op_switch_string: {
1335             int tableIndex = (++it)->u.operand;
1336             int defaultTarget = (++it)->u.operand;
1337             int scrutineeRegister = (++it)->u.operand;
1338             printLocationAndOp(out, exec, location, it, "switch_string");
1339             out.printf("%d, %d(->%d), %s", tableIndex, defaultTarget, location + defaultTarget, registerName(scrutineeRegister).data());
1340             break;
1341         }
1342         case op_new_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_func");
1347             out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1348             break;
1349         }
1350         case op_new_generator_func: {
1351             int r0 = (++it)->u.operand;
1352             int r1 = (++it)->u.operand;
1353             int f0 = (++it)->u.operand;
1354             printLocationAndOp(out, exec, location, it, "new_generator_func");
1355             out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1356             break;
1357         }
1358         case op_new_arrow_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, "op_new_arrow_func_exp");
1363             out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1364             break;
1365         }
1366         case op_new_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_func_exp");
1371             out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1372             break;
1373         }
1374         case op_new_generator_func_exp: {
1375             int r0 = (++it)->u.operand;
1376             int r1 = (++it)->u.operand;
1377             int f0 = (++it)->u.operand;
1378             printLocationAndOp(out, exec, location, it, "new_generator_func_exp");
1379             out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1380             break;
1381         }
1382         case op_set_function_name: {
1383             int funcReg = (++it)->u.operand;
1384             int nameReg = (++it)->u.operand;
1385             printLocationAndOp(out, exec, location, it, "set_function_name");
1386             out.printf("%s, %s", registerName(funcReg).data(), registerName(nameReg).data());
1387             break;
1388         }
1389         case op_call: {
1390             printCallOp(out, exec, location, it, "call", DumpCaches, hasPrintedProfiling, callLinkInfos);
1391             break;
1392         }
1393         case op_tail_call: {
1394             printCallOp(out, exec, location, it, "tail_call", DumpCaches, hasPrintedProfiling, callLinkInfos);
1395             break;
1396         }
1397         case op_call_eval: {
1398             printCallOp(out, exec, location, it, "call_eval", DontDumpCaches, hasPrintedProfiling, callLinkInfos);
1399             break;
1400         }
1401             
1402         case op_construct_varargs:
1403         case op_call_varargs:
1404         case op_tail_call_varargs: {
1405             int result = (++it)->u.operand;
1406             int callee = (++it)->u.operand;
1407             int thisValue = (++it)->u.operand;
1408             int arguments = (++it)->u.operand;
1409             int firstFreeRegister = (++it)->u.operand;
1410             int varArgOffset = (++it)->u.operand;
1411             ++it;
1412             printLocationAndOp(out, exec, location, it, opcode == op_call_varargs ? "call_varargs" : opcode == op_construct_varargs ? "construct_varargs" : "tail_call_varargs");
1413             out.printf("%s, %s, %s, %s, %d, %d", registerName(result).data(), registerName(callee).data(), registerName(thisValue).data(), registerName(arguments).data(), firstFreeRegister, varArgOffset);
1414             dumpValueProfiling(out, it, hasPrintedProfiling);
1415             break;
1416         }
1417
1418         case op_ret: {
1419             int r0 = (++it)->u.operand;
1420             printLocationOpAndRegisterOperand(out, exec, location, it, "ret", r0);
1421             break;
1422         }
1423         case op_construct: {
1424             printCallOp(out, exec, location, it, "construct", DumpCaches, hasPrintedProfiling, callLinkInfos);
1425             break;
1426         }
1427         case op_strcat: {
1428             int r0 = (++it)->u.operand;
1429             int r1 = (++it)->u.operand;
1430             int count = (++it)->u.operand;
1431             printLocationAndOp(out, exec, location, it, "strcat");
1432             out.printf("%s, %s, %d", registerName(r0).data(), registerName(r1).data(), count);
1433             break;
1434         }
1435         case op_to_primitive: {
1436             int r0 = (++it)->u.operand;
1437             int r1 = (++it)->u.operand;
1438             printLocationAndOp(out, exec, location, it, "to_primitive");
1439             out.printf("%s, %s", registerName(r0).data(), registerName(r1).data());
1440             break;
1441         }
1442         case op_get_enumerable_length: {
1443             int dst = it[1].u.operand;
1444             int base = it[2].u.operand;
1445             printLocationAndOp(out, exec, location, it, "op_get_enumerable_length");
1446             out.printf("%s, %s", registerName(dst).data(), registerName(base).data());
1447             it += OPCODE_LENGTH(op_get_enumerable_length) - 1;
1448             break;
1449         }
1450         case op_has_indexed_property: {
1451             int dst = it[1].u.operand;
1452             int base = it[2].u.operand;
1453             int propertyName = it[3].u.operand;
1454             ArrayProfile* arrayProfile = it[4].u.arrayProfile;
1455             printLocationAndOp(out, exec, location, it, "op_has_indexed_property");
1456             out.printf("%s, %s, %s, %p", registerName(dst).data(), registerName(base).data(), registerName(propertyName).data(), arrayProfile);
1457             it += OPCODE_LENGTH(op_has_indexed_property) - 1;
1458             break;
1459         }
1460         case op_has_structure_property: {
1461             int dst = it[1].u.operand;
1462             int base = it[2].u.operand;
1463             int propertyName = it[3].u.operand;
1464             int enumerator = it[4].u.operand;
1465             printLocationAndOp(out, exec, location, it, "op_has_structure_property");
1466             out.printf("%s, %s, %s, %s", registerName(dst).data(), registerName(base).data(), registerName(propertyName).data(), registerName(enumerator).data());
1467             it += OPCODE_LENGTH(op_has_structure_property) - 1;
1468             break;
1469         }
1470         case op_has_generic_property: {
1471             int dst = it[1].u.operand;
1472             int base = it[2].u.operand;
1473             int propertyName = it[3].u.operand;
1474             printLocationAndOp(out, exec, location, it, "op_has_generic_property");
1475             out.printf("%s, %s, %s", registerName(dst).data(), registerName(base).data(), registerName(propertyName).data());
1476             it += OPCODE_LENGTH(op_has_generic_property) - 1;
1477             break;
1478         }
1479         case op_get_direct_pname: {
1480             int dst = it[1].u.operand;
1481             int base = it[2].u.operand;
1482             int propertyName = it[3].u.operand;
1483             int index = it[4].u.operand;
1484             int enumerator = it[5].u.operand;
1485             ValueProfile* profile = it[6].u.profile;
1486             printLocationAndOp(out, exec, location, it, "op_get_direct_pname");
1487             out.printf("%s, %s, %s, %s, %s, %p", registerName(dst).data(), registerName(base).data(), registerName(propertyName).data(), registerName(index).data(), registerName(enumerator).data(), profile);
1488             it += OPCODE_LENGTH(op_get_direct_pname) - 1;
1489             break;
1490
1491         }
1492         case op_get_property_enumerator: {
1493             int dst = it[1].u.operand;
1494             int base = it[2].u.operand;
1495             printLocationAndOp(out, exec, location, it, "op_get_property_enumerator");
1496             out.printf("%s, %s", registerName(dst).data(), registerName(base).data());
1497             it += OPCODE_LENGTH(op_get_property_enumerator) - 1;
1498             break;
1499         }
1500         case op_enumerator_structure_pname: {
1501             int dst = it[1].u.operand;
1502             int enumerator = it[2].u.operand;
1503             int index = it[3].u.operand;
1504             printLocationAndOp(out, exec, location, it, "op_enumerator_structure_pname");
1505             out.printf("%s, %s, %s", registerName(dst).data(), registerName(enumerator).data(), registerName(index).data());
1506             it += OPCODE_LENGTH(op_enumerator_structure_pname) - 1;
1507             break;
1508         }
1509         case op_enumerator_generic_pname: {
1510             int dst = it[1].u.operand;
1511             int enumerator = it[2].u.operand;
1512             int index = it[3].u.operand;
1513             printLocationAndOp(out, exec, location, it, "op_enumerator_generic_pname");
1514             out.printf("%s, %s, %s", registerName(dst).data(), registerName(enumerator).data(), registerName(index).data());
1515             it += OPCODE_LENGTH(op_enumerator_generic_pname) - 1;
1516             break;
1517         }
1518         case op_to_index_string: {
1519             int dst = it[1].u.operand;
1520             int index = it[2].u.operand;
1521             printLocationAndOp(out, exec, location, it, "op_to_index_string");
1522             out.printf("%s, %s", registerName(dst).data(), registerName(index).data());
1523             it += OPCODE_LENGTH(op_to_index_string) - 1;
1524             break;
1525         }
1526         case op_push_with_scope: {
1527             int dst = (++it)->u.operand;
1528             int newScope = (++it)->u.operand;
1529             int currentScope = (++it)->u.operand;
1530             printLocationAndOp(out, exec, location, it, "push_with_scope");
1531             out.printf("%s, %s, %s", registerName(dst).data(), registerName(newScope).data(), registerName(currentScope).data());
1532             break;
1533         }
1534         case op_get_parent_scope: {
1535             int dst = (++it)->u.operand;
1536             int parentScope = (++it)->u.operand;
1537             printLocationAndOp(out, exec, location, it, "get_parent_scope");
1538             out.printf("%s, %s", registerName(dst).data(), registerName(parentScope).data());
1539             break;
1540         }
1541         case op_create_lexical_environment: {
1542             int dst = (++it)->u.operand;
1543             int scope = (++it)->u.operand;
1544             int symbolTable = (++it)->u.operand;
1545             int initialValue = (++it)->u.operand;
1546             printLocationAndOp(out, exec, location, it, "create_lexical_environment");
1547             out.printf("%s, %s, %s, %s", 
1548                 registerName(dst).data(), registerName(scope).data(), registerName(symbolTable).data(), registerName(initialValue).data());
1549             break;
1550         }
1551         case op_catch: {
1552             int r0 = (++it)->u.operand;
1553             int r1 = (++it)->u.operand;
1554             printLocationAndOp(out, exec, location, it, "catch");
1555             out.printf("%s, %s", registerName(r0).data(), registerName(r1).data());
1556             break;
1557         }
1558         case op_throw: {
1559             int r0 = (++it)->u.operand;
1560             printLocationOpAndRegisterOperand(out, exec, location, it, "throw", r0);
1561             break;
1562         }
1563         case op_throw_static_error: {
1564             int k0 = (++it)->u.operand;
1565             int k1 = (++it)->u.operand;
1566             printLocationAndOp(out, exec, location, it, "throw_static_error");
1567             out.printf("%s, %s", constantName(k0).data(), k1 ? "true" : "false");
1568             break;
1569         }
1570         case op_debug: {
1571             int debugHookID = (++it)->u.operand;
1572             int hasBreakpointFlag = (++it)->u.operand;
1573             printLocationAndOp(out, exec, location, it, "debug");
1574             out.printf("%s, %d", debugHookName(debugHookID), hasBreakpointFlag);
1575             break;
1576         }
1577         case op_save: {
1578             int generator = (++it)->u.operand;
1579             unsigned liveCalleeLocalsIndex = (++it)->u.unsignedValue;
1580             int offset = (++it)->u.operand;
1581             const FastBitVector& liveness = m_rareData->m_liveCalleeLocalsAtYield[liveCalleeLocalsIndex];
1582             printLocationAndOp(out, exec, location, it, "save");
1583             out.printf("%s, ", registerName(generator).data());
1584             liveness.dump(out);
1585             out.printf("(@live%1u), %d(->%d)", liveCalleeLocalsIndex, offset, location + offset);
1586             break;
1587         }
1588         case op_resume: {
1589             int generator = (++it)->u.operand;
1590             unsigned liveCalleeLocalsIndex = (++it)->u.unsignedValue;
1591             const FastBitVector& liveness = m_rareData->m_liveCalleeLocalsAtYield[liveCalleeLocalsIndex];
1592             printLocationAndOp(out, exec, location, it, "resume");
1593             out.printf("%s, ", registerName(generator).data());
1594             liveness.dump(out);
1595             out.printf("(@live%1u)", liveCalleeLocalsIndex);
1596             break;
1597         }
1598         case op_assert: {
1599             int condition = (++it)->u.operand;
1600             int line = (++it)->u.operand;
1601             printLocationAndOp(out, exec, location, it, "assert");
1602             out.printf("%s, %d", registerName(condition).data(), line);
1603             break;
1604         }
1605         case op_profile_will_call: {
1606             int function = (++it)->u.operand;
1607             printLocationOpAndRegisterOperand(out, exec, location, it, "profile_will_call", function);
1608             break;
1609         }
1610         case op_profile_did_call: {
1611             int function = (++it)->u.operand;
1612             printLocationOpAndRegisterOperand(out, exec, location, it, "profile_did_call", function);
1613             break;
1614         }
1615         case op_end: {
1616             int r0 = (++it)->u.operand;
1617             printLocationOpAndRegisterOperand(out, exec, location, it, "end", r0);
1618             break;
1619         }
1620         case op_resolve_scope: {
1621             int r0 = (++it)->u.operand;
1622             int scope = (++it)->u.operand;
1623             int id0 = (++it)->u.operand;
1624             ResolveType resolveType = static_cast<ResolveType>((++it)->u.operand);
1625             int depth = (++it)->u.operand;
1626             void* pointer = (++it)->u.pointer;
1627             printLocationAndOp(out, exec, location, it, "resolve_scope");
1628             out.printf("%s, %s, %s, <%s>, %d, %p", registerName(r0).data(), registerName(scope).data(), idName(id0, identifier(id0)).data(), resolveTypeName(resolveType), depth, pointer);
1629             break;
1630         }
1631         case op_get_from_scope: {
1632             int r0 = (++it)->u.operand;
1633             int r1 = (++it)->u.operand;
1634             int id0 = (++it)->u.operand;
1635             GetPutInfo getPutInfo = GetPutInfo((++it)->u.operand);
1636             ++it; // Structure
1637             int operand = (++it)->u.operand; // Operand
1638             printLocationAndOp(out, exec, location, it, "get_from_scope");
1639             out.print(registerName(r0), ", ", registerName(r1));
1640             if (static_cast<unsigned>(id0) == UINT_MAX)
1641                 out.print(", anonymous");
1642             else
1643                 out.print(", ", idName(id0, identifier(id0)));
1644             out.print(", ", getPutInfo.operand(), "<", resolveModeName(getPutInfo.resolveMode()), "|", resolveTypeName(getPutInfo.resolveType()), "|", initializationModeName(getPutInfo.initializationMode()), ">, ", operand);
1645             dumpValueProfiling(out, it, hasPrintedProfiling);
1646             break;
1647         }
1648         case op_put_to_scope: {
1649             int r0 = (++it)->u.operand;
1650             int id0 = (++it)->u.operand;
1651             int r1 = (++it)->u.operand;
1652             GetPutInfo getPutInfo = GetPutInfo((++it)->u.operand);
1653             ++it; // Structure
1654             int operand = (++it)->u.operand; // Operand
1655             printLocationAndOp(out, exec, location, it, "put_to_scope");
1656             out.print(registerName(r0));
1657             if (static_cast<unsigned>(id0) == UINT_MAX)
1658                 out.print(", anonymous");
1659             else
1660                 out.print(", ", idName(id0, identifier(id0)));
1661             out.print(", ", registerName(r1), ", ", getPutInfo.operand(), "<", resolveModeName(getPutInfo.resolveMode()), "|", resolveTypeName(getPutInfo.resolveType()), "|", initializationModeName(getPutInfo.initializationMode()), ">, <structure>, ", operand);
1662             break;
1663         }
1664         case op_get_from_arguments: {
1665             int r0 = (++it)->u.operand;
1666             int r1 = (++it)->u.operand;
1667             int offset = (++it)->u.operand;
1668             printLocationAndOp(out, exec, location, it, "get_from_arguments");
1669             out.printf("%s, %s, %d", registerName(r0).data(), registerName(r1).data(), offset);
1670             dumpValueProfiling(out, it, hasPrintedProfiling);
1671             break;
1672         }
1673         case op_put_to_arguments: {
1674             int r0 = (++it)->u.operand;
1675             int offset = (++it)->u.operand;
1676             int r1 = (++it)->u.operand;
1677             printLocationAndOp(out, exec, location, it, "put_to_arguments");
1678             out.printf("%s, %d, %s", registerName(r0).data(), offset, registerName(r1).data());
1679             break;
1680         }
1681         default:
1682             RELEASE_ASSERT_NOT_REACHED();
1683     }
1684
1685     dumpRareCaseProfile(out, "rare case: ", rareCaseProfileForBytecodeOffset(location), hasPrintedProfiling);
1686     dumpResultProfile(out, resultProfileForBytecodeOffset(location), hasPrintedProfiling);
1687     
1688 #if ENABLE(DFG_JIT)
1689     Vector<DFG::FrequentExitSite> exitSites = exitProfile().exitSitesFor(location);
1690     if (!exitSites.isEmpty()) {
1691         out.print(" !! frequent exits: ");
1692         CommaPrinter comma;
1693         for (unsigned i = 0; i < exitSites.size(); ++i)
1694             out.print(comma, exitSites[i].kind(), " ", exitSites[i].jitType());
1695     }
1696 #else // ENABLE(DFG_JIT)
1697     UNUSED_PARAM(location);
1698 #endif // ENABLE(DFG_JIT)
1699     out.print("\n");
1700 }
1701
1702 void CodeBlock::dumpBytecode(
1703     PrintStream& out, unsigned bytecodeOffset,
1704     const StubInfoMap& stubInfos, const CallLinkInfoMap& callLinkInfos)
1705 {
1706     ExecState* exec = m_globalObject->globalExec();
1707     const Instruction* it = instructions().begin() + bytecodeOffset;
1708     dumpBytecode(out, exec, instructions().begin(), it, stubInfos, callLinkInfos);
1709 }
1710
1711 #define FOR_EACH_MEMBER_VECTOR(macro) \
1712     macro(instructions) \
1713     macro(callLinkInfos) \
1714     macro(linkedCallerList) \
1715     macro(identifiers) \
1716     macro(functionExpressions) \
1717     macro(constantRegisters)
1718
1719 #define FOR_EACH_MEMBER_VECTOR_RARE_DATA(macro) \
1720     macro(regexps) \
1721     macro(functions) \
1722     macro(exceptionHandlers) \
1723     macro(switchJumpTables) \
1724     macro(stringSwitchJumpTables) \
1725     macro(evalCodeCache) \
1726     macro(expressionInfo) \
1727     macro(lineInfo) \
1728     macro(callReturnIndexVector)
1729
1730 template<typename T>
1731 static size_t sizeInBytes(const Vector<T>& vector)
1732 {
1733     return vector.capacity() * sizeof(T);
1734 }
1735
1736 namespace {
1737
1738 class PutToScopeFireDetail : public FireDetail {
1739 public:
1740     PutToScopeFireDetail(CodeBlock* codeBlock, const Identifier& ident)
1741         : m_codeBlock(codeBlock)
1742         , m_ident(ident)
1743     {
1744     }
1745     
1746     void dump(PrintStream& out) const override
1747     {
1748         out.print("Linking put_to_scope in ", FunctionExecutableDump(jsCast<FunctionExecutable*>(m_codeBlock->ownerExecutable())), " for ", m_ident);
1749     }
1750     
1751 private:
1752     CodeBlock* m_codeBlock;
1753     const Identifier& m_ident;
1754 };
1755
1756 } // anonymous namespace
1757
1758 CodeBlock::CodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, CodeBlock& other)
1759     : JSCell(*vm, structure)
1760     , m_globalObject(other.m_globalObject)
1761     , m_numCalleeLocals(other.m_numCalleeLocals)
1762     , m_numVars(other.m_numVars)
1763     , m_shouldAlwaysBeInlined(true)
1764 #if ENABLE(JIT)
1765     , m_capabilityLevelState(DFG::CapabilityLevelNotSet)
1766 #endif
1767     , m_didFailFTLCompilation(false)
1768     , m_hasBeenCompiledWithFTL(false)
1769     , m_isConstructor(other.m_isConstructor)
1770     , m_isStrictMode(other.m_isStrictMode)
1771     , m_codeType(other.m_codeType)
1772     , m_unlinkedCode(*other.m_vm, this, other.m_unlinkedCode.get())
1773     , m_hasDebuggerStatement(false)
1774     , m_steppingMode(SteppingModeDisabled)
1775     , m_numBreakpoints(0)
1776     , m_ownerExecutable(*other.m_vm, this, other.m_ownerExecutable.get())
1777     , m_vm(other.m_vm)
1778     , m_instructions(other.m_instructions)
1779     , m_thisRegister(other.m_thisRegister)
1780     , m_scopeRegister(other.m_scopeRegister)
1781     , m_hash(other.m_hash)
1782     , m_source(other.m_source)
1783     , m_sourceOffset(other.m_sourceOffset)
1784     , m_firstLineColumnOffset(other.m_firstLineColumnOffset)
1785     , m_constantRegisters(other.m_constantRegisters)
1786     , m_constantsSourceCodeRepresentation(other.m_constantsSourceCodeRepresentation)
1787     , m_functionDecls(other.m_functionDecls)
1788     , m_functionExprs(other.m_functionExprs)
1789     , m_osrExitCounter(0)
1790     , m_optimizationDelayCounter(0)
1791     , m_reoptimizationRetryCounter(0)
1792     , m_creationTime(std::chrono::steady_clock::now())
1793 {
1794     m_visitWeaklyHasBeenCalled.store(false, std::memory_order_relaxed);
1795
1796     ASSERT(heap()->isDeferred());
1797     ASSERT(m_scopeRegister.isLocal());
1798
1799     setNumParameters(other.numParameters());
1800 }
1801
1802 void CodeBlock::finishCreation(VM& vm, CopyParsedBlockTag, CodeBlock& other)
1803 {
1804     Base::finishCreation(vm);
1805
1806     optimizeAfterWarmUp();
1807     jitAfterWarmUp();
1808
1809     if (other.m_rareData) {
1810         createRareDataIfNecessary();
1811         
1812         m_rareData->m_exceptionHandlers = other.m_rareData->m_exceptionHandlers;
1813         m_rareData->m_constantBuffers = other.m_rareData->m_constantBuffers;
1814         m_rareData->m_switchJumpTables = other.m_rareData->m_switchJumpTables;
1815         m_rareData->m_stringSwitchJumpTables = other.m_rareData->m_stringSwitchJumpTables;
1816         m_rareData->m_liveCalleeLocalsAtYield = other.m_rareData->m_liveCalleeLocalsAtYield;
1817     }
1818     
1819     heap()->m_codeBlocks.add(this);
1820 }
1821
1822 CodeBlock::CodeBlock(VM* vm, Structure* structure, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock,
1823     JSScope* scope, PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset, unsigned firstLineColumnOffset)
1824     : JSCell(*vm, structure)
1825     , m_globalObject(scope->globalObject()->vm(), this, scope->globalObject())
1826     , m_numCalleeLocals(unlinkedCodeBlock->m_numCalleeLocals)
1827     , m_numVars(unlinkedCodeBlock->m_numVars)
1828     , m_shouldAlwaysBeInlined(true)
1829 #if ENABLE(JIT)
1830     , m_capabilityLevelState(DFG::CapabilityLevelNotSet)
1831 #endif
1832     , m_didFailFTLCompilation(false)
1833     , m_hasBeenCompiledWithFTL(false)
1834     , m_isConstructor(unlinkedCodeBlock->isConstructor())
1835     , m_isStrictMode(unlinkedCodeBlock->isStrictMode())
1836     , m_codeType(unlinkedCodeBlock->codeType())
1837     , m_unlinkedCode(m_globalObject->vm(), this, unlinkedCodeBlock)
1838     , m_hasDebuggerStatement(false)
1839     , m_steppingMode(SteppingModeDisabled)
1840     , m_numBreakpoints(0)
1841     , m_ownerExecutable(m_globalObject->vm(), this, ownerExecutable)
1842     , m_vm(unlinkedCodeBlock->vm())
1843     , m_thisRegister(unlinkedCodeBlock->thisRegister())
1844     , m_scopeRegister(unlinkedCodeBlock->scopeRegister())
1845     , m_source(sourceProvider)
1846     , m_sourceOffset(sourceOffset)
1847     , m_firstLineColumnOffset(firstLineColumnOffset)
1848     , m_osrExitCounter(0)
1849     , m_optimizationDelayCounter(0)
1850     , m_reoptimizationRetryCounter(0)
1851     , m_creationTime(std::chrono::steady_clock::now())
1852 {
1853     m_visitWeaklyHasBeenCalled.store(false, std::memory_order_relaxed);
1854
1855     ASSERT(heap()->isDeferred());
1856     ASSERT(m_scopeRegister.isLocal());
1857
1858     ASSERT(m_source);
1859     setNumParameters(unlinkedCodeBlock->numParameters());
1860 }
1861
1862 void CodeBlock::finishCreation(VM& vm, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock,
1863     JSScope* scope)
1864 {
1865     Base::finishCreation(vm);
1866
1867     if (vm.typeProfiler() || vm.controlFlowProfiler())
1868         vm.functionHasExecutedCache()->removeUnexecutedRange(ownerExecutable->sourceID(), ownerExecutable->typeProfilingStartOffset(), ownerExecutable->typeProfilingEndOffset());
1869
1870     setConstantRegisters(unlinkedCodeBlock->constantRegisters(), unlinkedCodeBlock->constantsSourceCodeRepresentation());
1871     if (unlinkedCodeBlock->usesGlobalObject())
1872         m_constantRegisters[unlinkedCodeBlock->globalObjectRegister().toConstantIndex()].set(*m_vm, this, m_globalObject.get());
1873
1874     for (unsigned i = 0; i < LinkTimeConstantCount; i++) {
1875         LinkTimeConstant type = static_cast<LinkTimeConstant>(i);
1876         if (unsigned registerIndex = unlinkedCodeBlock->registerIndexForLinkTimeConstant(type))
1877             m_constantRegisters[registerIndex].set(*m_vm, this, m_globalObject->jsCellForLinkTimeConstant(type));
1878     }
1879
1880 #if !ASSERT_DISABLED
1881     HashSet<int, WTF::IntHash<int>, WTF::UnsignedWithZeroKeyHashTraits<int>> clonedConstantSymbolTables;
1882 #endif
1883     {
1884 #if !ASSERT_DISABLED
1885         HashSet<SymbolTable*> clonedSymbolTables;
1886 #endif
1887         bool hasTypeProfiler = !!vm.typeProfiler();
1888         for (unsigned i = 0; i < m_constantRegisters.size(); i++) {
1889             if (m_constantRegisters[i].get().isEmpty())
1890                 continue;
1891             if (SymbolTable* symbolTable = jsDynamicCast<SymbolTable*>(m_constantRegisters[i].get())) {
1892                 ASSERT(clonedSymbolTables.add(symbolTable).isNewEntry);
1893                 if (hasTypeProfiler) {
1894                     ConcurrentJITLocker locker(symbolTable->m_lock);
1895                     symbolTable->prepareForTypeProfiling(locker);
1896                 }
1897                 m_constantRegisters[i].set(*m_vm, this, symbolTable->cloneScopePart(*m_vm));
1898 #if !ASSERT_DISABLED
1899                 clonedConstantSymbolTables.add(i + FirstConstantRegisterIndex);
1900 #endif
1901             }
1902         }
1903     }
1904
1905     // We already have the cloned symbol table for the module environment since we need to instantiate
1906     // the module environments before linking the code block. We replace the stored symbol table with the already cloned one.
1907     if (UnlinkedModuleProgramCodeBlock* unlinkedModuleProgramCodeBlock = jsDynamicCast<UnlinkedModuleProgramCodeBlock*>(unlinkedCodeBlock)) {
1908         SymbolTable* clonedSymbolTable = jsCast<ModuleProgramExecutable*>(ownerExecutable)->moduleEnvironmentSymbolTable();
1909         if (m_vm->typeProfiler()) {
1910             ConcurrentJITLocker locker(clonedSymbolTable->m_lock);
1911             clonedSymbolTable->prepareForTypeProfiling(locker);
1912         }
1913         replaceConstant(unlinkedModuleProgramCodeBlock->moduleEnvironmentSymbolTableConstantRegisterOffset(), clonedSymbolTable);
1914     }
1915
1916     bool shouldUpdateFunctionHasExecutedCache = vm.typeProfiler() || vm.controlFlowProfiler();
1917     m_functionDecls = RefCountedArray<WriteBarrier<FunctionExecutable>>(unlinkedCodeBlock->numberOfFunctionDecls());
1918     for (size_t count = unlinkedCodeBlock->numberOfFunctionDecls(), i = 0; i < count; ++i) {
1919         UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionDecl(i);
1920         if (shouldUpdateFunctionHasExecutedCache)
1921             vm.functionHasExecutedCache()->insertUnexecutedRange(ownerExecutable->sourceID(), unlinkedExecutable->typeProfilingStartOffset(), unlinkedExecutable->typeProfilingEndOffset());
1922         m_functionDecls[i].set(*m_vm, this, unlinkedExecutable->link(*m_vm, ownerExecutable->source()));
1923     }
1924
1925     m_functionExprs = RefCountedArray<WriteBarrier<FunctionExecutable>>(unlinkedCodeBlock->numberOfFunctionExprs());
1926     for (size_t count = unlinkedCodeBlock->numberOfFunctionExprs(), i = 0; i < count; ++i) {
1927         UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionExpr(i);
1928         if (shouldUpdateFunctionHasExecutedCache)
1929             vm.functionHasExecutedCache()->insertUnexecutedRange(ownerExecutable->sourceID(), unlinkedExecutable->typeProfilingStartOffset(), unlinkedExecutable->typeProfilingEndOffset());
1930         m_functionExprs[i].set(*m_vm, this, unlinkedExecutable->link(*m_vm, ownerExecutable->source()));
1931     }
1932
1933     if (unlinkedCodeBlock->hasRareData()) {
1934         createRareDataIfNecessary();
1935         if (size_t count = unlinkedCodeBlock->constantBufferCount()) {
1936             m_rareData->m_constantBuffers.grow(count);
1937             for (size_t i = 0; i < count; i++) {
1938                 const UnlinkedCodeBlock::ConstantBuffer& buffer = unlinkedCodeBlock->constantBuffer(i);
1939                 m_rareData->m_constantBuffers[i] = buffer;
1940             }
1941         }
1942         if (size_t count = unlinkedCodeBlock->numberOfExceptionHandlers()) {
1943             m_rareData->m_exceptionHandlers.resizeToFit(count);
1944             for (size_t i = 0; i < count; i++) {
1945                 const UnlinkedHandlerInfo& unlinkedHandler = unlinkedCodeBlock->exceptionHandler(i);
1946                 HandlerInfo& handler = m_rareData->m_exceptionHandlers[i];
1947 #if ENABLE(JIT)
1948                 handler.initialize(unlinkedHandler, CodeLocationLabel(MacroAssemblerCodePtr::createFromExecutableAddress(LLInt::getCodePtr(op_catch))));
1949 #else
1950                 handler.initialize(unlinkedHandler);
1951 #endif
1952             }
1953         }
1954
1955         if (size_t count = unlinkedCodeBlock->numberOfStringSwitchJumpTables()) {
1956             m_rareData->m_stringSwitchJumpTables.grow(count);
1957             for (size_t i = 0; i < count; i++) {
1958                 UnlinkedStringJumpTable::StringOffsetTable::iterator ptr = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.begin();
1959                 UnlinkedStringJumpTable::StringOffsetTable::iterator end = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.end();
1960                 for (; ptr != end; ++ptr) {
1961                     OffsetLocation offset;
1962                     offset.branchOffset = ptr->value;
1963                     m_rareData->m_stringSwitchJumpTables[i].offsetTable.add(ptr->key, offset);
1964                 }
1965             }
1966         }
1967
1968         if (size_t count = unlinkedCodeBlock->numberOfSwitchJumpTables()) {
1969             m_rareData->m_switchJumpTables.grow(count);
1970             for (size_t i = 0; i < count; i++) {
1971                 UnlinkedSimpleJumpTable& sourceTable = unlinkedCodeBlock->switchJumpTable(i);
1972                 SimpleJumpTable& destTable = m_rareData->m_switchJumpTables[i];
1973                 destTable.branchOffsets = sourceTable.branchOffsets;
1974                 destTable.min = sourceTable.min;
1975             }
1976         }
1977     }
1978
1979     // Allocate metadata buffers for the bytecode
1980     if (size_t size = unlinkedCodeBlock->numberOfLLintCallLinkInfos())
1981         m_llintCallLinkInfos = RefCountedArray<LLIntCallLinkInfo>(size);
1982     if (size_t size = unlinkedCodeBlock->numberOfArrayProfiles())
1983         m_arrayProfiles.grow(size);
1984     if (size_t size = unlinkedCodeBlock->numberOfArrayAllocationProfiles())
1985         m_arrayAllocationProfiles = RefCountedArray<ArrayAllocationProfile>(size);
1986     if (size_t size = unlinkedCodeBlock->numberOfValueProfiles())
1987         m_valueProfiles = RefCountedArray<ValueProfile>(size);
1988     if (size_t size = unlinkedCodeBlock->numberOfObjectAllocationProfiles())
1989         m_objectAllocationProfiles = RefCountedArray<ObjectAllocationProfile>(size);
1990
1991 #if ENABLE(JIT)
1992     setCalleeSaveRegisters(RegisterSet::llintBaselineCalleeSaveRegisters());
1993 #endif
1994
1995     // Copy and translate the UnlinkedInstructions
1996     unsigned instructionCount = unlinkedCodeBlock->instructions().count();
1997     UnlinkedInstructionStream::Reader instructionReader(unlinkedCodeBlock->instructions());
1998
1999     // Bookkeep the strongly referenced module environments.
2000     HashSet<JSModuleEnvironment*> stronglyReferencedModuleEnvironments;
2001
2002     // Bookkeep the merge point bytecode offsets.
2003     Vector<size_t> mergePointBytecodeOffsets;
2004
2005     RefCountedArray<Instruction> instructions(instructionCount);
2006
2007     for (unsigned i = 0; !instructionReader.atEnd(); ) {
2008         const UnlinkedInstruction* pc = instructionReader.next();
2009
2010         unsigned opLength = opcodeLength(pc[0].u.opcode);
2011
2012         instructions[i] = vm.interpreter->getOpcode(pc[0].u.opcode);
2013         for (size_t j = 1; j < opLength; ++j) {
2014             if (sizeof(int32_t) != sizeof(intptr_t))
2015                 instructions[i + j].u.pointer = 0;
2016             instructions[i + j].u.operand = pc[j].u.operand;
2017         }
2018         switch (pc[0].u.opcode) {
2019         case op_has_indexed_property: {
2020             int arrayProfileIndex = pc[opLength - 1].u.operand;
2021             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
2022
2023             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
2024             break;
2025         }
2026         case op_call_varargs:
2027         case op_tail_call_varargs:
2028         case op_construct_varargs:
2029         case op_get_by_val: {
2030             int arrayProfileIndex = pc[opLength - 2].u.operand;
2031             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
2032
2033             instructions[i + opLength - 2] = &m_arrayProfiles[arrayProfileIndex];
2034             FALLTHROUGH;
2035         }
2036         case op_get_direct_pname:
2037         case op_get_by_id:
2038         case op_get_from_arguments: {
2039             ValueProfile* profile = &m_valueProfiles[pc[opLength - 1].u.operand];
2040             ASSERT(profile->m_bytecodeOffset == -1);
2041             profile->m_bytecodeOffset = i;
2042             instructions[i + opLength - 1] = profile;
2043             break;
2044         }
2045         case op_put_by_val: {
2046             int arrayProfileIndex = pc[opLength - 1].u.operand;
2047             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
2048             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
2049             break;
2050         }
2051         case op_put_by_val_direct: {
2052             int arrayProfileIndex = pc[opLength - 1].u.operand;
2053             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
2054             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
2055             break;
2056         }
2057
2058         case op_new_array:
2059         case op_new_array_buffer:
2060         case op_new_array_with_size: {
2061             int arrayAllocationProfileIndex = pc[opLength - 1].u.operand;
2062             instructions[i + opLength - 1] = &m_arrayAllocationProfiles[arrayAllocationProfileIndex];
2063             break;
2064         }
2065         case op_new_object: {
2066             int objectAllocationProfileIndex = pc[opLength - 1].u.operand;
2067             ObjectAllocationProfile* objectAllocationProfile = &m_objectAllocationProfiles[objectAllocationProfileIndex];
2068             int inferredInlineCapacity = pc[opLength - 2].u.operand;
2069
2070             instructions[i + opLength - 1] = objectAllocationProfile;
2071             objectAllocationProfile->initialize(vm,
2072                 this, m_globalObject->objectPrototype(), inferredInlineCapacity);
2073             break;
2074         }
2075
2076         case op_call:
2077         case op_tail_call:
2078         case op_call_eval: {
2079             ValueProfile* profile = &m_valueProfiles[pc[opLength - 1].u.operand];
2080             ASSERT(profile->m_bytecodeOffset == -1);
2081             profile->m_bytecodeOffset = i;
2082             instructions[i + opLength - 1] = profile;
2083             int arrayProfileIndex = pc[opLength - 2].u.operand;
2084             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
2085             instructions[i + opLength - 2] = &m_arrayProfiles[arrayProfileIndex];
2086             instructions[i + 5] = &m_llintCallLinkInfos[pc[5].u.operand];
2087             break;
2088         }
2089         case op_construct: {
2090             instructions[i + 5] = &m_llintCallLinkInfos[pc[5].u.operand];
2091             ValueProfile* profile = &m_valueProfiles[pc[opLength - 1].u.operand];
2092             ASSERT(profile->m_bytecodeOffset == -1);
2093             profile->m_bytecodeOffset = i;
2094             instructions[i + opLength - 1] = profile;
2095             break;
2096         }
2097         case op_get_array_length:
2098             CRASH();
2099
2100 #if !ASSERT_DISABLED
2101         case op_create_lexical_environment: {
2102             int symbolTableIndex = pc[3].u.operand;
2103             ASSERT(clonedConstantSymbolTables.contains(symbolTableIndex));
2104             break;
2105         }
2106 #endif
2107
2108         case op_resolve_scope: {
2109             const Identifier& ident = identifier(pc[3].u.operand);
2110             ResolveType type = static_cast<ResolveType>(pc[4].u.operand);
2111             RELEASE_ASSERT(type != LocalClosureVar);
2112             int localScopeDepth = pc[5].u.operand;
2113
2114             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Get, type, NotInitialization);
2115             instructions[i + 4].u.operand = op.type;
2116             instructions[i + 5].u.operand = op.depth;
2117             if (op.lexicalEnvironment) {
2118                 if (op.type == ModuleVar) {
2119                     // Keep the linked module environment strongly referenced.
2120                     if (stronglyReferencedModuleEnvironments.add(jsCast<JSModuleEnvironment*>(op.lexicalEnvironment)).isNewEntry)
2121                         addConstant(op.lexicalEnvironment);
2122                     instructions[i + 6].u.jsCell.set(vm, this, op.lexicalEnvironment);
2123                 } else
2124                     instructions[i + 6].u.symbolTable.set(vm, this, op.lexicalEnvironment->symbolTable());
2125             } else if (JSScope* constantScope = JSScope::constantScopeForCodeBlock(op.type, this))
2126                 instructions[i + 6].u.jsCell.set(vm, this, constantScope);
2127             else
2128                 instructions[i + 6].u.pointer = nullptr;
2129             break;
2130         }
2131
2132         case op_get_from_scope: {
2133             ValueProfile* profile = &m_valueProfiles[pc[opLength - 1].u.operand];
2134             ASSERT(profile->m_bytecodeOffset == -1);
2135             profile->m_bytecodeOffset = i;
2136             instructions[i + opLength - 1] = profile;
2137
2138             // get_from_scope dst, scope, id, GetPutInfo, Structure, Operand
2139
2140             int localScopeDepth = pc[5].u.operand;
2141             instructions[i + 5].u.pointer = nullptr;
2142
2143             GetPutInfo getPutInfo = GetPutInfo(pc[4].u.operand);
2144             ASSERT(getPutInfo.initializationMode() == NotInitialization);
2145             if (getPutInfo.resolveType() == LocalClosureVar) {
2146                 instructions[i + 4] = GetPutInfo(getPutInfo.resolveMode(), ClosureVar, getPutInfo.initializationMode()).operand();
2147                 break;
2148             }
2149
2150             const Identifier& ident = identifier(pc[3].u.operand);
2151             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Get, getPutInfo.resolveType(), NotInitialization);
2152
2153             instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), op.type, getPutInfo.initializationMode()).operand();
2154             if (op.type == ModuleVar)
2155                 instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), ClosureVar, getPutInfo.initializationMode()).operand();
2156             if (op.type == GlobalVar || op.type == GlobalVarWithVarInjectionChecks || op.type == GlobalLexicalVar || op.type == GlobalLexicalVarWithVarInjectionChecks)
2157                 instructions[i + 5].u.watchpointSet = op.watchpointSet;
2158             else if (op.structure)
2159                 instructions[i + 5].u.structure.set(vm, this, op.structure);
2160             instructions[i + 6].u.pointer = reinterpret_cast<void*>(op.operand);
2161             break;
2162         }
2163
2164         case op_put_to_scope: {
2165             // put_to_scope scope, id, value, GetPutInfo, Structure, Operand
2166             GetPutInfo getPutInfo = GetPutInfo(pc[4].u.operand);
2167             if (getPutInfo.resolveType() == LocalClosureVar) {
2168                 // Only do watching if the property we're putting to is not anonymous.
2169                 if (static_cast<unsigned>(pc[2].u.operand) != UINT_MAX) {
2170                     int symbolTableIndex = pc[5].u.operand;
2171                     ASSERT(clonedConstantSymbolTables.contains(symbolTableIndex));
2172                     SymbolTable* symbolTable = jsCast<SymbolTable*>(getConstant(symbolTableIndex));
2173                     const Identifier& ident = identifier(pc[2].u.operand);
2174                     ConcurrentJITLocker locker(symbolTable->m_lock);
2175                     auto iter = symbolTable->find(locker, ident.impl());
2176                     ASSERT(iter != symbolTable->end(locker));
2177                     iter->value.prepareToWatch();
2178                     instructions[i + 5].u.watchpointSet = iter->value.watchpointSet();
2179                 } else
2180                     instructions[i + 5].u.watchpointSet = nullptr;
2181                 break;
2182             }
2183
2184             const Identifier& ident = identifier(pc[2].u.operand);
2185             int localScopeDepth = pc[5].u.operand;
2186             instructions[i + 5].u.pointer = nullptr;
2187             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Put, getPutInfo.resolveType(), getPutInfo.initializationMode());
2188
2189             instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), op.type, getPutInfo.initializationMode()).operand();
2190             if (op.type == GlobalVar || op.type == GlobalVarWithVarInjectionChecks || op.type == GlobalLexicalVar || op.type == GlobalLexicalVarWithVarInjectionChecks)
2191                 instructions[i + 5].u.watchpointSet = op.watchpointSet;
2192             else if (op.type == ClosureVar || op.type == ClosureVarWithVarInjectionChecks) {
2193                 if (op.watchpointSet)
2194                     op.watchpointSet->invalidate(PutToScopeFireDetail(this, ident));
2195             } else if (op.structure)
2196                 instructions[i + 5].u.structure.set(vm, this, op.structure);
2197             instructions[i + 6].u.pointer = reinterpret_cast<void*>(op.operand);
2198
2199             break;
2200         }
2201
2202         case op_profile_type: {
2203             RELEASE_ASSERT(vm.typeProfiler());
2204             // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType?
2205             size_t instructionOffset = i + opLength - 1;
2206             unsigned divotStart, divotEnd;
2207             GlobalVariableID globalVariableID = 0;
2208             RefPtr<TypeSet> globalTypeSet;
2209             bool shouldAnalyze = m_unlinkedCode->typeProfilerExpressionInfoForBytecodeOffset(instructionOffset, divotStart, divotEnd);
2210             VirtualRegister profileRegister(pc[1].u.operand);
2211             ProfileTypeBytecodeFlag flag = static_cast<ProfileTypeBytecodeFlag>(pc[3].u.operand);
2212             SymbolTable* symbolTable = nullptr;
2213
2214             switch (flag) {
2215             case ProfileTypeBytecodeClosureVar: {
2216                 const Identifier& ident = identifier(pc[4].u.operand);
2217                 int localScopeDepth = pc[2].u.operand;
2218                 ResolveType type = static_cast<ResolveType>(pc[5].u.operand);
2219                 // Even though type profiling may be profiling either a Get or a Put, we can always claim a Get because
2220                 // we're abstractly "read"ing from a JSScope.
2221                 ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Get, type, NotInitialization);
2222
2223                 if (op.type == ClosureVar || op.type == ModuleVar)
2224                     symbolTable = op.lexicalEnvironment->symbolTable();
2225                 else if (op.type == GlobalVar)
2226                     symbolTable = m_globalObject.get()->symbolTable();
2227
2228                 UniquedStringImpl* impl = (op.type == ModuleVar) ? op.importedName.get() : ident.impl();
2229                 if (symbolTable) {
2230                     ConcurrentJITLocker locker(symbolTable->m_lock);
2231                     // If our parent scope was created while profiling was disabled, it will not have prepared for profiling yet.
2232                     symbolTable->prepareForTypeProfiling(locker);
2233                     globalVariableID = symbolTable->uniqueIDForVariable(locker, impl, vm);
2234                     globalTypeSet = symbolTable->globalTypeSetForVariable(locker, impl, vm);
2235                 } else
2236                     globalVariableID = TypeProfilerNoGlobalIDExists;
2237
2238                 break;
2239             }
2240             case ProfileTypeBytecodeLocallyResolved: {
2241                 int symbolTableIndex = pc[2].u.operand;
2242                 ASSERT(clonedConstantSymbolTables.contains(symbolTableIndex));
2243                 SymbolTable* symbolTable = jsCast<SymbolTable*>(getConstant(symbolTableIndex));
2244                 const Identifier& ident = identifier(pc[4].u.operand);
2245                 ConcurrentJITLocker locker(symbolTable->m_lock);
2246                 // If our parent scope was created while profiling was disabled, it will not have prepared for profiling yet.
2247                 globalVariableID = symbolTable->uniqueIDForVariable(locker, ident.impl(), vm);
2248                 globalTypeSet = symbolTable->globalTypeSetForVariable(locker, ident.impl(), vm);
2249
2250                 break;
2251             }
2252             case ProfileTypeBytecodeDoesNotHaveGlobalID: 
2253             case ProfileTypeBytecodeFunctionArgument: {
2254                 globalVariableID = TypeProfilerNoGlobalIDExists;
2255                 break;
2256             }
2257             case ProfileTypeBytecodeFunctionReturnStatement: {
2258                 RELEASE_ASSERT(ownerExecutable->isFunctionExecutable());
2259                 globalTypeSet = jsCast<FunctionExecutable*>(ownerExecutable)->returnStatementTypeSet();
2260                 globalVariableID = TypeProfilerReturnStatement;
2261                 if (!shouldAnalyze) {
2262                     // Because a return statement can be added implicitly to return undefined at the end of a function,
2263                     // and these nodes don't emit expression ranges because they aren't in the actual source text of
2264                     // the user's program, give the type profiler some range to identify these return statements.
2265                     // Currently, the text offset that is used as identification is "f" in the function keyword
2266                     // and is stored on TypeLocation's m_divotForFunctionOffsetIfReturnStatement member variable.
2267                     divotStart = divotEnd = ownerExecutable->typeProfilingStartOffset();
2268                     shouldAnalyze = true;
2269                 }
2270                 break;
2271             }
2272             }
2273
2274             std::pair<TypeLocation*, bool> locationPair = vm.typeProfiler()->typeLocationCache()->getTypeLocation(globalVariableID,
2275                 ownerExecutable->sourceID(), divotStart, divotEnd, globalTypeSet, &vm);
2276             TypeLocation* location = locationPair.first;
2277             bool isNewLocation = locationPair.second;
2278
2279             if (flag == ProfileTypeBytecodeFunctionReturnStatement)
2280                 location->m_divotForFunctionOffsetIfReturnStatement = ownerExecutable->typeProfilingStartOffset();
2281
2282             if (shouldAnalyze && isNewLocation)
2283                 vm.typeProfiler()->insertNewLocation(location);
2284
2285             instructions[i + 2].u.location = location;
2286             break;
2287         }
2288
2289         case op_debug: {
2290             if (pc[1].u.index == DidReachBreakpoint)
2291                 m_hasDebuggerStatement = true;
2292             break;
2293         }
2294
2295         case op_save: {
2296             unsigned liveCalleeLocalsIndex = pc[2].u.index;
2297             int offset = pc[3].u.operand;
2298             if (liveCalleeLocalsIndex >= mergePointBytecodeOffsets.size())
2299                 mergePointBytecodeOffsets.resize(liveCalleeLocalsIndex + 1);
2300             mergePointBytecodeOffsets[liveCalleeLocalsIndex] = i + offset;
2301             break;
2302         }
2303
2304         default:
2305             break;
2306         }
2307         i += opLength;
2308     }
2309
2310     if (vm.controlFlowProfiler())
2311         insertBasicBlockBoundariesForControlFlowProfiler(instructions);
2312
2313     m_instructions = WTFMove(instructions);
2314
2315     // Perform bytecode liveness analysis to determine which locals are live and should be resumed when executing op_resume.
2316     if (unlinkedCodeBlock->parseMode() == SourceParseMode::GeneratorBodyMode) {
2317         if (size_t count = mergePointBytecodeOffsets.size()) {
2318             createRareDataIfNecessary();
2319             BytecodeLivenessAnalysis liveness(this);
2320             m_rareData->m_liveCalleeLocalsAtYield.grow(count);
2321             size_t liveCalleeLocalsIndex = 0;
2322             for (size_t bytecodeOffset : mergePointBytecodeOffsets) {
2323                 m_rareData->m_liveCalleeLocalsAtYield[liveCalleeLocalsIndex] = liveness.getLivenessInfoAtBytecodeOffset(bytecodeOffset);
2324                 ++liveCalleeLocalsIndex;
2325             }
2326         }
2327     }
2328
2329     // Set optimization thresholds only after m_instructions is initialized, since these
2330     // rely on the instruction count (and are in theory permitted to also inspect the
2331     // instruction stream to more accurate assess the cost of tier-up).
2332     optimizeAfterWarmUp();
2333     jitAfterWarmUp();
2334
2335     // If the concurrent thread will want the code block's hash, then compute it here
2336     // synchronously.
2337     if (Options::alwaysComputeHash())
2338         hash();
2339
2340     if (Options::dumpGeneratedBytecodes())
2341         dumpBytecode();
2342     
2343     heap()->m_codeBlocks.add(this);
2344     heap()->reportExtraMemoryAllocated(m_instructions.size() * sizeof(Instruction));
2345 }
2346
2347 #if ENABLE(WEBASSEMBLY)
2348 CodeBlock::CodeBlock(VM* vm, Structure* structure, WebAssemblyExecutable* ownerExecutable, JSGlobalObject* globalObject)
2349     : JSCell(*vm, structure)
2350     , m_globalObject(globalObject->vm(), this, globalObject)
2351     , m_numCalleeLocals(0)
2352     , m_numVars(0)
2353     , m_shouldAlwaysBeInlined(false)
2354 #if ENABLE(JIT)
2355     , m_capabilityLevelState(DFG::CannotCompile)
2356 #endif
2357     , m_didFailFTLCompilation(false)
2358     , m_hasBeenCompiledWithFTL(false)
2359     , m_isConstructor(false)
2360     , m_isStrictMode(false)
2361     , m_codeType(FunctionCode)
2362     , m_hasDebuggerStatement(false)
2363     , m_steppingMode(SteppingModeDisabled)
2364     , m_numBreakpoints(0)
2365     , m_ownerExecutable(m_globalObject->vm(), this, ownerExecutable)
2366     , m_vm(vm)
2367     , m_osrExitCounter(0)
2368     , m_optimizationDelayCounter(0)
2369     , m_reoptimizationRetryCounter(0)
2370     , m_creationTime(std::chrono::steady_clock::now())
2371 {
2372     ASSERT(heap()->isDeferred());
2373 }
2374
2375 void CodeBlock::finishCreation(VM& vm, WebAssemblyExecutable*, JSGlobalObject*)
2376 {
2377     Base::finishCreation(vm);
2378
2379     heap()->m_codeBlocks.add(this);
2380 }
2381 #endif
2382
2383 CodeBlock::~CodeBlock()
2384 {
2385     if (m_vm->m_perBytecodeProfiler)
2386         m_vm->m_perBytecodeProfiler->notifyDestruction(this);
2387     
2388 #if ENABLE(VERBOSE_VALUE_PROFILE)
2389     dumpValueProfiles();
2390 #endif
2391
2392     // We may be destroyed before any CodeBlocks that refer to us are destroyed.
2393     // Consider that two CodeBlocks become unreachable at the same time. There
2394     // is no guarantee about the order in which the CodeBlocks are destroyed.
2395     // So, if we don't remove incoming calls, and get destroyed before the
2396     // CodeBlock(s) that have calls into us, then the CallLinkInfo vector's
2397     // destructor will try to remove nodes from our (no longer valid) linked list.
2398     unlinkIncomingCalls();
2399     
2400     // Note that our outgoing calls will be removed from other CodeBlocks'
2401     // m_incomingCalls linked lists through the execution of the ~CallLinkInfo
2402     // destructors.
2403
2404 #if ENABLE(JIT)
2405     for (Bag<StructureStubInfo>::iterator iter = m_stubInfos.begin(); !!iter; ++iter) {
2406         StructureStubInfo* stub = *iter;
2407         stub->aboutToDie();
2408         stub->deref();
2409     }
2410 #endif // ENABLE(JIT)
2411 }
2412
2413 void CodeBlock::setAlternative(VM& vm, CodeBlock* alternative)
2414 {
2415     m_alternative.set(vm, this, alternative);
2416 }
2417
2418 void CodeBlock::setNumParameters(int newValue)
2419 {
2420     m_numParameters = newValue;
2421
2422     m_argumentValueProfiles = RefCountedArray<ValueProfile>(newValue);
2423 }
2424
2425 void EvalCodeCache::visitAggregate(SlotVisitor& visitor)
2426 {
2427     EvalCacheMap::iterator end = m_cacheMap.end();
2428     for (EvalCacheMap::iterator ptr = m_cacheMap.begin(); ptr != end; ++ptr)
2429         visitor.append(&ptr->value);
2430 }
2431
2432 CodeBlock* CodeBlock::specialOSREntryBlockOrNull()
2433 {
2434 #if ENABLE(FTL_JIT)
2435     if (jitType() != JITCode::DFGJIT)
2436         return 0;
2437     DFG::JITCode* jitCode = m_jitCode->dfg();
2438     return jitCode->osrEntryBlock();
2439 #else // ENABLE(FTL_JIT)
2440     return 0;
2441 #endif // ENABLE(FTL_JIT)
2442 }
2443
2444 void CodeBlock::visitWeakly(SlotVisitor& visitor)
2445 {
2446     bool setByMe = m_visitWeaklyHasBeenCalled.compareExchangeStrong(false, true);
2447     if (!setByMe)
2448         return;
2449
2450     if (Heap::isMarked(this))
2451         return;
2452
2453     if (shouldVisitStrongly()) {
2454         visitor.appendUnbarrieredReadOnlyPointer(this);
2455         return;
2456     }
2457
2458     // There are two things that may use unconditional finalizers: inline cache clearing
2459     // and jettisoning. The probability of us wanting to do at least one of those things
2460     // is probably quite close to 1. So we add one no matter what and when it runs, it
2461     // figures out whether it has any work to do.
2462     visitor.addUnconditionalFinalizer(&m_unconditionalFinalizer);
2463
2464     if (!JITCode::isOptimizingJIT(jitType()))
2465         return;
2466
2467     // If we jettison ourselves we'll install our alternative, so make sure that it
2468     // survives GC even if we don't.
2469     visitor.append(&m_alternative);
2470     
2471     // There are two things that we use weak reference harvesters for: DFG fixpoint for
2472     // jettisoning, and trying to find structures that would be live based on some
2473     // inline cache. So it makes sense to register them regardless.
2474     visitor.addWeakReferenceHarvester(&m_weakReferenceHarvester);
2475
2476 #if ENABLE(DFG_JIT)
2477     // We get here if we're live in the sense that our owner executable is live,
2478     // but we're not yet live for sure in another sense: we may yet decide that this
2479     // code block should be jettisoned based on its outgoing weak references being
2480     // stale. Set a flag to indicate that we're still assuming that we're dead, and
2481     // perform one round of determining if we're live. The GC may determine, based on
2482     // either us marking additional objects, or by other objects being marked for
2483     // other reasons, that this iteration should run again; it will notify us of this
2484     // decision by calling harvestWeakReferences().
2485
2486     m_allTransitionsHaveBeenMarked = false;
2487     propagateTransitions(visitor);
2488
2489     m_jitCode->dfgCommon()->livenessHasBeenProved = false;
2490     determineLiveness(visitor);
2491 #endif // ENABLE(DFG_JIT)
2492 }
2493
2494 size_t CodeBlock::estimatedSize(JSCell* cell)
2495 {
2496     CodeBlock* thisObject = jsCast<CodeBlock*>(cell);
2497     size_t extraMemoryAllocated = thisObject->m_instructions.size() * sizeof(Instruction);
2498     if (thisObject->m_jitCode)
2499         extraMemoryAllocated += thisObject->m_jitCode->size();
2500     return Base::estimatedSize(cell) + extraMemoryAllocated;
2501 }
2502
2503 void CodeBlock::visitChildren(JSCell* cell, SlotVisitor& visitor)
2504 {
2505     CodeBlock* thisObject = jsCast<CodeBlock*>(cell);
2506     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
2507     JSCell::visitChildren(thisObject, visitor);
2508     thisObject->visitChildren(visitor);
2509 }
2510
2511 void CodeBlock::visitChildren(SlotVisitor& visitor)
2512 {
2513     // There are two things that may use unconditional finalizers: inline cache clearing
2514     // and jettisoning. The probability of us wanting to do at least one of those things
2515     // is probably quite close to 1. So we add one no matter what and when it runs, it
2516     // figures out whether it has any work to do.
2517     visitor.addUnconditionalFinalizer(&m_unconditionalFinalizer);
2518
2519     if (CodeBlock* otherBlock = specialOSREntryBlockOrNull())
2520         visitor.appendUnbarrieredReadOnlyPointer(otherBlock);
2521
2522     if (m_jitCode)
2523         visitor.reportExtraMemoryVisited(m_jitCode->size());
2524     if (m_instructions.size())
2525         visitor.reportExtraMemoryVisited(m_instructions.size() * sizeof(Instruction) / m_instructions.refCount());
2526
2527     stronglyVisitStrongReferences(visitor);
2528     stronglyVisitWeakReferences(visitor);
2529
2530     m_allTransitionsHaveBeenMarked = false;
2531     propagateTransitions(visitor);
2532 }
2533
2534 bool CodeBlock::shouldVisitStrongly()
2535 {
2536     if (Options::forceCodeBlockLiveness())
2537         return true;
2538
2539     if (shouldJettisonDueToOldAge())
2540         return false;
2541
2542     // Interpreter and Baseline JIT CodeBlocks don't need to be jettisoned when
2543     // their weak references go stale. So if a basline JIT CodeBlock gets
2544     // scanned, we can assume that this means that it's live.
2545     if (!JITCode::isOptimizingJIT(jitType()))
2546         return true;
2547
2548     return false;
2549 }
2550
2551 bool CodeBlock::shouldJettisonDueToWeakReference()
2552 {
2553     if (!JITCode::isOptimizingJIT(jitType()))
2554         return false;
2555     return !Heap::isMarked(this);
2556 }
2557
2558 bool CodeBlock::shouldJettisonDueToOldAge()
2559 {
2560     return false;
2561 }
2562
2563 #if ENABLE(DFG_JIT)
2564 static bool shouldMarkTransition(DFG::WeakReferenceTransition& transition)
2565 {
2566     if (transition.m_codeOrigin && !Heap::isMarked(transition.m_codeOrigin.get()))
2567         return false;
2568     
2569     if (!Heap::isMarked(transition.m_from.get()))
2570         return false;
2571     
2572     return true;
2573 }
2574 #endif // ENABLE(DFG_JIT)
2575
2576 void CodeBlock::propagateTransitions(SlotVisitor& visitor)
2577 {
2578     UNUSED_PARAM(visitor);
2579
2580     if (m_allTransitionsHaveBeenMarked)
2581         return;
2582
2583     bool allAreMarkedSoFar = true;
2584         
2585     Interpreter* interpreter = m_vm->interpreter;
2586     if (jitType() == JITCode::InterpreterThunk) {
2587         const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
2588         for (size_t i = 0; i < propertyAccessInstructions.size(); ++i) {
2589             Instruction* instruction = &instructions()[propertyAccessInstructions[i]];
2590             switch (interpreter->getOpcodeID(instruction[0].u.opcode)) {
2591             case op_put_by_id: {
2592                 StructureID oldStructureID = instruction[4].u.structureID;
2593                 StructureID newStructureID = instruction[6].u.structureID;
2594                 if (!oldStructureID || !newStructureID)
2595                     break;
2596                 Structure* oldStructure =
2597                     m_vm->heap.structureIDTable().get(oldStructureID);
2598                 Structure* newStructure =
2599                     m_vm->heap.structureIDTable().get(newStructureID);
2600                 if (Heap::isMarked(oldStructure))
2601                     visitor.appendUnbarrieredReadOnlyPointer(newStructure);
2602                 else
2603                     allAreMarkedSoFar = false;
2604                 break;
2605             }
2606             default:
2607                 break;
2608             }
2609         }
2610     }
2611
2612 #if ENABLE(JIT)
2613     if (JITCode::isJIT(jitType())) {
2614         for (Bag<StructureStubInfo>::iterator iter = m_stubInfos.begin(); !!iter; ++iter) {
2615             StructureStubInfo& stubInfo = **iter;
2616             if (stubInfo.cacheType != CacheType::Stub)
2617                 continue;
2618             PolymorphicAccess* list = stubInfo.u.stub;
2619             JSCell* origin = stubInfo.codeOrigin.codeOriginOwner();
2620             if (origin && !Heap::isMarked(origin)) {
2621                 allAreMarkedSoFar = false;
2622                 continue;
2623             }
2624             for (unsigned j = list->size(); j--;) {
2625                 const AccessCase& access = list->at(j);
2626                 if (access.type() != AccessCase::Transition)
2627                     continue;
2628                 if (Heap::isMarked(access.structure()))
2629                     visitor.appendUnbarrieredReadOnlyPointer(access.newStructure());
2630                 else
2631                     allAreMarkedSoFar = false;
2632             }
2633         }
2634     }
2635 #endif // ENABLE(JIT)
2636     
2637 #if ENABLE(DFG_JIT)
2638     if (JITCode::isOptimizingJIT(jitType())) {
2639         DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2640         
2641         for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
2642             if (shouldMarkTransition(dfgCommon->transitions[i])) {
2643                 // If the following three things are live, then the target of the
2644                 // transition is also live:
2645                 //
2646                 // - This code block. We know it's live already because otherwise
2647                 //   we wouldn't be scanning ourselves.
2648                 //
2649                 // - The code origin of the transition. Transitions may arise from
2650                 //   code that was inlined. They are not relevant if the user's
2651                 //   object that is required for the inlinee to run is no longer
2652                 //   live.
2653                 //
2654                 // - The source of the transition. The transition checks if some
2655                 //   heap location holds the source, and if so, stores the target.
2656                 //   Hence the source must be live for the transition to be live.
2657                 //
2658                 // We also short-circuit the liveness if the structure is harmless
2659                 // to mark (i.e. its global object and prototype are both already
2660                 // live).
2661                 
2662                 visitor.append(&dfgCommon->transitions[i].m_to);
2663             } else
2664                 allAreMarkedSoFar = false;
2665         }
2666     }
2667 #endif // ENABLE(DFG_JIT)
2668     
2669     if (allAreMarkedSoFar)
2670         m_allTransitionsHaveBeenMarked = true;
2671 }
2672
2673 void CodeBlock::determineLiveness(SlotVisitor& visitor)
2674 {
2675     UNUSED_PARAM(visitor);
2676     
2677 #if ENABLE(DFG_JIT)
2678     // Check if we have any remaining work to do.
2679     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2680     if (dfgCommon->livenessHasBeenProved)
2681         return;
2682     
2683     // Now check all of our weak references. If all of them are live, then we
2684     // have proved liveness and so we scan our strong references. If at end of
2685     // GC we still have not proved liveness, then this code block is toast.
2686     bool allAreLiveSoFar = true;
2687     for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
2688         if (!Heap::isMarked(dfgCommon->weakReferences[i].get())) {
2689             allAreLiveSoFar = false;
2690             break;
2691         }
2692     }
2693     if (allAreLiveSoFar) {
2694         for (unsigned i = 0; i < dfgCommon->weakStructureReferences.size(); ++i) {
2695             if (!Heap::isMarked(dfgCommon->weakStructureReferences[i].get())) {
2696                 allAreLiveSoFar = false;
2697                 break;
2698             }
2699         }
2700     }
2701     
2702     // If some weak references are dead, then this fixpoint iteration was
2703     // unsuccessful.
2704     if (!allAreLiveSoFar)
2705         return;
2706     
2707     // All weak references are live. Record this information so we don't
2708     // come back here again, and scan the strong references.
2709     dfgCommon->livenessHasBeenProved = true;
2710     visitor.appendUnbarrieredReadOnlyPointer(this);
2711 #endif // ENABLE(DFG_JIT)
2712 }
2713
2714 void CodeBlock::WeakReferenceHarvester::visitWeakReferences(SlotVisitor& visitor)
2715 {
2716     CodeBlock* codeBlock =
2717         bitwise_cast<CodeBlock*>(
2718             bitwise_cast<char*>(this) - OBJECT_OFFSETOF(CodeBlock, m_weakReferenceHarvester));
2719
2720     codeBlock->propagateTransitions(visitor);
2721     codeBlock->determineLiveness(visitor);
2722 }
2723
2724 void CodeBlock::finalizeLLIntInlineCaches()
2725 {
2726 #if ENABLE(WEBASSEMBLY)
2727     if (m_ownerExecutable->isWebAssemblyExecutable())
2728         return;
2729 #endif
2730
2731     Interpreter* interpreter = m_vm->interpreter;
2732     const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
2733     for (size_t size = propertyAccessInstructions.size(), i = 0; i < size; ++i) {
2734         Instruction* curInstruction = &instructions()[propertyAccessInstructions[i]];
2735         switch (interpreter->getOpcodeID(curInstruction[0].u.opcode)) {
2736         case op_get_by_id: {
2737             StructureID oldStructureID = curInstruction[4].u.structureID;
2738             if (!oldStructureID || Heap::isMarked(m_vm->heap.structureIDTable().get(oldStructureID)))
2739                 break;
2740             if (Options::verboseOSR())
2741                 dataLogF("Clearing LLInt property access.\n");
2742             curInstruction[4].u.structureID = 0;
2743             curInstruction[5].u.operand = 0;
2744             break;
2745         }
2746         case op_put_by_id: {
2747             StructureID oldStructureID = curInstruction[4].u.structureID;
2748             StructureID newStructureID = curInstruction[6].u.structureID;
2749             StructureChain* chain = curInstruction[7].u.structureChain.get();
2750             if ((!oldStructureID || Heap::isMarked(m_vm->heap.structureIDTable().get(oldStructureID))) &&
2751                 (!newStructureID || Heap::isMarked(m_vm->heap.structureIDTable().get(newStructureID))) &&
2752                 (!chain || Heap::isMarked(chain)))
2753                 break;
2754             if (Options::verboseOSR())
2755                 dataLogF("Clearing LLInt put transition.\n");
2756             curInstruction[4].u.structureID = 0;
2757             curInstruction[5].u.operand = 0;
2758             curInstruction[6].u.structureID = 0;
2759             curInstruction[7].u.structureChain.clear();
2760             break;
2761         }
2762         case op_get_array_length:
2763             break;
2764         case op_to_this:
2765             if (!curInstruction[2].u.structure || Heap::isMarked(curInstruction[2].u.structure.get()))
2766                 break;
2767             if (Options::verboseOSR())
2768                 dataLogF("Clearing LLInt to_this with structure %p.\n", curInstruction[2].u.structure.get());
2769             curInstruction[2].u.structure.clear();
2770             curInstruction[3].u.toThisStatus = merge(
2771                 curInstruction[3].u.toThisStatus, ToThisClearedByGC);
2772             break;
2773         case op_create_this: {
2774             auto& cacheWriteBarrier = curInstruction[4].u.jsCell;
2775             if (!cacheWriteBarrier || cacheWriteBarrier.unvalidatedGet() == JSCell::seenMultipleCalleeObjects())
2776                 break;
2777             JSCell* cachedFunction = cacheWriteBarrier.get();
2778             if (Heap::isMarked(cachedFunction))
2779                 break;
2780             if (Options::verboseOSR())
2781                 dataLogF("Clearing LLInt create_this with cached callee %p.\n", cachedFunction);
2782             cacheWriteBarrier.clear();
2783             break;
2784         }
2785         case op_resolve_scope: {
2786             // Right now this isn't strictly necessary. Any symbol tables that this will refer to
2787             // are for outer functions, and we refer to those functions strongly, and they refer
2788             // to the symbol table strongly. But it's nice to be on the safe side.
2789             WriteBarrierBase<SymbolTable>& symbolTable = curInstruction[6].u.symbolTable;
2790             if (!symbolTable || Heap::isMarked(symbolTable.get()))
2791                 break;
2792             if (Options::verboseOSR())
2793                 dataLogF("Clearing dead symbolTable %p.\n", symbolTable.get());
2794             symbolTable.clear();
2795             break;
2796         }
2797         case op_get_from_scope:
2798         case op_put_to_scope: {
2799             GetPutInfo getPutInfo = GetPutInfo(curInstruction[4].u.operand);
2800             if (getPutInfo.resolveType() == GlobalVar || getPutInfo.resolveType() == GlobalVarWithVarInjectionChecks 
2801                 || getPutInfo.resolveType() == LocalClosureVar || getPutInfo.resolveType() == GlobalLexicalVar || getPutInfo.resolveType() == GlobalLexicalVarWithVarInjectionChecks)
2802                 continue;
2803             WriteBarrierBase<Structure>& structure = curInstruction[5].u.structure;
2804             if (!structure || Heap::isMarked(structure.get()))
2805                 break;
2806             if (Options::verboseOSR())
2807                 dataLogF("Clearing scope access with structure %p.\n", structure.get());
2808             structure.clear();
2809             break;
2810         }
2811         default:
2812             OpcodeID opcodeID = interpreter->getOpcodeID(curInstruction[0].u.opcode);
2813             ASSERT_WITH_MESSAGE_UNUSED(opcodeID, false, "Unhandled opcode in CodeBlock::finalizeUnconditionally, %s(%d) at bc %u", opcodeNames[opcodeID], opcodeID, propertyAccessInstructions[i]);
2814         }
2815     }
2816
2817     for (unsigned i = 0; i < m_llintCallLinkInfos.size(); ++i) {
2818         if (m_llintCallLinkInfos[i].isLinked() && !Heap::isMarked(m_llintCallLinkInfos[i].callee.get())) {
2819             if (Options::verboseOSR())
2820                 dataLog("Clearing LLInt call from ", *this, "\n");
2821             m_llintCallLinkInfos[i].unlink();
2822         }
2823         if (!!m_llintCallLinkInfos[i].lastSeenCallee && !Heap::isMarked(m_llintCallLinkInfos[i].lastSeenCallee.get()))
2824             m_llintCallLinkInfos[i].lastSeenCallee.clear();
2825     }
2826 }
2827
2828 void CodeBlock::finalizeBaselineJITInlineCaches()
2829 {
2830 #if ENABLE(JIT)
2831     for (auto iter = callLinkInfosBegin(); !!iter; ++iter)
2832         (*iter)->visitWeak(*vm());
2833
2834     for (Bag<StructureStubInfo>::iterator iter = m_stubInfos.begin(); !!iter; ++iter) {
2835         StructureStubInfo& stubInfo = **iter;
2836         stubInfo.visitWeakReferences(this);
2837     }
2838 #endif
2839 }
2840
2841 void CodeBlock::UnconditionalFinalizer::finalizeUnconditionally()
2842 {
2843     CodeBlock* codeBlock = bitwise_cast<CodeBlock*>(
2844         bitwise_cast<char*>(this) - OBJECT_OFFSETOF(CodeBlock, m_unconditionalFinalizer));
2845
2846 #if ENABLE(DFG_JIT)
2847     if (codeBlock->shouldJettisonDueToWeakReference()) {
2848         codeBlock->jettison(Profiler::JettisonDueToWeakReference);
2849         return;
2850     }
2851 #endif // ENABLE(DFG_JIT)
2852
2853     if (codeBlock->shouldJettisonDueToOldAge()) {
2854         codeBlock->jettison(Profiler::JettisonDueToOldAge);
2855         return;
2856     }
2857
2858     if (JITCode::couldBeInterpreted(codeBlock->jitType()))
2859         codeBlock->finalizeLLIntInlineCaches();
2860
2861 #if ENABLE(JIT)
2862     if (!!codeBlock->jitCode())
2863         codeBlock->finalizeBaselineJITInlineCaches();
2864 #endif
2865 }
2866
2867 void CodeBlock::getStubInfoMap(const ConcurrentJITLocker&, StubInfoMap& result)
2868 {
2869 #if ENABLE(JIT)
2870     toHashMap(m_stubInfos, getStructureStubInfoCodeOrigin, result);
2871 #else
2872     UNUSED_PARAM(result);
2873 #endif
2874 }
2875
2876 void CodeBlock::getStubInfoMap(StubInfoMap& result)
2877 {
2878     ConcurrentJITLocker locker(m_lock);
2879     getStubInfoMap(locker, result);
2880 }
2881
2882 void CodeBlock::getCallLinkInfoMap(const ConcurrentJITLocker&, CallLinkInfoMap& result)
2883 {
2884 #if ENABLE(JIT)
2885     toHashMap(m_callLinkInfos, getCallLinkInfoCodeOrigin, result);
2886 #else
2887     UNUSED_PARAM(result);
2888 #endif
2889 }
2890
2891 void CodeBlock::getCallLinkInfoMap(CallLinkInfoMap& result)
2892 {
2893     ConcurrentJITLocker locker(m_lock);
2894     getCallLinkInfoMap(locker, result);
2895 }
2896
2897 void CodeBlock::getByValInfoMap(const ConcurrentJITLocker&, ByValInfoMap& result)
2898 {
2899 #if ENABLE(JIT)
2900     for (auto* byValInfo : m_byValInfos)
2901         result.add(CodeOrigin(byValInfo->bytecodeIndex), byValInfo);
2902 #else
2903     UNUSED_PARAM(result);
2904 #endif
2905 }
2906
2907 void CodeBlock::getByValInfoMap(ByValInfoMap& result)
2908 {
2909     ConcurrentJITLocker locker(m_lock);
2910     getByValInfoMap(locker, result);
2911 }
2912
2913 #if ENABLE(JIT)
2914 StructureStubInfo* CodeBlock::addStubInfo(AccessType accessType)
2915 {
2916     ConcurrentJITLocker locker(m_lock);
2917     return m_stubInfos.add(accessType);
2918 }
2919
2920 StructureStubInfo* CodeBlock::findStubInfo(CodeOrigin codeOrigin)
2921 {
2922     for (StructureStubInfo* stubInfo : m_stubInfos) {
2923         if (stubInfo->codeOrigin == codeOrigin)
2924             return stubInfo;
2925     }
2926     return nullptr;
2927 }
2928
2929 ByValInfo* CodeBlock::addByValInfo()
2930 {
2931     ConcurrentJITLocker locker(m_lock);
2932     return m_byValInfos.add();
2933 }
2934
2935 CallLinkInfo* CodeBlock::addCallLinkInfo()
2936 {
2937     ConcurrentJITLocker locker(m_lock);
2938     return m_callLinkInfos.add();
2939 }
2940
2941 CallLinkInfo* CodeBlock::getCallLinkInfoForBytecodeIndex(unsigned index)
2942 {
2943     for (auto iter = m_callLinkInfos.begin(); !!iter; ++iter) {
2944         if ((*iter)->codeOrigin() == CodeOrigin(index))
2945             return *iter;
2946     }
2947     return nullptr;
2948 }
2949 #endif
2950
2951 void CodeBlock::visitOSRExitTargets(SlotVisitor& visitor)
2952 {
2953     // We strongly visit OSR exits targets because we don't want to deal with
2954     // the complexity of generating an exit target CodeBlock on demand and
2955     // guaranteeing that it matches the details of the CodeBlock we compiled
2956     // the OSR exit against.
2957
2958     visitor.append(&m_alternative);
2959
2960 #if ENABLE(DFG_JIT)
2961     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2962     if (dfgCommon->inlineCallFrames) {
2963         for (auto* inlineCallFrame : *dfgCommon->inlineCallFrames) {
2964             ASSERT(inlineCallFrame->baselineCodeBlock);
2965             visitor.append(&inlineCallFrame->baselineCodeBlock);
2966         }
2967     }
2968 #endif
2969 }
2970
2971 void CodeBlock::stronglyVisitStrongReferences(SlotVisitor& visitor)
2972 {
2973     visitor.append(&m_globalObject);
2974     visitor.append(&m_ownerExecutable);
2975     visitor.append(&m_unlinkedCode);
2976     if (m_rareData)
2977         m_rareData->m_evalCodeCache.visitAggregate(visitor);
2978     visitor.appendValues(m_constantRegisters.data(), m_constantRegisters.size());
2979     for (size_t i = 0; i < m_functionExprs.size(); ++i)
2980         visitor.append(&m_functionExprs[i]);
2981     for (size_t i = 0; i < m_functionDecls.size(); ++i)
2982         visitor.append(&m_functionDecls[i]);
2983     for (unsigned i = 0; i < m_objectAllocationProfiles.size(); ++i)
2984         m_objectAllocationProfiles[i].visitAggregate(visitor);
2985
2986 #if ENABLE(DFG_JIT)
2987     if (JITCode::isOptimizingJIT(jitType()))
2988         visitOSRExitTargets(visitor);
2989 #endif
2990
2991     updateAllPredictions();
2992 }
2993
2994 void CodeBlock::stronglyVisitWeakReferences(SlotVisitor& visitor)
2995 {
2996     UNUSED_PARAM(visitor);
2997
2998 #if ENABLE(DFG_JIT)
2999     if (!JITCode::isOptimizingJIT(jitType()))
3000         return;
3001     
3002     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
3003
3004     for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
3005         if (!!dfgCommon->transitions[i].m_codeOrigin)
3006             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.
3007         visitor.append(&dfgCommon->transitions[i].m_from);
3008         visitor.append(&dfgCommon->transitions[i].m_to);
3009     }
3010     
3011     for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i)
3012         visitor.append(&dfgCommon->weakReferences[i]);
3013
3014     for (unsigned i = 0; i < dfgCommon->weakStructureReferences.size(); ++i)
3015         visitor.append(&dfgCommon->weakStructureReferences[i]);
3016
3017     dfgCommon->livenessHasBeenProved = true;
3018 #endif    
3019 }
3020
3021 CodeBlock* CodeBlock::baselineAlternative()
3022 {
3023 #if ENABLE(JIT)
3024     CodeBlock* result = this;
3025     while (result->alternative())
3026         result = result->alternative();
3027     RELEASE_ASSERT(result);
3028     RELEASE_ASSERT(JITCode::isBaselineCode(result->jitType()) || result->jitType() == JITCode::None);
3029     return result;
3030 #else
3031     return this;
3032 #endif
3033 }
3034
3035 CodeBlock* CodeBlock::baselineVersion()
3036 {
3037 #if ENABLE(JIT)
3038     if (JITCode::isBaselineCode(jitType()))
3039         return this;
3040     CodeBlock* result = replacement();
3041     if (!result) {
3042         // This can happen if we're creating the original CodeBlock for an executable.
3043         // Assume that we're the baseline CodeBlock.
3044         RELEASE_ASSERT(jitType() == JITCode::None);
3045         return this;
3046     }
3047     result = result->baselineAlternative();
3048     return result;
3049 #else
3050     return this;
3051 #endif
3052 }
3053
3054 #if ENABLE(JIT)
3055 bool CodeBlock::hasOptimizedReplacement(JITCode::JITType typeToReplace)
3056 {
3057     return JITCode::isHigherTier(replacement()->jitType(), typeToReplace);
3058 }
3059
3060 bool CodeBlock::hasOptimizedReplacement()
3061 {
3062     return hasOptimizedReplacement(jitType());
3063 }
3064 #endif
3065
3066 HandlerInfo* CodeBlock::handlerForBytecodeOffset(unsigned bytecodeOffset, RequiredHandler requiredHandler)
3067 {
3068     RELEASE_ASSERT(bytecodeOffset < instructions().size());
3069     return handlerForIndex(bytecodeOffset, requiredHandler);
3070 }
3071
3072 HandlerInfo* CodeBlock::handlerForIndex(unsigned index, RequiredHandler requiredHandler)
3073 {
3074     if (!m_rareData)
3075         return 0;
3076     
3077     Vector<HandlerInfo>& exceptionHandlers = m_rareData->m_exceptionHandlers;
3078     for (size_t i = 0; i < exceptionHandlers.size(); ++i) {
3079         HandlerInfo& handler = exceptionHandlers[i];
3080         if ((requiredHandler == RequiredHandler::CatchHandler) && !handler.isCatchHandler())
3081             continue;
3082
3083         // Handlers are ordered innermost first, so the first handler we encounter
3084         // that contains the source address is the correct handler to use.
3085         // This index used is either the BytecodeOffset or a CallSiteIndex.
3086         if (handler.start <= index && handler.end > index)
3087             return &handler;
3088     }
3089
3090     return 0;
3091 }
3092
3093 CallSiteIndex CodeBlock::newExceptionHandlingCallSiteIndex(CallSiteIndex originalCallSite)
3094 {
3095 #if ENABLE(DFG_JIT)
3096     RELEASE_ASSERT(JITCode::isOptimizingJIT(jitType()));
3097     RELEASE_ASSERT(canGetCodeOrigin(originalCallSite));
3098     ASSERT(!!handlerForIndex(originalCallSite.bits()));
3099     CodeOrigin originalOrigin = codeOrigin(originalCallSite);
3100     return m_jitCode->dfgCommon()->addUniqueCallSiteIndex(originalOrigin);
3101 #else
3102     // We never create new on-the-fly exception handling
3103     // call sites outside the DFG/FTL inline caches.
3104     UNUSED_PARAM(originalCallSite);
3105     RELEASE_ASSERT_NOT_REACHED();
3106     return CallSiteIndex(0u);
3107 #endif
3108 }
3109
3110 void CodeBlock::removeExceptionHandlerForCallSite(CallSiteIndex callSiteIndex)
3111 {
3112     RELEASE_ASSERT(m_rareData);
3113     Vector<HandlerInfo>& exceptionHandlers = m_rareData->m_exceptionHandlers;
3114     unsigned index = callSiteIndex.bits();
3115     for (size_t i = 0; i < exceptionHandlers.size(); ++i) {
3116         HandlerInfo& handler = exceptionHandlers[i];
3117         if (handler.start <= index && handler.end > index) {
3118             exceptionHandlers.remove(i);
3119             return;
3120         }
3121     }
3122
3123     RELEASE_ASSERT_NOT_REACHED();
3124 }
3125
3126 unsigned CodeBlock::lineNumberForBytecodeOffset(unsigned bytecodeOffset)
3127 {
3128     RELEASE_ASSERT(bytecodeOffset < instructions().size());
3129     return ownerScriptExecutable()->firstLine() + m_unlinkedCode->lineNumberForBytecodeOffset(bytecodeOffset);
3130 }
3131
3132 unsigned CodeBlock::columnNumberForBytecodeOffset(unsigned bytecodeOffset)
3133 {
3134     int divot;
3135     int startOffset;
3136     int endOffset;
3137     unsigned line;
3138     unsigned column;
3139     expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
3140     return column;
3141 }
3142
3143 void CodeBlock::expressionRangeForBytecodeOffset(unsigned bytecodeOffset, int& divot, int& startOffset, int& endOffset, unsigned& line, unsigned& column)
3144 {
3145     m_unlinkedCode->expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
3146     divot += m_sourceOffset;
3147     column += line ? 1 : firstLineColumnOffset();
3148     line += ownerScriptExecutable()->firstLine();
3149 }
3150
3151 bool CodeBlock::hasOpDebugForLineAndColumn(unsigned line, unsigned column)
3152 {
3153     Interpreter* interpreter = vm()->interpreter;
3154     const Instruction* begin = instructions().begin();
3155     const Instruction* end = instructions().end();
3156     for (const Instruction* it = begin; it != end;) {
3157         OpcodeID opcodeID = interpreter->getOpcodeID(it->u.opcode);
3158         if (opcodeID == op_debug) {
3159             unsigned bytecodeOffset = it - begin;
3160             int unused;
3161             unsigned opDebugLine;
3162             unsigned opDebugColumn;
3163             expressionRangeForBytecodeOffset(bytecodeOffset, unused, unused, unused, opDebugLine, opDebugColumn);
3164             if (line == opDebugLine && (column == Breakpoint::unspecifiedColumn || column == opDebugColumn))
3165                 return true;
3166         }
3167         it += opcodeLengths[opcodeID];
3168     }
3169     return false;
3170 }
3171
3172 void CodeBlock::shrinkToFit(ShrinkMode shrinkMode)
3173 {
3174     m_rareCaseProfiles.shrinkToFit();
3175     m_resultProfiles.shrinkToFit();
3176     
3177     if (shrinkMode == EarlyShrink) {
3178         m_constantRegisters.shrinkToFit();
3179         m_constantsSourceCodeRepresentation.shrinkToFit();
3180         
3181         if (m_rareData) {
3182             m_rareData->m_switchJumpTables.shrinkToFit();
3183             m_rareData->m_stringSwitchJumpTables.shrinkToFit();
3184             m_rareData->m_liveCalleeLocalsAtYield.shrinkToFit();
3185         }
3186     } // else don't shrink these, because we would have already pointed pointers into these tables.
3187 }
3188
3189 #if ENABLE(JIT)
3190 void CodeBlock::linkIncomingCall(ExecState* callerFrame, CallLinkInfo* incoming)
3191 {
3192     noticeIncomingCall(callerFrame);
3193     m_incomingCalls.push(incoming);
3194 }
3195
3196 void CodeBlock::linkIncomingPolymorphicCall(ExecState* callerFrame, PolymorphicCallNode* incoming)
3197 {
3198     noticeIncomingCall(callerFrame);
3199     m_incomingPolymorphicCalls.push(incoming);
3200 }
3201 #endif // ENABLE(JIT)
3202
3203 void CodeBlock::unlinkIncomingCalls()
3204 {
3205     while (m_incomingLLIntCalls.begin() != m_incomingLLIntCalls.end())
3206         m_incomingLLIntCalls.begin()->unlink();
3207 #if ENABLE(JIT)
3208     while (m_incomingCalls.begin() != m_incomingCalls.end())
3209         m_incomingCalls.begin()->unlink(*vm());
3210     while (m_incomingPolymorphicCalls.begin() != m_incomingPolymorphicCalls.end())
3211         m_incomingPolymorphicCalls.begin()->unlink(*vm());
3212 #endif // ENABLE(JIT)
3213 }
3214
3215 void CodeBlock::linkIncomingCall(ExecState* callerFrame, LLIntCallLinkInfo* incoming)
3216 {
3217     noticeIncomingCall(callerFrame);
3218     m_incomingLLIntCalls.push(incoming);
3219 }
3220
3221 CodeBlock* CodeBlock::newReplacement()
3222 {
3223     return ownerScriptExecutable()->newReplacementCodeBlockFor(specializationKind());
3224 }
3225
3226 #if ENABLE(JIT)
3227 CodeBlock* CodeBlock::replacement()
3228 {
3229     const ClassInfo* classInfo = this->classInfo();
3230
3231     if (classInfo == FunctionCodeBlock::info())
3232         return jsCast<FunctionExecutable*>(ownerExecutable())->codeBlockFor(m_isConstructor ? CodeForConstruct : CodeForCall);
3233
3234     if (classInfo == EvalCodeBlock::info())
3235         return jsCast<EvalExecutable*>(ownerExecutable())->codeBlock();
3236
3237     if (classInfo == ProgramCodeBlock::info())
3238         return jsCast<ProgramExecutable*>(ownerExecutable())->codeBlock();
3239
3240     if (classInfo == ModuleProgramCodeBlock::info())
3241         return jsCast<ModuleProgramExecutable*>(ownerExecutable())->codeBlock();
3242
3243 #if ENABLE(WEBASSEMBLY)
3244     if (classInfo == WebAssemblyCodeBlock::info())
3245         return nullptr;
3246 #endif
3247
3248     RELEASE_ASSERT_NOT_REACHED();
3249     return nullptr;
3250 }
3251
3252 DFG::CapabilityLevel CodeBlock::computeCapabilityLevel()
3253 {
3254     const ClassInfo* classInfo = this->classInfo();
3255
3256     if (classInfo == FunctionCodeBlock::info()) {
3257         if (m_isConstructor)
3258             return DFG::functionForConstructCapabilityLevel(this);
3259         return DFG::functionForCallCapabilityLevel(this);
3260     }
3261
3262     if (classInfo == EvalCodeBlock::info())
3263         return DFG::evalCapabilityLevel(this);
3264
3265     if (classInfo == ProgramCodeBlock::info())
3266         return DFG::programCapabilityLevel(this);
3267
3268     if (classInfo == ModuleProgramCodeBlock::info())
3269         return DFG::programCapabilityLevel(this);
3270
3271 #if ENABLE(WEBASSEMBLY)
3272     if (classInfo == WebAssemblyCodeBlock::info())
3273         return DFG::CannotCompile;
3274 #endif
3275
3276     RELEASE_ASSERT_NOT_REACHED();
3277     return DFG::CannotCompile;
3278 }
3279
3280 #endif // ENABLE(JIT)
3281
3282 void CodeBlock::jettison(Profiler::JettisonReason reason, ReoptimizationMode mode, const FireDetail* detail)
3283 {
3284 #if !ENABLE(DFG_JIT)
3285     UNUSED_PARAM(mode);
3286     UNUSED_PARAM(detail);
3287 #endif
3288
3289     RELEASE_ASSERT(reason != Profiler::NotJettisoned);
3290     
3291 #if ENABLE(DFG_JIT)
3292     if (DFG::shouldDumpDisassembly()) {
3293         dataLog("Jettisoning ", *this);
3294         if (mode == CountReoptimization)
3295             dataLog(" and counting reoptimization");
3296         dataLog(" due to ", reason);
3297         if (detail)
3298             dataLog(", ", *detail);
3299         dataLog(".\n");
3300     }
3301     
3302     if (reason == Profiler::JettisonDueToWeakReference) {
3303         if (DFG::shouldDumpDisassembly()) {
3304             dataLog(*this, " will be jettisoned because of the following dead references:\n");
3305             DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
3306             for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
3307                 DFG::WeakReferenceTransition& transition = dfgCommon->transitions[i];
3308                 JSCell* origin = transition.m_codeOrigin.get();
3309                 JSCell* from = transition.m_from.get();
3310                 JSCell* to = transition.m_to.get();
3311                 if ((!origin || Heap::isMarked(origin)) && Heap::isMarked(from))
3312                     continue;
3313                 dataLog("    Transition under ", RawPointer(origin), ", ", RawPointer(from), " -> ", RawPointer(to), ".\n");
3314             }
3315             for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
3316                 JSCell* weak = dfgCommon->weakReferences[i].get();
3317                 if (Heap::isMarked(weak))
3318                     continue;
3319                 dataLog("    Weak reference ", RawPointer(weak), ".\n");
3320             }
3321         }
3322     }
3323 #endif // ENABLE(DFG_JIT)
3324
3325     DeferGCForAWhile deferGC(*heap());
3326     
3327     // We want to accomplish two things here:
3328     // 1) Make sure that if this CodeBlock is on the stack right now, then if we return to it
3329     //    we should OSR exit at the top of the next bytecode instruction after the return.
3330     // 2) Make sure that if we call the owner executable, then we shouldn't call this CodeBlock.
3331
3332 #if ENABLE(DFG_JIT)
3333     if (reason != Profiler::JettisonDueToOldAge) {
3334         if (Profiler::Compilation* compilation = jitCode()->dfgCommon()->compilation.get())
3335             compilation->setJettisonReason(reason, detail);
3336         
3337         // This accomplishes (1), and does its own book-keeping about whether it has already happened.
3338         if (!jitCode()->dfgCommon()->invalidate()) {
3339             // We've already been invalidated.
3340             RELEASE_ASSERT(this != replacement());
3341             return;
3342         }
3343     }
3344     
3345     if (DFG::shouldDumpDisassembly())
3346         dataLog("    Did invalidate ", *this, "\n");
3347     
3348     // Count the reoptimization if that's what the user wanted.
3349     if (mode == CountReoptimization) {
3350         // FIXME: Maybe this should call alternative().
3351         // https://bugs.webkit.org/show_bug.cgi?id=123677
3352         baselineAlternative()->countReoptimization();
3353         if (DFG::shouldDumpDisassembly())
3354             dataLog("    Did count reoptimization for ", *this, "\n");
3355     }
3356     
3357     if (this != replacement()) {
3358         // This means that we were never the entrypoint. This can happen for OSR entry code
3359         // blocks.
3360         return;
3361     }
3362
3363     if (alternative())
3364         alternative()->optimizeAfterWarmUp();
3365
3366     if (reason != Profiler::JettisonDueToOldAge)
3367         tallyFrequentExitSites();
3368 #endif // ENABLE(DFG_JIT)
3369
3370     // This accomplishes (2).
3371     ownerScriptExecutable()->installCode(
3372         m_globalObject->vm(), alternative(), codeType(), specializationKind());
3373
3374 #if ENABLE(DFG_JIT)
3375     if (DFG::shouldDumpDisassembly())
3376         dataLog("    Did install baseline version of ", *this, "\n");
3377 #endif // ENABLE(DFG_JIT)
3378 }
3379
3380 JSGlobalObject* CodeBlock::globalObjectFor(CodeOrigin codeOrigin)
3381 {
3382     if (!codeOrigin.inlineCallFrame)
3383         return globalObject();
3384     return codeOrigin.inlineCallFrame->baselineCodeBlock->globalObject();
3385 }
3386
3387 class RecursionCheckFunctor {
3388 public:
3389     RecursionCheckFunctor(CallFrame* startCallFrame, CodeBlock* codeBlock, unsigned depthToCheck)
3390         : m_startCallFrame(startCallFrame)
3391         , m_codeBlock(codeBlock)
3392         , m_depthToCheck(depthToCheck)
3393         , m_foundStartCallFrame(false)
3394         , m_didRecurse(false)
3395     { }
3396
3397     StackVisitor::Status operator()(StackVisitor& visitor) const
3398     {
3399         CallFrame* currentCallFrame = visitor->callFrame();
3400
3401         if (currentCallFrame == m_startCallFrame)
3402             m_foundStartCallFrame = true;
3403
3404         if (m_foundStartCallFrame) {
3405             if (visitor->callFrame()->codeBlock() == m_codeBlock) {
3406                 m_didRecurse = true;
3407                 return StackVisitor::Done;
3408             }
3409
3410             if (!m_depthToCheck--)
3411                 return StackVisitor::Done;
3412         }
3413
3414         return StackVisitor::Continue;
3415     }
3416
3417     bool didRecurse() const { return m_didRecurse; }
3418
3419 private:
3420     CallFrame* m_startCallFrame;
3421     CodeBlock* m_codeBlock;
3422     mutable unsigned m_depthToCheck;
3423     mutable bool m_foundStartCallFrame;
3424     mutable bool m_didRecurse;
3425 };
3426
3427 void CodeBlock::noticeIncomingCall(ExecState* callerFrame)
3428 {
3429     CodeBlock* callerCodeBlock = callerFrame->codeBlock();
3430     
3431     if (Options::verboseCallLink())
3432         dataLog("Noticing call link from ", pointerDump(callerCodeBlock), " to ", *this, "\n");
3433     
3434 #if ENABLE(DFG_JIT)
3435     if (!m_shouldAlwaysBeInlined)
3436         return;
3437     
3438     if (!callerCodeBlock) {
3439         m_shouldAlwaysBeInlined = false;
3440         if (Options::verboseCallLink())
3441             dataLog("    Clearing SABI because caller is native.\n");
3442         return;
3443     }
3444
3445     if (!hasBaselineJITProfiling())
3446         return;
3447
3448     if (!DFG::mightInlineFunction(this))
3449         return;
3450
3451     if (!canInline(capabilityLevelState()))
3452         return;
3453     
3454     if (!DFG::isSmallEnoughToInlineCodeInto(callerCodeBlock)) {
3455         m_shouldAlwaysBeInlined = false;
3456         if (Options::verboseCallLink())
3457             dataLog("    Clearing SABI because caller is too large.\n");
3458         return;
3459     }
3460
3461     if (callerCodeBlock->jitType() == JITCode::InterpreterThunk) {
3462         // If the caller is still in the interpreter, then we can't expect inlining to
3463         // happen anytime soon. Assume it's profitable to optimize it separately. This
3464         // ensures that a function is SABI only if it is called no more frequently than
3465         // any of its callers.
3466         m_shouldAlwaysBeInlined = false;
3467         if (Options::verboseCallLink())
3468             dataLog("    Clearing SABI because caller is in LLInt.\n");
3469         return;
3470     }
3471     
3472     if (JITCode::isOptimizingJIT(callerCodeBlock->jitType())) {
3473         m_shouldAlwaysBeInlined = false;
3474         if (Options::verboseCallLink())
3475             dataLog("    Clearing SABI bcause caller was already optimized.\n");
3476         return;
3477     }
3478     
3479     if (callerCodeBlock->codeType() != FunctionCode) {
3480         // If the caller is either eval or global code, assume that that won't be
3481         // optimized anytime soon. For eval code this is particularly true since we
3482         // delay eval optimization by a *lot*.
3483         m_shouldAlwaysBeInlined = false;
3484         if (Options::verboseCallLink())
3485             dataLog("    Clearing SABI because caller is not a function.\n");
3486         return;
3487     }
3488
3489     // Recursive calls won't be inlined.
3490     RecursionCheckFunctor functor(callerFrame, this, Options::maximumInliningDepth());
3491     vm()->topCallFrame->iterate(functor);
3492
3493     if (functor.didRecurse()) {
3494         if (Options::verboseCallLink())
3495             dataLog("    Clearing SABI because recursion was detected.\n");
3496         m_shouldAlwaysBeInlined = false;
3497         return;
3498     }
3499     
3500     if (callerCodeBlock->capabilityLevelState() == DFG::CapabilityLevelNotSet) {
3501         dataLog("In call from ", *callerCodeBlock, " ", callerFrame->codeOrigin(), " to ", *this, ": caller's DFG capability level is not set.\n");
3502         CRASH();
3503     }
3504     
3505     if (canCompile(callerCodeBlock->capabilityLevelState()))
3506         return;
3507     
3508     if (Options::verboseCallLink())
3509         dataLog("    Clearing SABI because the caller is not a DFG candidate.\n");
3510     
3511     m_shouldAlwaysBeInlined = false;
3512 #endif
3513 }
3514
3515 unsigned CodeBlock::reoptimizationRetryCounter() const
3516 {
3517 #if ENABLE(JIT)
3518     ASSERT(m_reoptimizationRetryCounter <= Options::reoptimizationRetryCounterMax());
3519     return m_reoptimizationRetryCounter;
3520 #else
3521     return 0;
3522 #endif // ENABLE(JIT)
3523 }
3524
3525 #if ENABLE(JIT)
3526 void CodeBlock::setCalleeSaveRegisters(RegisterSet calleeSaveRegisters)
3527 {
3528     m_calleeSaveRegisters = std::make_unique<RegisterAtOffsetList>(calleeSaveRegisters);
3529 }
3530
3531 void CodeBlock::setCalleeSaveRegisters(std::unique_ptr<RegisterAtOffsetList> registerAtOffsetList)
3532 {
3533     m_calleeSaveRegisters = WTFMove(registerAtOffsetList);
3534 }
3535     
3536 static size_t roundCalleeSaveSpaceAsVirtualRegisters(size_t calleeSaveRegisters)
3537 {
3538     static const unsigned cpuRegisterSize = sizeof(void*);
3539     return (WTF::roundUpToMultipleOf(sizeof(Register), calleeSaveRegisters * cpuRegisterSize) / sizeof(Register));
3540
3541 }
3542
3543 size_t CodeBlock::llintBaselineCalleeSaveSpaceAsVirtualRegisters()
3544 {
3545     return roundCalleeSaveSpaceAsVirtualRegisters(numberOfLLIntBaselineCalleeSaveRegisters());
3546 }
3547
3548 size_t CodeBlock::calleeSaveSpaceAsVirtualRegisters()
3549 {
3550     return roundCalleeSaveSpaceAsVirtualRegisters(m_calleeSaveRegisters->size());
3551 }
3552
3553 void CodeBlock::countReoptimization()
3554 {
3555     m_reoptimizationRetryCounter++;
3556     if (m_reoptimizationRetryCounter > Options::reoptimizationRetryCounterMax())
3557         m_reoptimizationRetryCounter = Options::reoptimizationRetryCounterMax();
3558 }
3559
3560 unsigned CodeBlock::numberOfDFGCompiles()
3561 {
3562     ASSERT(JITCode::isBaselineCode(jitType()));
3563     if (Options::testTheFTL()) {
3564         if (m_didFailFTLCompilation)
3565             return 1000000;
3566         return (m_hasBeenCompiledWithFTL ? 1 : 0) + m_reoptimizationRetryCounter;
3567     }
3568     return (JITCode::isOptimizingJIT(replacement()->jitType()) ? 1 : 0) + m_reoptimizationRetryCounter;
3569 }
3570
3571 int32_t CodeBlock::codeTypeThresholdMultiplier() const
3572 {
3573     if (codeType() == EvalCode)
3574         return Options::evalThresholdMultiplier();
3575     
3576     return 1;
3577 }
3578
3579 double CodeBlock::optimizationThresholdScalingFactor()
3580 {
3581     // This expression arises from doing a least-squares fit of
3582     //
3583     // F[x_] =: a * Sqrt[x + b] + Abs[c * x] + d
3584     //
3585     // against the data points:
3586     //
3587     //    x       F[x_]
3588     //    10       0.9          (smallest reasonable code block)
3589     //   200       1.0          (typical small-ish code block)
3590     //   320       1.2          (something I saw in 3d-cube that I wanted to optimize)
3591     //  1268       5.0          (something I saw in 3d-cube that I didn't want to optimize)
3592     //  4000       5.5          (random large size, used to cause the function to converge to a shallow curve of some sort)
3593     // 10000       6.0          (similar to above)
3594     //
3595     // I achieve the minimization using the following Mathematica code:
3596     //
3597     // MyFunctionTemplate[x_, a_, b_, c_, d_] := a*Sqrt[x + b] + Abs[c*x] + d
3598     //
3599     // samples = {{10, 0.9}, {200, 1}, {320, 1.2}, {1268, 5}, {4000, 5.5}, {10000, 6}}
3600     //
3601     // solution = 
3602     //     Minimize[Plus @@ ((MyFunctionTemplate[#[[1]], a, b, c, d] - #[[2]])^2 & /@ samples),
3603     //         {a, b, c, d}][[2]]
3604     //
3605     // And the code below (to initialize a, b, c, d) is generated by:
3606     //
3607     // Print["const double " <> ToString[#[[1]]] <> " = " <>
3608     //     If[#[[2]] < 0.00001, "0.0", ToString[#[[2]]]] <> ";"] & /@ solution
3609     //
3610     // We've long known the following to be true:
3611     // - Small code blocks are cheap to optimize and so we should do it sooner rather
3612     //   than later.
3613     // - Large code blocks are expensive to optimize and so we should postpone doing so,
3614     //   and sometimes have a large enough threshold that we never optimize them.
3615     // - The difference in cost is not totally linear because (a) just invoking the
3616     //   DFG incurs some base cost and (b) for large code blocks there is enough slop
3617     //   in the correlation between instruction count and the actual compilation cost
3618     //   that for those large blocks, the instruction count should not have a strong
3619     //   influence on our threshold.
3620     //
3621     // I knew the goals but I didn't know how to achieve them; so I picked an interesting
3622     // example where the heuristics were right (code block in 3d-cube with instruction
3623     // count 320, which got compiled early as it should have been) and one where they were
3624     // totally wrong (code block in 3d-cube with instruction count 1268, which was expensive
3625     // to compile and didn't run often enough to warrant compilation in my opinion), and
3626     // then threw in additional data points that represented my own guess of what our
3627     // heuristics should do for some round-numbered examples.
3628     //
3629     // The expression to which I decided to fit the data arose because I started with an
3630     // affine function, and then did two things: put the linear part in an Abs to ensure
3631     // that the fit didn't end up choosing a negative value of c (which would result in
3632     // the function turning over and going negative for large x) and I threw in a Sqrt
3633     // term because Sqrt represents my intution that the function should be more sensitive
3634     // to small changes in small values of x, but less sensitive when x gets large.
3635     
3636     // Note that the current fit essentially eliminates the linear portion of the
3637     // expression (c == 0.0).
3638     const double a = 0.061504;
3639     const double b = 1.02406;
3640     const double c = 0.0;
3641     const double d = 0.825914;
3642     
3643     double instructionCount = this->instructionCount();
3644     
3645     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.
3646     
3647     double result = d + a * sqrt(instructionCount + b) + c * instructionCount;
3648     
3649     result *= codeTypeThresholdMultiplier();
3650     
3651     if (Options::verboseOSR()) {
3652         dataLog(
3653             *this, ": instruction count is ", instructionCount,
3654             ", scaling execution counter by ", result, " * ", codeTypeThresholdMultiplier(),
3655             "\n");
3656     }
3657     return result;
3658 }
3659
3660 static int32_t clipThreshold(double threshold)
3661 {
3662     if (threshold < 1.0)
3663         return 1;
3664     
3665     if (threshold > static_cast<double>(std::numeric_limits<int32_t>::max()))
3666         return std::numeric_limits<int32_t>::max();
3667     
3668     return static_cast<int32_t>(threshold);
3669 }
3670
3671 int32_t CodeBlock::adjustedCounterValue(int32_t desiredThreshold)
3672 {
3673     return clipThreshold(
3674         static_cast<double>(desiredThreshold) *
3675         optimizationThresholdScalingFactor() *
3676         (1 << reoptimizationRetryCounter()));
3677 }
3678
3679 bool CodeBlock::checkIfOptimizationThresholdReached()
3680 {
3681 #if ENABLE(DFG_JIT)
3682     if (DFG::Worklist* worklist = DFG::existingGlobalDFGWorklistOrNull()) {
3683         if (worklist->compilationState(DFG::CompilationKey(this, DFG::DFGMode))
3684             == DFG::Worklist::Compiled) {
3685             optimizeNextInvocation();
3686             return true;
3687         }
3688     }
3689 #endif
3690     
3691     return m_jitExecuteCounter.checkIfThresholdCrossedAndSet(this);
3692 }
3693
3694 void CodeBlock::optimizeNextInvocation()
3695 {
3696     if (Options::verboseOSR())
3697         dataLog(*this, ": Optimizing next invocation.\n");
3698     m_jitExecuteCounter.setNewThreshold(0, this);
3699 }
3700
3701 void CodeBlock::dontOptimizeAnytimeSoon()
3702 {
3703     if (Options::verboseOSR())
3704         dataLog(*this, ": Not optimizing anytime soon.\n");
3705     m_jitExecuteCounter.deferIndefinitely();
3706 }
3707
3708 void CodeBlock::optimizeAfterWarmUp()
3709 {
3710     if (Options::verboseOSR())
3711         dataLog(*this, ": Optimizing after warm-up.\n");
3712 #if ENABLE(DFG_JIT)
3713     m_jitExecuteCounter.setNewThreshold(
3714         adjustedCounterValue(Options::thresholdForOptimizeAfterWarmUp()), this);
3715 #endif
3716 }
3717
3718 void CodeBlock::optimizeAfterLongWarmUp()
3719 {
3720     if (Options::verboseOSR())
3721         dataLog(*this, ": Optimizing after long warm-up.\n");
3722 #if ENABLE(DFG_JIT)
3723     m_jitExecuteCounter.setNewThreshold(
3724         adjustedCounterValue(Options::thresholdForOptimizeAfterLongWarmUp()), this);
3725 #endif
3726 }
3727
3728 void CodeBlock::optimizeSoon()
3729 {
3730     if (Options::verboseOSR())
3731         dataLog(*this, ": Optimizing soon.\n");
3732 #if ENABLE(DFG_JIT)
3733     m_jitExecuteCounter.setNewThreshold(
3734         adjustedCounterValue(Options::thresholdForOptimizeSoon()), this);
3735 #endif
3736 }
3737
3738 void CodeBlock::forceOptimizationSlowPathConcurrently()
3739 {
3740     if (Options::verboseOSR())
3741         dataLog(*this, ": Forcing slow path concurrently.\n");
3742     m_jitExecuteCounter.forceSlowPathConcurrently();
3743 }
3744
3745 #if ENABLE(DFG_JIT)
3746 void CodeBlock::setOptimizationThresholdBasedOnCompilationResult(CompilationResult result)
3747 {
3748     JITCode::JITType type = jitType();
3749     if (type != JITCode::BaselineJIT) {
3750         dataLog(*this, ": expected to have baseline code but have ", type, "\n");
3751         RELEASE_ASSERT_NOT_REACHED();
3752     }
3753     
3754     CodeBlock* theReplacement = replacement();
3755     if ((result == CompilationSuccessful) != (theReplacement != this)) {
3756         dataLog(*this, ": we have result = ", result, " but ");
3757         if (theReplacement == this)
3758             dataLog("we are our own replacement.\n");
3759         else
3760             dataLog("our replacement is ", pointerDump(theReplacement), "\n");
3761         RELEASE_ASSERT_NOT_REACHED();
3762     }
3763     
3764     switch (result) {
3765     case CompilationSuccessful:
3766         RELEASE_ASSERT(JITCode::isOptimizingJIT(replacement()->jitType()));
3767         optimizeNextInvocation();
3768         return;
3769     case CompilationFailed:
3770         dontOptimizeAnytimeSoon();
3771         return;
3772     case CompilationDeferred:
3773         // We'd like to do dontOptimizeAnytimeSoon() but we cannot because
3774         //&nbs