Polymorphic call inlining should be based on polymorphic call inline caching rather...
[WebKit-https.git] / Source / JavaScriptCore / bytecode / CodeBlock.cpp
1 /*
2  * Copyright (C) 2008-2010, 2012-2015 Apple Inc. All rights reserved.
3  * Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca>
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1.  Redistributions of source code must retain the above copyright
10  *     notice, this list of conditions and the following disclaimer.
11  * 2.  Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution.
14  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
15  *     its contributors may be used to endorse or promote products derived
16  *     from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include "config.h"
31 #include "CodeBlock.h"
32
33 #include "BasicBlockLocation.h"
34 #include "BytecodeGenerator.h"
35 #include "BytecodeUseDef.h"
36 #include "CallLinkStatus.h"
37 #include "DFGCapabilities.h"
38 #include "DFGCommon.h"
39 #include "DFGDriver.h"
40 #include "DFGJITCode.h"
41 #include "DFGWorklist.h"
42 #include "Debugger.h"
43 #include "FunctionExecutableDump.h"
44 #include "Interpreter.h"
45 #include "JIT.h"
46 #include "JITStubs.h"
47 #include "JSCJSValue.h"
48 #include "JSFunction.h"
49 #include "JSLexicalEnvironment.h"
50 #include "JSNameScope.h"
51 #include "LLIntEntrypoint.h"
52 #include "LowLevelInterpreter.h"
53 #include "JSCInlines.h"
54 #include "PolymorphicGetByIdList.h"
55 #include "PolymorphicPutByIdList.h"
56 #include "ProfilerDatabase.h"
57 #include "ReduceWhitespace.h"
58 #include "Repatch.h"
59 #include "RepatchBuffer.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
70 #if ENABLE(DFG_JIT)
71 #include "DFGOperations.h"
72 #endif
73
74 #if ENABLE(FTL_JIT)
75 #include "FTLJITCode.h"
76 #endif
77
78 namespace JSC {
79
80 CString CodeBlock::inferredName() const
81 {
82     switch (codeType()) {
83     case GlobalCode:
84         return "<global>";
85     case EvalCode:
86         return "<eval>";
87     case FunctionCode:
88         return jsCast<FunctionExecutable*>(ownerExecutable())->inferredName().utf8();
89     default:
90         CRASH();
91         return CString("", 0);
92     }
93 }
94
95 bool CodeBlock::hasHash() const
96 {
97     return !!m_hash;
98 }
99
100 bool CodeBlock::isSafeToComputeHash() const
101 {
102     return !isCompilationThread();
103 }
104
105 CodeBlockHash CodeBlock::hash() const
106 {
107     if (!m_hash) {
108         RELEASE_ASSERT(isSafeToComputeHash());
109         m_hash = CodeBlockHash(ownerExecutable()->source(), specializationKind());
110     }
111     return m_hash;
112 }
113
114 CString CodeBlock::sourceCodeForTools() const
115 {
116     if (codeType() != FunctionCode)
117         return ownerExecutable()->source().toUTF8();
118     
119     SourceProvider* provider = source();
120     FunctionExecutable* executable = jsCast<FunctionExecutable*>(ownerExecutable());
121     UnlinkedFunctionExecutable* unlinked = executable->unlinkedExecutable();
122     unsigned unlinkedStartOffset = unlinked->startOffset();
123     unsigned linkedStartOffset = executable->source().startOffset();
124     int delta = linkedStartOffset - unlinkedStartOffset;
125     unsigned rangeStart = delta + unlinked->unlinkedFunctionNameStart();
126     unsigned rangeEnd = delta + unlinked->startOffset() + unlinked->sourceLength();
127     return toCString(
128         "function ",
129         provider->source().impl()->utf8ForRange(rangeStart, rangeEnd - rangeStart));
130 }
131
132 CString CodeBlock::sourceCodeOnOneLine() const
133 {
134     return reduceWhitespace(sourceCodeForTools());
135 }
136
137 CString CodeBlock::hashAsStringIfPossible() const
138 {
139     if (hasHash() || isSafeToComputeHash())
140         return toCString(hash());
141     return "<no-hash>";
142 }
143
144 void CodeBlock::dumpAssumingJITType(PrintStream& out, JITCode::JITType jitType) const
145 {
146     out.print(inferredName(), "#", hashAsStringIfPossible());
147     out.print(":[", RawPointer(this), "->");
148     if (!!m_alternative)
149         out.print(RawPointer(m_alternative.get()), "->");
150     out.print(RawPointer(ownerExecutable()), ", ", jitType, codeType());
151
152     if (codeType() == FunctionCode)
153         out.print(specializationKind());
154     out.print(", ", instructionCount());
155     if (this->jitType() == JITCode::BaselineJIT && m_shouldAlwaysBeInlined)
156         out.print(" (ShouldAlwaysBeInlined)");
157     if (ownerExecutable()->neverInline())
158         out.print(" (NeverInline)");
159     if (ownerExecutable()->didTryToEnterInLoop())
160         out.print(" (DidTryToEnterInLoop)");
161     if (ownerExecutable()->isStrictMode())
162         out.print(" (StrictMode)");
163     if (this->jitType() == JITCode::BaselineJIT && m_didFailFTLCompilation)
164         out.print(" (FTLFail)");
165     if (this->jitType() == JITCode::BaselineJIT && m_hasBeenCompiledWithFTL)
166         out.print(" (HadFTLReplacement)");
167     out.print("]");
168 }
169
170 void CodeBlock::dump(PrintStream& out) const
171 {
172     dumpAssumingJITType(out, jitType());
173 }
174
175 static CString constantName(int k, JSValue value)
176 {
177     return toCString(value, "(@k", k - FirstConstantRegisterIndex, ")");
178 }
179
180 static CString idName(int id0, const Identifier& ident)
181 {
182     return toCString(ident.impl(), "(@id", id0, ")");
183 }
184
185 CString CodeBlock::registerName(int r) const
186 {
187     if (r == missingThisObjectMarker())
188         return "<null>";
189
190     if (isConstantRegisterIndex(r))
191         return constantName(r, getConstant(r));
192
193     if (operandIsArgument(r)) {
194         if (!VirtualRegister(r).toArgument())
195             return "this";
196         return toCString("arg", VirtualRegister(r).toArgument());
197     }
198
199     return toCString("loc", VirtualRegister(r).toLocal());
200 }
201
202 static CString regexpToSourceString(RegExp* regExp)
203 {
204     char postfix[5] = { '/', 0, 0, 0, 0 };
205     int index = 1;
206     if (regExp->global())
207         postfix[index++] = 'g';
208     if (regExp->ignoreCase())
209         postfix[index++] = 'i';
210     if (regExp->multiline())
211         postfix[index] = 'm';
212
213     return toCString("/", regExp->pattern().impl(), postfix);
214 }
215
216 static CString regexpName(int re, RegExp* regexp)
217 {
218     return toCString(regexpToSourceString(regexp), "(@re", re, ")");
219 }
220
221 NEVER_INLINE static const char* debugHookName(int debugHookID)
222 {
223     switch (static_cast<DebugHookID>(debugHookID)) {
224         case DidEnterCallFrame:
225             return "didEnterCallFrame";
226         case WillLeaveCallFrame:
227             return "willLeaveCallFrame";
228         case WillExecuteStatement:
229             return "willExecuteStatement";
230         case WillExecuteProgram:
231             return "willExecuteProgram";
232         case DidExecuteProgram:
233             return "didExecuteProgram";
234         case DidReachBreakpoint:
235             return "didReachBreakpoint";
236     }
237
238     RELEASE_ASSERT_NOT_REACHED();
239     return "";
240 }
241
242 void CodeBlock::printUnaryOp(PrintStream& out, ExecState* exec, int location, const Instruction*& it, const char* op)
243 {
244     int r0 = (++it)->u.operand;
245     int r1 = (++it)->u.operand;
246
247     printLocationAndOp(out, exec, location, it, op);
248     out.printf("%s, %s", registerName(r0).data(), registerName(r1).data());
249 }
250
251 void CodeBlock::printBinaryOp(PrintStream& out, ExecState* exec, int location, const Instruction*& it, const char* op)
252 {
253     int r0 = (++it)->u.operand;
254     int r1 = (++it)->u.operand;
255     int r2 = (++it)->u.operand;
256     printLocationAndOp(out, exec, location, it, op);
257     out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
258 }
259
260 void CodeBlock::printConditionalJump(PrintStream& out, ExecState* exec, const Instruction*, const Instruction*& it, int location, const char* op)
261 {
262     int r0 = (++it)->u.operand;
263     int offset = (++it)->u.operand;
264     printLocationAndOp(out, exec, location, it, op);
265     out.printf("%s, %d(->%d)", registerName(r0).data(), offset, location + offset);
266 }
267
268 void CodeBlock::printGetByIdOp(PrintStream& out, ExecState* exec, int location, const Instruction*& it)
269 {
270     const char* op;
271     switch (exec->interpreter()->getOpcodeID(it->u.opcode)) {
272     case op_get_by_id:
273         op = "get_by_id";
274         break;
275     case op_get_by_id_out_of_line:
276         op = "get_by_id_out_of_line";
277         break;
278     case op_get_array_length:
279         op = "array_length";
280         break;
281     default:
282         RELEASE_ASSERT_NOT_REACHED();
283 #if COMPILER_QUIRK(CONSIDERS_UNREACHABLE_CODE)
284         op = 0;
285 #endif
286     }
287     int r0 = (++it)->u.operand;
288     int r1 = (++it)->u.operand;
289     int id0 = (++it)->u.operand;
290     printLocationAndOp(out, exec, location, it, op);
291     out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), idName(id0, identifier(id0)).data());
292     it += 4; // Increment up to the value profiler.
293 }
294
295 static void dumpStructure(PrintStream& out, const char* name, Structure* structure, const Identifier& ident)
296 {
297     if (!structure)
298         return;
299     
300     out.printf("%s = %p", name, structure);
301     
302     PropertyOffset offset = structure->getConcurrently(ident.impl());
303     if (offset != invalidOffset)
304         out.printf(" (offset = %d)", offset);
305 }
306
307 static void dumpChain(PrintStream& out, StructureChain* chain, const Identifier& ident)
308 {
309     out.printf("chain = %p: [", chain);
310     bool first = true;
311     for (WriteBarrier<Structure>* currentStructure = chain->head();
312          *currentStructure;
313          ++currentStructure) {
314         if (first)
315             first = false;
316         else
317             out.printf(", ");
318         dumpStructure(out, "struct", currentStructure->get(), ident);
319     }
320     out.printf("]");
321 }
322
323 void CodeBlock::printGetByIdCacheStatus(PrintStream& out, ExecState* exec, int location, const StubInfoMap& map)
324 {
325     Instruction* instruction = instructions().begin() + location;
326
327     const Identifier& ident = identifier(instruction[3].u.operand);
328     
329     UNUSED_PARAM(ident); // tell the compiler to shut up in certain platform configurations.
330     
331     if (exec->interpreter()->getOpcodeID(instruction[0].u.opcode) == op_get_array_length)
332         out.printf(" llint(array_length)");
333     else if (Structure* structure = instruction[4].u.structure.get()) {
334         out.printf(" llint(");
335         dumpStructure(out, "struct", structure, ident);
336         out.printf(")");
337     }
338
339 #if ENABLE(JIT)
340     if (StructureStubInfo* stubPtr = map.get(CodeOrigin(location))) {
341         StructureStubInfo& stubInfo = *stubPtr;
342         if (stubInfo.resetByGC)
343             out.print(" (Reset By GC)");
344         
345         if (stubInfo.seen) {
346             out.printf(" jit(");
347             
348             Structure* baseStructure = 0;
349             Structure* prototypeStructure = 0;
350             StructureChain* chain = 0;
351             PolymorphicGetByIdList* list = 0;
352             
353             switch (stubInfo.accessType) {
354             case access_get_by_id_self:
355                 out.printf("self");
356                 baseStructure = stubInfo.u.getByIdSelf.baseObjectStructure.get();
357                 break;
358             case access_get_by_id_list:
359                 out.printf("list");
360                 list = stubInfo.u.getByIdList.list;
361                 break;
362             case access_unset:
363                 out.printf("unset");
364                 break;
365             default:
366                 RELEASE_ASSERT_NOT_REACHED();
367                 break;
368             }
369             
370             if (baseStructure) {
371                 out.printf(", ");
372                 dumpStructure(out, "struct", baseStructure, ident);
373             }
374             
375             if (prototypeStructure) {
376                 out.printf(", ");
377                 dumpStructure(out, "prototypeStruct", baseStructure, ident);
378             }
379             
380             if (chain) {
381                 out.printf(", ");
382                 dumpChain(out, chain, ident);
383             }
384             
385             if (list) {
386                 out.printf(", list = %p: [", list);
387                 for (unsigned i = 0; i < list->size(); ++i) {
388                     if (i)
389                         out.printf(", ");
390                     out.printf("(");
391                     dumpStructure(out, "base", list->at(i).structure(), ident);
392                     if (list->at(i).chain()) {
393                         out.printf(", ");
394                         dumpChain(out, list->at(i).chain(), ident);
395                     }
396                     out.printf(")");
397                 }
398                 out.printf("]");
399             }
400             out.printf(")");
401         }
402     }
403 #else
404     UNUSED_PARAM(map);
405 #endif
406 }
407
408 void CodeBlock::printPutByIdCacheStatus(PrintStream& out, ExecState* exec, int location, const StubInfoMap& map)
409 {
410     Instruction* instruction = instructions().begin() + location;
411
412     const Identifier& ident = identifier(instruction[2].u.operand);
413     
414     UNUSED_PARAM(ident); // tell the compiler to shut up in certain platform configurations.
415     
416     if (Structure* structure = instruction[4].u.structure.get()) {
417         switch (exec->interpreter()->getOpcodeID(instruction[0].u.opcode)) {
418         case op_put_by_id:
419         case op_put_by_id_out_of_line:
420             out.print(" llint(");
421             dumpStructure(out, "struct", structure, ident);
422             out.print(")");
423             break;
424             
425         case op_put_by_id_transition_direct:
426         case op_put_by_id_transition_normal:
427         case op_put_by_id_transition_direct_out_of_line:
428         case op_put_by_id_transition_normal_out_of_line:
429             out.print(" llint(");
430             dumpStructure(out, "prev", structure, ident);
431             out.print(", ");
432             dumpStructure(out, "next", instruction[6].u.structure.get(), ident);
433             if (StructureChain* chain = instruction[7].u.structureChain.get()) {
434                 out.print(", ");
435                 dumpChain(out, chain, ident);
436             }
437             out.print(")");
438             break;
439             
440         default:
441             out.print(" llint(unknown)");
442             break;
443         }
444     }
445
446 #if ENABLE(JIT)
447     if (StructureStubInfo* stubPtr = map.get(CodeOrigin(location))) {
448         StructureStubInfo& stubInfo = *stubPtr;
449         if (stubInfo.resetByGC)
450             out.print(" (Reset By GC)");
451         
452         if (stubInfo.seen) {
453             out.printf(" jit(");
454             
455             switch (stubInfo.accessType) {
456             case access_put_by_id_replace:
457                 out.print("replace, ");
458                 dumpStructure(out, "struct", stubInfo.u.putByIdReplace.baseObjectStructure.get(), ident);
459                 break;
460             case access_put_by_id_transition_normal:
461             case access_put_by_id_transition_direct:
462                 out.print("transition, ");
463                 dumpStructure(out, "prev", stubInfo.u.putByIdTransition.previousStructure.get(), ident);
464                 out.print(", ");
465                 dumpStructure(out, "next", stubInfo.u.putByIdTransition.structure.get(), ident);
466                 if (StructureChain* chain = stubInfo.u.putByIdTransition.chain.get()) {
467                     out.print(", ");
468                     dumpChain(out, chain, ident);
469                 }
470                 break;
471             case access_put_by_id_list: {
472                 out.printf("list = [");
473                 PolymorphicPutByIdList* list = stubInfo.u.putByIdList.list;
474                 CommaPrinter comma;
475                 for (unsigned i = 0; i < list->size(); ++i) {
476                     out.print(comma, "(");
477                     const PutByIdAccess& access = list->at(i);
478                     
479                     if (access.isReplace()) {
480                         out.print("replace, ");
481                         dumpStructure(out, "struct", access.oldStructure(), ident);
482                     } else if (access.isSetter()) {
483                         out.print("setter, ");
484                         dumpStructure(out, "struct", access.oldStructure(), ident);
485                     } else if (access.isCustom()) {
486                         out.print("custom, ");
487                         dumpStructure(out, "struct", access.oldStructure(), ident);
488                     } else if (access.isTransition()) {
489                         out.print("transition, ");
490                         dumpStructure(out, "prev", access.oldStructure(), ident);
491                         out.print(", ");
492                         dumpStructure(out, "next", access.newStructure(), ident);
493                         if (access.chain()) {
494                             out.print(", ");
495                             dumpChain(out, access.chain(), ident);
496                         }
497                     } else
498                         out.print("unknown");
499                     
500                     out.print(")");
501                 }
502                 out.print("]");
503                 break;
504             }
505             case access_unset:
506                 out.printf("unset");
507                 break;
508             default:
509                 RELEASE_ASSERT_NOT_REACHED();
510                 break;
511             }
512             out.printf(")");
513         }
514     }
515 #else
516     UNUSED_PARAM(map);
517 #endif
518 }
519
520 void CodeBlock::printCallOp(PrintStream& out, ExecState* exec, int location, const Instruction*& it, const char* op, CacheDumpMode cacheDumpMode, bool& hasPrintedProfiling, const CallLinkInfoMap& map)
521 {
522     int dst = (++it)->u.operand;
523     int func = (++it)->u.operand;
524     int argCount = (++it)->u.operand;
525     int registerOffset = (++it)->u.operand;
526     printLocationAndOp(out, exec, location, it, op);
527     out.printf("%s, %s, %d, %d", registerName(dst).data(), registerName(func).data(), argCount, registerOffset);
528     if (cacheDumpMode == DumpCaches) {
529         LLIntCallLinkInfo* callLinkInfo = it[1].u.callLinkInfo;
530         if (callLinkInfo->lastSeenCallee) {
531             out.printf(
532                 " llint(%p, exec %p)",
533                 callLinkInfo->lastSeenCallee.get(),
534                 callLinkInfo->lastSeenCallee->executable());
535         }
536 #if ENABLE(JIT)
537         if (CallLinkInfo* info = map.get(CodeOrigin(location))) {
538             JSFunction* target = info->lastSeenCallee.get();
539             if (target)
540                 out.printf(" jit(%p, exec %p)", target, target->executable());
541         }
542         out.print(" status(", CallLinkStatus::computeFor(this, location, map), ")");
543 #else
544         UNUSED_PARAM(map);
545 #endif
546     }
547     ++it;
548     ++it;
549     dumpArrayProfiling(out, it, hasPrintedProfiling);
550     dumpValueProfiling(out, it, hasPrintedProfiling);
551 }
552
553 void CodeBlock::printPutByIdOp(PrintStream& out, ExecState* exec, int location, const Instruction*& it, const char* op)
554 {
555     int r0 = (++it)->u.operand;
556     int id0 = (++it)->u.operand;
557     int r1 = (++it)->u.operand;
558     printLocationAndOp(out, exec, location, it, op);
559     out.printf("%s, %s, %s", registerName(r0).data(), idName(id0, identifier(id0)).data(), registerName(r1).data());
560     it += 5;
561 }
562
563 void CodeBlock::dumpBytecode(PrintStream& out)
564 {
565     // We only use the ExecState* for things that don't actually lead to JS execution,
566     // like converting a JSString to a String. Hence the globalExec is appropriate.
567     ExecState* exec = m_globalObject->globalExec();
568     
569     size_t instructionCount = 0;
570
571     for (size_t i = 0; i < instructions().size(); i += opcodeLengths[exec->interpreter()->getOpcodeID(instructions()[i].u.opcode)])
572         ++instructionCount;
573
574     out.print(*this);
575     out.printf(
576         ": %lu m_instructions; %lu bytes; %d parameter(s); %d callee register(s); %d variable(s)",
577         static_cast<unsigned long>(instructions().size()),
578         static_cast<unsigned long>(instructions().size() * sizeof(Instruction)),
579         m_numParameters, m_numCalleeRegisters, m_numVars);
580     if (symbolTable() && symbolTable()->captureCount()) {
581         out.printf(
582             "; %d captured var(s) (from r%d to r%d, inclusive)",
583             symbolTable()->captureCount(), symbolTable()->captureStart(), symbolTable()->captureEnd() + 1);
584     }
585     if (usesArguments()) {
586         out.printf(
587             "; uses arguments, in r%d, r%d",
588             argumentsRegister().offset(),
589             unmodifiedArgumentsRegister(argumentsRegister()).offset());
590     }
591     if (needsActivation() && codeType() == FunctionCode)
592         out.printf("; lexical environment in r%d", activationRegister().offset());
593     out.printf("\n");
594     
595     StubInfoMap stubInfos;
596     CallLinkInfoMap callLinkInfos;
597     getStubInfoMap(stubInfos);
598     getCallLinkInfoMap(callLinkInfos);
599     
600     const Instruction* begin = instructions().begin();
601     const Instruction* end = instructions().end();
602     for (const Instruction* it = begin; it != end; ++it)
603         dumpBytecode(out, exec, begin, it, stubInfos, callLinkInfos);
604     
605     if (numberOfIdentifiers()) {
606         out.printf("\nIdentifiers:\n");
607         size_t i = 0;
608         do {
609             out.printf("  id%u = %s\n", static_cast<unsigned>(i), identifier(i).string().utf8().data());
610             ++i;
611         } while (i != numberOfIdentifiers());
612     }
613
614     if (!m_constantRegisters.isEmpty()) {
615         out.printf("\nConstants:\n");
616         size_t i = 0;
617         do {
618             out.printf("   k%u = %s\n", static_cast<unsigned>(i), toCString(m_constantRegisters[i].get()).data());
619             ++i;
620         } while (i < m_constantRegisters.size());
621     }
622
623     if (size_t count = m_unlinkedCode->numberOfRegExps()) {
624         out.printf("\nm_regexps:\n");
625         size_t i = 0;
626         do {
627             out.printf("  re%u = %s\n", static_cast<unsigned>(i), regexpToSourceString(m_unlinkedCode->regexp(i)).data());
628             ++i;
629         } while (i < count);
630     }
631
632     if (m_rareData && !m_rareData->m_exceptionHandlers.isEmpty()) {
633         out.printf("\nException Handlers:\n");
634         unsigned i = 0;
635         do {
636             out.printf("\t %d: { start: [%4d] end: [%4d] target: [%4d] depth: [%4d] }\n", i + 1, m_rareData->m_exceptionHandlers[i].start, m_rareData->m_exceptionHandlers[i].end, m_rareData->m_exceptionHandlers[i].target, m_rareData->m_exceptionHandlers[i].scopeDepth);
637             ++i;
638         } while (i < m_rareData->m_exceptionHandlers.size());
639     }
640     
641     if (m_rareData && !m_rareData->m_switchJumpTables.isEmpty()) {
642         out.printf("Switch Jump Tables:\n");
643         unsigned i = 0;
644         do {
645             out.printf("  %1d = {\n", i);
646             int entry = 0;
647             Vector<int32_t>::const_iterator end = m_rareData->m_switchJumpTables[i].branchOffsets.end();
648             for (Vector<int32_t>::const_iterator iter = m_rareData->m_switchJumpTables[i].branchOffsets.begin(); iter != end; ++iter, ++entry) {
649                 if (!*iter)
650                     continue;
651                 out.printf("\t\t%4d => %04d\n", entry + m_rareData->m_switchJumpTables[i].min, *iter);
652             }
653             out.printf("      }\n");
654             ++i;
655         } while (i < m_rareData->m_switchJumpTables.size());
656     }
657     
658     if (m_rareData && !m_rareData->m_stringSwitchJumpTables.isEmpty()) {
659         out.printf("\nString Switch Jump Tables:\n");
660         unsigned i = 0;
661         do {
662             out.printf("  %1d = {\n", i);
663             StringJumpTable::StringOffsetTable::const_iterator end = m_rareData->m_stringSwitchJumpTables[i].offsetTable.end();
664             for (StringJumpTable::StringOffsetTable::const_iterator iter = m_rareData->m_stringSwitchJumpTables[i].offsetTable.begin(); iter != end; ++iter)
665                 out.printf("\t\t\"%s\" => %04d\n", iter->key->utf8().data(), iter->value.branchOffset);
666             out.printf("      }\n");
667             ++i;
668         } while (i < m_rareData->m_stringSwitchJumpTables.size());
669     }
670
671     out.printf("\n");
672 }
673
674 void CodeBlock::beginDumpProfiling(PrintStream& out, bool& hasPrintedProfiling)
675 {
676     if (hasPrintedProfiling) {
677         out.print("; ");
678         return;
679     }
680     
681     out.print("    ");
682     hasPrintedProfiling = true;
683 }
684
685 void CodeBlock::dumpValueProfiling(PrintStream& out, const Instruction*& it, bool& hasPrintedProfiling)
686 {
687     ConcurrentJITLocker locker(m_lock);
688     
689     ++it;
690     CString description = it->u.profile->briefDescription(locker);
691     if (!description.length())
692         return;
693     beginDumpProfiling(out, hasPrintedProfiling);
694     out.print(description);
695 }
696
697 void CodeBlock::dumpArrayProfiling(PrintStream& out, const Instruction*& it, bool& hasPrintedProfiling)
698 {
699     ConcurrentJITLocker locker(m_lock);
700     
701     ++it;
702     if (!it->u.arrayProfile)
703         return;
704     CString description = it->u.arrayProfile->briefDescription(locker, this);
705     if (!description.length())
706         return;
707     beginDumpProfiling(out, hasPrintedProfiling);
708     out.print(description);
709 }
710
711 void CodeBlock::dumpRareCaseProfile(PrintStream& out, const char* name, RareCaseProfile* profile, bool& hasPrintedProfiling)
712 {
713     if (!profile || !profile->m_counter)
714         return;
715
716     beginDumpProfiling(out, hasPrintedProfiling);
717     out.print(name, profile->m_counter);
718 }
719
720 void CodeBlock::printLocationAndOp(PrintStream& out, ExecState*, int location, const Instruction*&, const char* op)
721 {
722     out.printf("[%4d] %-17s ", location, op);
723 }
724
725 void CodeBlock::printLocationOpAndRegisterOperand(PrintStream& out, ExecState* exec, int location, const Instruction*& it, const char* op, int operand)
726 {
727     printLocationAndOp(out, exec, location, it, op);
728     out.printf("%s", registerName(operand).data());
729 }
730
731 void CodeBlock::dumpBytecode(
732     PrintStream& out, ExecState* exec, const Instruction* begin, const Instruction*& it,
733     const StubInfoMap& stubInfos, const CallLinkInfoMap& callLinkInfos)
734 {
735     int location = it - begin;
736     bool hasPrintedProfiling = false;
737     OpcodeID opcode = exec->interpreter()->getOpcodeID(it->u.opcode);
738     switch (opcode) {
739         case op_enter: {
740             printLocationAndOp(out, exec, location, it, "enter");
741             break;
742         }
743         case op_touch_entry: {
744             printLocationAndOp(out, exec, location, it, "touch_entry");
745             break;
746         }
747         case op_create_lexical_environment: {
748             int r0 = (++it)->u.operand;
749             int r1 = (++it)->u.operand;
750             printLocationAndOp(out, exec, location, it, "create_lexical_environment");
751             out.printf("%s %s", registerName(r0).data(), registerName(r1).data());
752             break;
753         }
754         case op_get_scope: {
755             int r0 = (++it)->u.operand;
756             printLocationOpAndRegisterOperand(out, exec, location, it, "get_scope", r0);
757             break;
758         }
759         case op_create_arguments: {
760             int r0 = (++it)->u.operand;
761             int r1 = (++it)->u.operand;
762             printLocationAndOp(out, exec, location, it, "create_arguments");
763             out.printf("%s %s", registerName(r0).data(), registerName(r1).data());
764             break;
765         }
766         case op_init_lazy_reg: {
767             int r0 = (++it)->u.operand;
768             printLocationOpAndRegisterOperand(out, exec, location, it, "init_lazy_reg", r0);
769             break;
770         }
771         case op_get_callee: {
772             int r0 = (++it)->u.operand;
773             printLocationOpAndRegisterOperand(out, exec, location, it, "get_callee", r0);
774             ++it;
775             break;
776         }
777         case op_create_this: {
778             int r0 = (++it)->u.operand;
779             int r1 = (++it)->u.operand;
780             unsigned inferredInlineCapacity = (++it)->u.operand;
781             printLocationAndOp(out, exec, location, it, "create_this");
782             out.printf("%s, %s, %u", registerName(r0).data(), registerName(r1).data(), inferredInlineCapacity);
783             break;
784         }
785         case op_to_this: {
786             int r0 = (++it)->u.operand;
787             printLocationOpAndRegisterOperand(out, exec, location, it, "to_this", r0);
788             Structure* structure = (++it)->u.structure.get();
789             if (structure)
790                 out.print(" cache(struct = ", RawPointer(structure), ")");
791             out.print(" ", (++it)->u.toThisStatus);
792             break;
793         }
794         case op_new_object: {
795             int r0 = (++it)->u.operand;
796             unsigned inferredInlineCapacity = (++it)->u.operand;
797             printLocationAndOp(out, exec, location, it, "new_object");
798             out.printf("%s, %u", registerName(r0).data(), inferredInlineCapacity);
799             ++it; // Skip object allocation profile.
800             break;
801         }
802         case op_new_array: {
803             int dst = (++it)->u.operand;
804             int argv = (++it)->u.operand;
805             int argc = (++it)->u.operand;
806             printLocationAndOp(out, exec, location, it, "new_array");
807             out.printf("%s, %s, %d", registerName(dst).data(), registerName(argv).data(), argc);
808             ++it; // Skip array allocation profile.
809             break;
810         }
811         case op_new_array_with_size: {
812             int dst = (++it)->u.operand;
813             int length = (++it)->u.operand;
814             printLocationAndOp(out, exec, location, it, "new_array_with_size");
815             out.printf("%s, %s", registerName(dst).data(), registerName(length).data());
816             ++it; // Skip array allocation profile.
817             break;
818         }
819         case op_new_array_buffer: {
820             int dst = (++it)->u.operand;
821             int argv = (++it)->u.operand;
822             int argc = (++it)->u.operand;
823             printLocationAndOp(out, exec, location, it, "new_array_buffer");
824             out.printf("%s, %d, %d", registerName(dst).data(), argv, argc);
825             ++it; // Skip array allocation profile.
826             break;
827         }
828         case op_new_regexp: {
829             int r0 = (++it)->u.operand;
830             int re0 = (++it)->u.operand;
831             printLocationAndOp(out, exec, location, it, "new_regexp");
832             out.printf("%s, ", registerName(r0).data());
833             if (r0 >=0 && r0 < (int)m_unlinkedCode->numberOfRegExps())
834                 out.printf("%s", regexpName(re0, regexp(re0)).data());
835             else
836                 out.printf("bad_regexp(%d)", re0);
837             break;
838         }
839         case op_mov: {
840             int r0 = (++it)->u.operand;
841             int r1 = (++it)->u.operand;
842             printLocationAndOp(out, exec, location, it, "mov");
843             out.printf("%s, %s", registerName(r0).data(), registerName(r1).data());
844             break;
845         }
846         case op_profile_type: {
847             int r0 = (++it)->u.operand;
848             ++it;
849             ++it;
850             ++it;
851             ++it;
852             printLocationAndOp(out, exec, location, it, "op_profile_type");
853             out.printf("%s", registerName(r0).data());
854             break;
855         }
856         case op_profile_control_flow: {
857             BasicBlockLocation* basicBlockLocation = (++it)->u.basicBlockLocation;
858             printLocationAndOp(out, exec, location, it, "profile_control_flow");
859             out.printf("[%d, %d]", basicBlockLocation->startOffset(), basicBlockLocation->endOffset());
860             break;
861         }
862         case op_not: {
863             printUnaryOp(out, exec, location, it, "not");
864             break;
865         }
866         case op_eq: {
867             printBinaryOp(out, exec, location, it, "eq");
868             break;
869         }
870         case op_eq_null: {
871             printUnaryOp(out, exec, location, it, "eq_null");
872             break;
873         }
874         case op_neq: {
875             printBinaryOp(out, exec, location, it, "neq");
876             break;
877         }
878         case op_neq_null: {
879             printUnaryOp(out, exec, location, it, "neq_null");
880             break;
881         }
882         case op_stricteq: {
883             printBinaryOp(out, exec, location, it, "stricteq");
884             break;
885         }
886         case op_nstricteq: {
887             printBinaryOp(out, exec, location, it, "nstricteq");
888             break;
889         }
890         case op_less: {
891             printBinaryOp(out, exec, location, it, "less");
892             break;
893         }
894         case op_lesseq: {
895             printBinaryOp(out, exec, location, it, "lesseq");
896             break;
897         }
898         case op_greater: {
899             printBinaryOp(out, exec, location, it, "greater");
900             break;
901         }
902         case op_greatereq: {
903             printBinaryOp(out, exec, location, it, "greatereq");
904             break;
905         }
906         case op_inc: {
907             int r0 = (++it)->u.operand;
908             printLocationOpAndRegisterOperand(out, exec, location, it, "inc", r0);
909             break;
910         }
911         case op_dec: {
912             int r0 = (++it)->u.operand;
913             printLocationOpAndRegisterOperand(out, exec, location, it, "dec", r0);
914             break;
915         }
916         case op_to_number: {
917             printUnaryOp(out, exec, location, it, "to_number");
918             break;
919         }
920         case op_negate: {
921             printUnaryOp(out, exec, location, it, "negate");
922             break;
923         }
924         case op_add: {
925             printBinaryOp(out, exec, location, it, "add");
926             ++it;
927             break;
928         }
929         case op_mul: {
930             printBinaryOp(out, exec, location, it, "mul");
931             ++it;
932             break;
933         }
934         case op_div: {
935             printBinaryOp(out, exec, location, it, "div");
936             ++it;
937             break;
938         }
939         case op_mod: {
940             printBinaryOp(out, exec, location, it, "mod");
941             break;
942         }
943         case op_sub: {
944             printBinaryOp(out, exec, location, it, "sub");
945             ++it;
946             break;
947         }
948         case op_lshift: {
949             printBinaryOp(out, exec, location, it, "lshift");
950             break;            
951         }
952         case op_rshift: {
953             printBinaryOp(out, exec, location, it, "rshift");
954             break;
955         }
956         case op_urshift: {
957             printBinaryOp(out, exec, location, it, "urshift");
958             break;
959         }
960         case op_bitand: {
961             printBinaryOp(out, exec, location, it, "bitand");
962             ++it;
963             break;
964         }
965         case op_bitxor: {
966             printBinaryOp(out, exec, location, it, "bitxor");
967             ++it;
968             break;
969         }
970         case op_bitor: {
971             printBinaryOp(out, exec, location, it, "bitor");
972             ++it;
973             break;
974         }
975         case op_check_has_instance: {
976             int r0 = (++it)->u.operand;
977             int r1 = (++it)->u.operand;
978             int r2 = (++it)->u.operand;
979             int offset = (++it)->u.operand;
980             printLocationAndOp(out, exec, location, it, "check_has_instance");
981             out.printf("%s, %s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), registerName(r2).data(), offset, location + offset);
982             break;
983         }
984         case op_instanceof: {
985             int r0 = (++it)->u.operand;
986             int r1 = (++it)->u.operand;
987             int r2 = (++it)->u.operand;
988             printLocationAndOp(out, exec, location, it, "instanceof");
989             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
990             break;
991         }
992         case op_unsigned: {
993             printUnaryOp(out, exec, location, it, "unsigned");
994             break;
995         }
996         case op_typeof: {
997             printUnaryOp(out, exec, location, it, "typeof");
998             break;
999         }
1000         case op_is_undefined: {
1001             printUnaryOp(out, exec, location, it, "is_undefined");
1002             break;
1003         }
1004         case op_is_boolean: {
1005             printUnaryOp(out, exec, location, it, "is_boolean");
1006             break;
1007         }
1008         case op_is_number: {
1009             printUnaryOp(out, exec, location, it, "is_number");
1010             break;
1011         }
1012         case op_is_string: {
1013             printUnaryOp(out, exec, location, it, "is_string");
1014             break;
1015         }
1016         case op_is_object: {
1017             printUnaryOp(out, exec, location, it, "is_object");
1018             break;
1019         }
1020         case op_is_function: {
1021             printUnaryOp(out, exec, location, it, "is_function");
1022             break;
1023         }
1024         case op_in: {
1025             printBinaryOp(out, exec, location, it, "in");
1026             break;
1027         }
1028         case op_init_global_const_nop: {
1029             printLocationAndOp(out, exec, location, it, "init_global_const_nop");
1030             it++;
1031             it++;
1032             it++;
1033             it++;
1034             break;
1035         }
1036         case op_init_global_const: {
1037             WriteBarrier<Unknown>* registerPointer = (++it)->u.registerPointer;
1038             int r0 = (++it)->u.operand;
1039             printLocationAndOp(out, exec, location, it, "init_global_const");
1040             out.printf("g%d(%p), %s", m_globalObject->findRegisterIndex(registerPointer), registerPointer, registerName(r0).data());
1041             it++;
1042             it++;
1043             break;
1044         }
1045         case op_get_by_id:
1046         case op_get_by_id_out_of_line:
1047         case op_get_array_length: {
1048             printGetByIdOp(out, exec, location, it);
1049             printGetByIdCacheStatus(out, exec, location, stubInfos);
1050             dumpValueProfiling(out, it, hasPrintedProfiling);
1051             break;
1052         }
1053         case op_get_arguments_length: {
1054             printUnaryOp(out, exec, location, it, "get_arguments_length");
1055             it++;
1056             break;
1057         }
1058         case op_put_by_id: {
1059             printPutByIdOp(out, exec, location, it, "put_by_id");
1060             printPutByIdCacheStatus(out, exec, location, stubInfos);
1061             break;
1062         }
1063         case op_put_by_id_out_of_line: {
1064             printPutByIdOp(out, exec, location, it, "put_by_id_out_of_line");
1065             printPutByIdCacheStatus(out, exec, location, stubInfos);
1066             break;
1067         }
1068         case op_put_by_id_transition_direct: {
1069             printPutByIdOp(out, exec, location, it, "put_by_id_transition_direct");
1070             printPutByIdCacheStatus(out, exec, location, stubInfos);
1071             break;
1072         }
1073         case op_put_by_id_transition_direct_out_of_line: {
1074             printPutByIdOp(out, exec, location, it, "put_by_id_transition_direct_out_of_line");
1075             printPutByIdCacheStatus(out, exec, location, stubInfos);
1076             break;
1077         }
1078         case op_put_by_id_transition_normal: {
1079             printPutByIdOp(out, exec, location, it, "put_by_id_transition_normal");
1080             printPutByIdCacheStatus(out, exec, location, stubInfos);
1081             break;
1082         }
1083         case op_put_by_id_transition_normal_out_of_line: {
1084             printPutByIdOp(out, exec, location, it, "put_by_id_transition_normal_out_of_line");
1085             printPutByIdCacheStatus(out, exec, location, stubInfos);
1086             break;
1087         }
1088         case op_put_getter_setter: {
1089             int r0 = (++it)->u.operand;
1090             int id0 = (++it)->u.operand;
1091             int r1 = (++it)->u.operand;
1092             int r2 = (++it)->u.operand;
1093             printLocationAndOp(out, exec, location, it, "put_getter_setter");
1094             out.printf("%s, %s, %s, %s", registerName(r0).data(), idName(id0, identifier(id0)).data(), registerName(r1).data(), registerName(r2).data());
1095             break;
1096         }
1097         case op_del_by_id: {
1098             int r0 = (++it)->u.operand;
1099             int r1 = (++it)->u.operand;
1100             int id0 = (++it)->u.operand;
1101             printLocationAndOp(out, exec, location, it, "del_by_id");
1102             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), idName(id0, identifier(id0)).data());
1103             break;
1104         }
1105         case op_get_by_val: {
1106             int r0 = (++it)->u.operand;
1107             int r1 = (++it)->u.operand;
1108             int r2 = (++it)->u.operand;
1109             printLocationAndOp(out, exec, location, it, "get_by_val");
1110             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
1111             dumpArrayProfiling(out, it, hasPrintedProfiling);
1112             dumpValueProfiling(out, it, hasPrintedProfiling);
1113             break;
1114         }
1115         case op_get_argument_by_val: {
1116             int r0 = (++it)->u.operand;
1117             int r1 = (++it)->u.operand;
1118             int r2 = (++it)->u.operand;
1119             int r3 = (++it)->u.operand;
1120             printLocationAndOp(out, exec, location, it, "get_argument_by_val");
1121             out.printf("%s, %s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data(), registerName(r3).data());
1122             ++it;
1123             dumpValueProfiling(out, it, hasPrintedProfiling);
1124             break;
1125         }
1126         case op_put_by_val: {
1127             int r0 = (++it)->u.operand;
1128             int r1 = (++it)->u.operand;
1129             int r2 = (++it)->u.operand;
1130             printLocationAndOp(out, exec, location, it, "put_by_val");
1131             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
1132             dumpArrayProfiling(out, it, hasPrintedProfiling);
1133             break;
1134         }
1135         case op_put_by_val_direct: {
1136             int r0 = (++it)->u.operand;
1137             int r1 = (++it)->u.operand;
1138             int r2 = (++it)->u.operand;
1139             printLocationAndOp(out, exec, location, it, "put_by_val_direct");
1140             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
1141             dumpArrayProfiling(out, it, hasPrintedProfiling);
1142             break;
1143         }
1144         case op_del_by_val: {
1145             int r0 = (++it)->u.operand;
1146             int r1 = (++it)->u.operand;
1147             int r2 = (++it)->u.operand;
1148             printLocationAndOp(out, exec, location, it, "del_by_val");
1149             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
1150             break;
1151         }
1152         case op_put_by_index: {
1153             int r0 = (++it)->u.operand;
1154             unsigned n0 = (++it)->u.operand;
1155             int r1 = (++it)->u.operand;
1156             printLocationAndOp(out, exec, location, it, "put_by_index");
1157             out.printf("%s, %u, %s", registerName(r0).data(), n0, registerName(r1).data());
1158             break;
1159         }
1160         case op_jmp: {
1161             int offset = (++it)->u.operand;
1162             printLocationAndOp(out, exec, location, it, "jmp");
1163             out.printf("%d(->%d)", offset, location + offset);
1164             break;
1165         }
1166         case op_jtrue: {
1167             printConditionalJump(out, exec, begin, it, location, "jtrue");
1168             break;
1169         }
1170         case op_jfalse: {
1171             printConditionalJump(out, exec, begin, it, location, "jfalse");
1172             break;
1173         }
1174         case op_jeq_null: {
1175             printConditionalJump(out, exec, begin, it, location, "jeq_null");
1176             break;
1177         }
1178         case op_jneq_null: {
1179             printConditionalJump(out, exec, begin, it, location, "jneq_null");
1180             break;
1181         }
1182         case op_jneq_ptr: {
1183             int r0 = (++it)->u.operand;
1184             Special::Pointer pointer = (++it)->u.specialPointer;
1185             int offset = (++it)->u.operand;
1186             printLocationAndOp(out, exec, location, it, "jneq_ptr");
1187             out.printf("%s, %d (%p), %d(->%d)", registerName(r0).data(), pointer, m_globalObject->actualPointerFor(pointer), offset, location + offset);
1188             break;
1189         }
1190         case op_jless: {
1191             int r0 = (++it)->u.operand;
1192             int r1 = (++it)->u.operand;
1193             int offset = (++it)->u.operand;
1194             printLocationAndOp(out, exec, location, it, "jless");
1195             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1196             break;
1197         }
1198         case op_jlesseq: {
1199             int r0 = (++it)->u.operand;
1200             int r1 = (++it)->u.operand;
1201             int offset = (++it)->u.operand;
1202             printLocationAndOp(out, exec, location, it, "jlesseq");
1203             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1204             break;
1205         }
1206         case op_jgreater: {
1207             int r0 = (++it)->u.operand;
1208             int r1 = (++it)->u.operand;
1209             int offset = (++it)->u.operand;
1210             printLocationAndOp(out, exec, location, it, "jgreater");
1211             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1212             break;
1213         }
1214         case op_jgreatereq: {
1215             int r0 = (++it)->u.operand;
1216             int r1 = (++it)->u.operand;
1217             int offset = (++it)->u.operand;
1218             printLocationAndOp(out, exec, location, it, "jgreatereq");
1219             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1220             break;
1221         }
1222         case op_jnless: {
1223             int r0 = (++it)->u.operand;
1224             int r1 = (++it)->u.operand;
1225             int offset = (++it)->u.operand;
1226             printLocationAndOp(out, exec, location, it, "jnless");
1227             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1228             break;
1229         }
1230         case op_jnlesseq: {
1231             int r0 = (++it)->u.operand;
1232             int r1 = (++it)->u.operand;
1233             int offset = (++it)->u.operand;
1234             printLocationAndOp(out, exec, location, it, "jnlesseq");
1235             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1236             break;
1237         }
1238         case op_jngreater: {
1239             int r0 = (++it)->u.operand;
1240             int r1 = (++it)->u.operand;
1241             int offset = (++it)->u.operand;
1242             printLocationAndOp(out, exec, location, it, "jngreater");
1243             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1244             break;
1245         }
1246         case op_jngreatereq: {
1247             int r0 = (++it)->u.operand;
1248             int r1 = (++it)->u.operand;
1249             int offset = (++it)->u.operand;
1250             printLocationAndOp(out, exec, location, it, "jngreatereq");
1251             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1252             break;
1253         }
1254         case op_loop_hint: {
1255             printLocationAndOp(out, exec, location, it, "loop_hint");
1256             break;
1257         }
1258         case op_switch_imm: {
1259             int tableIndex = (++it)->u.operand;
1260             int defaultTarget = (++it)->u.operand;
1261             int scrutineeRegister = (++it)->u.operand;
1262             printLocationAndOp(out, exec, location, it, "switch_imm");
1263             out.printf("%d, %d(->%d), %s", tableIndex, defaultTarget, location + defaultTarget, registerName(scrutineeRegister).data());
1264             break;
1265         }
1266         case op_switch_char: {
1267             int tableIndex = (++it)->u.operand;
1268             int defaultTarget = (++it)->u.operand;
1269             int scrutineeRegister = (++it)->u.operand;
1270             printLocationAndOp(out, exec, location, it, "switch_char");
1271             out.printf("%d, %d(->%d), %s", tableIndex, defaultTarget, location + defaultTarget, registerName(scrutineeRegister).data());
1272             break;
1273         }
1274         case op_switch_string: {
1275             int tableIndex = (++it)->u.operand;
1276             int defaultTarget = (++it)->u.operand;
1277             int scrutineeRegister = (++it)->u.operand;
1278             printLocationAndOp(out, exec, location, it, "switch_string");
1279             out.printf("%d, %d(->%d), %s", tableIndex, defaultTarget, location + defaultTarget, registerName(scrutineeRegister).data());
1280             break;
1281         }
1282         case op_new_func: {
1283             int r0 = (++it)->u.operand;
1284             int r1 = (++it)->u.operand;
1285             int f0 = (++it)->u.operand;
1286             int shouldCheck = (++it)->u.operand;
1287             printLocationAndOp(out, exec, location, it, "new_func");
1288             out.printf("%s, %s, f%d, %s", registerName(r0).data(), registerName(r1).data(), f0, shouldCheck ? "<Checked>" : "<Unchecked>");
1289             break;
1290         }
1291         case op_new_func_exp: {
1292             int r0 = (++it)->u.operand;
1293             int r1 = (++it)->u.operand;
1294             int f0 = (++it)->u.operand;
1295             printLocationAndOp(out, exec, location, it, "new_func_exp");
1296             out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1297             break;
1298         }
1299         case op_call: {
1300             printCallOp(out, exec, location, it, "call", DumpCaches, hasPrintedProfiling, callLinkInfos);
1301             break;
1302         }
1303         case op_call_eval: {
1304             printCallOp(out, exec, location, it, "call_eval", DontDumpCaches, hasPrintedProfiling, callLinkInfos);
1305             break;
1306         }
1307             
1308         case op_construct_varargs:
1309         case op_call_varargs: {
1310             int result = (++it)->u.operand;
1311             int callee = (++it)->u.operand;
1312             int thisValue = (++it)->u.operand;
1313             int arguments = (++it)->u.operand;
1314             int firstFreeRegister = (++it)->u.operand;
1315             int varArgOffset = (++it)->u.operand;
1316             ++it;
1317             printLocationAndOp(out, exec, location, it, opcode == op_call_varargs ? "call_varargs" : "construct_varargs");
1318             out.printf("%s, %s, %s, %s, %d, %d", registerName(result).data(), registerName(callee).data(), registerName(thisValue).data(), registerName(arguments).data(), firstFreeRegister, varArgOffset);
1319             dumpValueProfiling(out, it, hasPrintedProfiling);
1320             break;
1321         }
1322
1323         case op_tear_off_arguments: {
1324             int r0 = (++it)->u.operand;
1325             int r1 = (++it)->u.operand;
1326             printLocationAndOp(out, exec, location, it, "tear_off_arguments");
1327             out.printf("%s, %s", registerName(r0).data(), registerName(r1).data());
1328             break;
1329         }
1330         case op_ret: {
1331             int r0 = (++it)->u.operand;
1332             printLocationOpAndRegisterOperand(out, exec, location, it, "ret", r0);
1333             break;
1334         }
1335         case op_construct: {
1336             printCallOp(out, exec, location, it, "construct", DumpCaches, hasPrintedProfiling, callLinkInfos);
1337             break;
1338         }
1339         case op_strcat: {
1340             int r0 = (++it)->u.operand;
1341             int r1 = (++it)->u.operand;
1342             int count = (++it)->u.operand;
1343             printLocationAndOp(out, exec, location, it, "strcat");
1344             out.printf("%s, %s, %d", registerName(r0).data(), registerName(r1).data(), count);
1345             break;
1346         }
1347         case op_to_primitive: {
1348             int r0 = (++it)->u.operand;
1349             int r1 = (++it)->u.operand;
1350             printLocationAndOp(out, exec, location, it, "to_primitive");
1351             out.printf("%s, %s", registerName(r0).data(), registerName(r1).data());
1352             break;
1353         }
1354         case op_get_enumerable_length: {
1355             int dst = it[1].u.operand;
1356             int base = it[2].u.operand;
1357             printLocationAndOp(out, exec, location, it, "op_get_enumerable_length");
1358             out.printf("%s, %s", registerName(dst).data(), registerName(base).data());
1359             it += OPCODE_LENGTH(op_get_enumerable_length) - 1;
1360             break;
1361         }
1362         case op_has_indexed_property: {
1363             int dst = it[1].u.operand;
1364             int base = it[2].u.operand;
1365             int propertyName = it[3].u.operand;
1366             ArrayProfile* arrayProfile = it[4].u.arrayProfile;
1367             printLocationAndOp(out, exec, location, it, "op_has_indexed_property");
1368             out.printf("%s, %s, %s, %p", registerName(dst).data(), registerName(base).data(), registerName(propertyName).data(), arrayProfile);
1369             it += OPCODE_LENGTH(op_has_indexed_property) - 1;
1370             break;
1371         }
1372         case op_has_structure_property: {
1373             int dst = it[1].u.operand;
1374             int base = it[2].u.operand;
1375             int propertyName = it[3].u.operand;
1376             int enumerator = it[4].u.operand;
1377             printLocationAndOp(out, exec, location, it, "op_has_structure_property");
1378             out.printf("%s, %s, %s, %s", registerName(dst).data(), registerName(base).data(), registerName(propertyName).data(), registerName(enumerator).data());
1379             it += OPCODE_LENGTH(op_has_structure_property) - 1;
1380             break;
1381         }
1382         case op_has_generic_property: {
1383             int dst = it[1].u.operand;
1384             int base = it[2].u.operand;
1385             int propertyName = it[3].u.operand;
1386             printLocationAndOp(out, exec, location, it, "op_has_generic_property");
1387             out.printf("%s, %s, %s", registerName(dst).data(), registerName(base).data(), registerName(propertyName).data());
1388             it += OPCODE_LENGTH(op_has_generic_property) - 1;
1389             break;
1390         }
1391         case op_get_direct_pname: {
1392             int dst = it[1].u.operand;
1393             int base = it[2].u.operand;
1394             int propertyName = it[3].u.operand;
1395             int index = it[4].u.operand;
1396             int enumerator = it[5].u.operand;
1397             ValueProfile* profile = it[6].u.profile;
1398             printLocationAndOp(out, exec, location, it, "op_get_direct_pname");
1399             out.printf("%s, %s, %s, %s, %s, %p", registerName(dst).data(), registerName(base).data(), registerName(propertyName).data(), registerName(index).data(), registerName(enumerator).data(), profile);
1400             it += OPCODE_LENGTH(op_get_direct_pname) - 1;
1401             break;
1402
1403         }
1404         case op_get_structure_property_enumerator: {
1405             int dst = it[1].u.operand;
1406             int base = it[2].u.operand;
1407             printLocationAndOp(out, exec, location, it, "op_get_structure_property_enumerator");
1408             out.printf("%s, %s", registerName(dst).data(), registerName(base).data());
1409             it += OPCODE_LENGTH(op_get_structure_property_enumerator) - 1;
1410             break;
1411         }
1412         case op_get_generic_property_enumerator: {
1413             int dst = it[1].u.operand;
1414             int base = it[2].u.operand;
1415             int length = it[3].u.operand;
1416             int structureEnumerator = it[4].u.operand;
1417             printLocationAndOp(out, exec, location, it, "op_get_generic_property_enumerator");
1418             out.printf("%s, %s, %s, %s", registerName(dst).data(), registerName(base).data(), registerName(length).data(), registerName(structureEnumerator).data());
1419             it += OPCODE_LENGTH(op_get_generic_property_enumerator) - 1;
1420             break;
1421         }
1422         case op_next_enumerator_pname: {
1423             int dst = it[1].u.operand;
1424             int enumerator = it[2].u.operand;
1425             int index = it[3].u.operand;
1426             printLocationAndOp(out, exec, location, it, "op_next_enumerator_pname");
1427             out.printf("%s, %s, %s", registerName(dst).data(), registerName(enumerator).data(), registerName(index).data());
1428             it += OPCODE_LENGTH(op_next_enumerator_pname) - 1;
1429             break;
1430         }
1431         case op_to_index_string: {
1432             int dst = it[1].u.operand;
1433             int index = it[2].u.operand;
1434             printLocationAndOp(out, exec, location, it, "op_to_index_string");
1435             out.printf("%s, %s", registerName(dst).data(), registerName(index).data());
1436             it += OPCODE_LENGTH(op_to_index_string) - 1;
1437             break;
1438         }
1439         case op_push_with_scope: {
1440             int dst = (++it)->u.operand;
1441             int newScope = (++it)->u.operand;
1442             printLocationAndOp(out, exec, location, it, "push_with_scope");
1443             out.printf("%s, %s", registerName(dst).data(), registerName(newScope).data());
1444             break;
1445         }
1446         case op_pop_scope: {
1447             int r0 = (++it)->u.operand;
1448             printLocationOpAndRegisterOperand(out, exec, location, it, "pop_scope", r0);
1449             break;
1450         }
1451         case op_push_name_scope: {
1452             int dst = (++it)->u.operand;
1453             int id0 = (++it)->u.operand;
1454             int r1 = (++it)->u.operand;
1455             unsigned attributes = (++it)->u.operand;
1456             JSNameScope::Type scopeType = (JSNameScope::Type)(++it)->u.operand;
1457             printLocationAndOp(out, exec, location, it, "push_name_scope");
1458             out.printf("%s, %s, %s, %u %s", registerName(dst).data(), idName(id0, identifier(id0)).data(), registerName(r1).data(), attributes, (scopeType == JSNameScope::FunctionNameScope) ? "functionScope" : ((scopeType == JSNameScope::CatchScope) ? "catchScope" : "unknownScopeType"));
1459             break;
1460         }
1461         case op_catch: {
1462             int r0 = (++it)->u.operand;
1463             printLocationOpAndRegisterOperand(out, exec, location, it, "catch", r0);
1464             break;
1465         }
1466         case op_throw: {
1467             int r0 = (++it)->u.operand;
1468             printLocationOpAndRegisterOperand(out, exec, location, it, "throw", r0);
1469             break;
1470         }
1471         case op_throw_static_error: {
1472             int k0 = (++it)->u.operand;
1473             int k1 = (++it)->u.operand;
1474             printLocationAndOp(out, exec, location, it, "throw_static_error");
1475             out.printf("%s, %s", constantName(k0, getConstant(k0)).data(), k1 ? "true" : "false");
1476             break;
1477         }
1478         case op_debug: {
1479             int debugHookID = (++it)->u.operand;
1480             int hasBreakpointFlag = (++it)->u.operand;
1481             printLocationAndOp(out, exec, location, it, "debug");
1482             out.printf("%s %d", debugHookName(debugHookID), hasBreakpointFlag);
1483             break;
1484         }
1485         case op_profile_will_call: {
1486             int function = (++it)->u.operand;
1487             printLocationOpAndRegisterOperand(out, exec, location, it, "profile_will_call", function);
1488             break;
1489         }
1490         case op_profile_did_call: {
1491             int function = (++it)->u.operand;
1492             printLocationOpAndRegisterOperand(out, exec, location, it, "profile_did_call", function);
1493             break;
1494         }
1495         case op_end: {
1496             int r0 = (++it)->u.operand;
1497             printLocationOpAndRegisterOperand(out, exec, location, it, "end", r0);
1498             break;
1499         }
1500         case op_resolve_scope: {
1501             int r0 = (++it)->u.operand;
1502             int scope = (++it)->u.operand;
1503             int id0 = (++it)->u.operand;
1504             ResolveModeAndType modeAndType = ResolveModeAndType((++it)->u.operand);
1505             int depth = (++it)->u.operand;
1506             printLocationAndOp(out, exec, location, it, "resolve_scope");
1507             out.printf("%s, %s, %s, %u<%s|%s>, %d", registerName(r0).data(), registerName(scope).data(), idName(id0, identifier(id0)).data(),
1508                 modeAndType.operand(), resolveModeName(modeAndType.mode()), resolveTypeName(modeAndType.type()),
1509                 depth);
1510             ++it;
1511             break;
1512         }
1513         case op_get_from_scope: {
1514             int r0 = (++it)->u.operand;
1515             int r1 = (++it)->u.operand;
1516             int id0 = (++it)->u.operand;
1517             ResolveModeAndType modeAndType = ResolveModeAndType((++it)->u.operand);
1518             ++it; // Structure
1519             int operand = (++it)->u.operand; // Operand
1520             ++it; // Skip value profile.
1521             printLocationAndOp(out, exec, location, it, "get_from_scope");
1522             out.printf("%s, %s, %s, %u<%s|%s>, <structure>, %d",
1523                 registerName(r0).data(), registerName(r1).data(), idName(id0, identifier(id0)).data(),
1524                 modeAndType.operand(), resolveModeName(modeAndType.mode()), resolveTypeName(modeAndType.type()),
1525                 operand);
1526             break;
1527         }
1528         case op_put_to_scope: {
1529             int r0 = (++it)->u.operand;
1530             int id0 = (++it)->u.operand;
1531             int r1 = (++it)->u.operand;
1532             ResolveModeAndType modeAndType = ResolveModeAndType((++it)->u.operand);
1533             ++it; // Structure
1534             int operand = (++it)->u.operand; // Operand
1535             printLocationAndOp(out, exec, location, it, "put_to_scope");
1536             out.printf("%s, %s, %s, %u<%s|%s>, <structure>, %d",
1537                 registerName(r0).data(), idName(id0, identifier(id0)).data(), registerName(r1).data(),
1538                 modeAndType.operand(), resolveModeName(modeAndType.mode()), resolveTypeName(modeAndType.type()),
1539                 operand);
1540             break;
1541         }
1542         default:
1543             RELEASE_ASSERT_NOT_REACHED();
1544     }
1545
1546     dumpRareCaseProfile(out, "rare case: ", rareCaseProfileForBytecodeOffset(location), hasPrintedProfiling);
1547     dumpRareCaseProfile(out, "special fast case: ", specialFastCaseProfileForBytecodeOffset(location), hasPrintedProfiling);
1548     
1549 #if ENABLE(DFG_JIT)
1550     Vector<DFG::FrequentExitSite> exitSites = exitProfile().exitSitesFor(location);
1551     if (!exitSites.isEmpty()) {
1552         out.print(" !! frequent exits: ");
1553         CommaPrinter comma;
1554         for (unsigned i = 0; i < exitSites.size(); ++i)
1555             out.print(comma, exitSites[i].kind(), " ", exitSites[i].jitType());
1556     }
1557 #else // ENABLE(DFG_JIT)
1558     UNUSED_PARAM(location);
1559 #endif // ENABLE(DFG_JIT)
1560     out.print("\n");
1561 }
1562
1563 void CodeBlock::dumpBytecode(
1564     PrintStream& out, unsigned bytecodeOffset,
1565     const StubInfoMap& stubInfos, const CallLinkInfoMap& callLinkInfos)
1566 {
1567     ExecState* exec = m_globalObject->globalExec();
1568     const Instruction* it = instructions().begin() + bytecodeOffset;
1569     dumpBytecode(out, exec, instructions().begin(), it, stubInfos, callLinkInfos);
1570 }
1571
1572 #define FOR_EACH_MEMBER_VECTOR(macro) \
1573     macro(instructions) \
1574     macro(callLinkInfos) \
1575     macro(linkedCallerList) \
1576     macro(identifiers) \
1577     macro(functionExpressions) \
1578     macro(constantRegisters)
1579
1580 #define FOR_EACH_MEMBER_VECTOR_RARE_DATA(macro) \
1581     macro(regexps) \
1582     macro(functions) \
1583     macro(exceptionHandlers) \
1584     macro(switchJumpTables) \
1585     macro(stringSwitchJumpTables) \
1586     macro(evalCodeCache) \
1587     macro(expressionInfo) \
1588     macro(lineInfo) \
1589     macro(callReturnIndexVector)
1590
1591 template<typename T>
1592 static size_t sizeInBytes(const Vector<T>& vector)
1593 {
1594     return vector.capacity() * sizeof(T);
1595 }
1596
1597 namespace {
1598
1599 class PutToScopeFireDetail : public FireDetail {
1600 public:
1601     PutToScopeFireDetail(CodeBlock* codeBlock, const Identifier& ident)
1602         : m_codeBlock(codeBlock)
1603         , m_ident(ident)
1604     {
1605     }
1606     
1607     virtual void dump(PrintStream& out) const override
1608     {
1609         out.print("Linking put_to_scope in ", FunctionExecutableDump(jsCast<FunctionExecutable*>(m_codeBlock->ownerExecutable())), " for ", m_ident);
1610     }
1611     
1612 private:
1613     CodeBlock* m_codeBlock;
1614     const Identifier& m_ident;
1615 };
1616
1617 } // anonymous namespace
1618
1619 CodeBlock::CodeBlock(CopyParsedBlockTag, CodeBlock& other)
1620     : m_globalObject(other.m_globalObject)
1621     , m_heap(other.m_heap)
1622     , m_numCalleeRegisters(other.m_numCalleeRegisters)
1623     , m_numVars(other.m_numVars)
1624     , m_isConstructor(other.m_isConstructor)
1625     , m_shouldAlwaysBeInlined(true)
1626     , m_didFailFTLCompilation(false)
1627     , m_hasBeenCompiledWithFTL(false)
1628     , m_unlinkedCode(*other.m_vm, other.m_ownerExecutable.get(), other.m_unlinkedCode.get())
1629     , m_hasDebuggerStatement(false)
1630     , m_steppingMode(SteppingModeDisabled)
1631     , m_numBreakpoints(0)
1632     , m_ownerExecutable(*other.m_vm, other.m_ownerExecutable.get(), other.m_ownerExecutable.get())
1633     , m_vm(other.m_vm)
1634     , m_instructions(other.m_instructions)
1635     , m_thisRegister(other.m_thisRegister)
1636     , m_scopeRegister(other.m_scopeRegister)
1637     , m_argumentsRegister(other.m_argumentsRegister)
1638     , m_lexicalEnvironmentRegister(other.m_lexicalEnvironmentRegister)
1639     , m_isStrictMode(other.m_isStrictMode)
1640     , m_needsActivation(other.m_needsActivation)
1641     , m_mayBeExecuting(false)
1642     , m_visitAggregateHasBeenCalled(false)
1643     , m_source(other.m_source)
1644     , m_sourceOffset(other.m_sourceOffset)
1645     , m_firstLineColumnOffset(other.m_firstLineColumnOffset)
1646     , m_codeType(other.m_codeType)
1647     , m_constantRegisters(other.m_constantRegisters)
1648     , m_functionDecls(other.m_functionDecls)
1649     , m_functionExprs(other.m_functionExprs)
1650     , m_osrExitCounter(0)
1651     , m_optimizationDelayCounter(0)
1652     , m_reoptimizationRetryCounter(0)
1653     , m_hash(other.m_hash)
1654 #if ENABLE(JIT)
1655     , m_capabilityLevelState(DFG::CapabilityLevelNotSet)
1656 #endif
1657 {
1658     ASSERT(m_heap->isDeferred());
1659     ASSERT(m_scopeRegister.isLocal());
1660
1661     if (SymbolTable* symbolTable = other.symbolTable())
1662         m_symbolTable.set(*m_vm, m_ownerExecutable.get(), symbolTable);
1663     
1664     setNumParameters(other.numParameters());
1665     optimizeAfterWarmUp();
1666     jitAfterWarmUp();
1667
1668     if (other.m_rareData) {
1669         createRareDataIfNecessary();
1670         
1671         m_rareData->m_exceptionHandlers = other.m_rareData->m_exceptionHandlers;
1672         m_rareData->m_constantBuffers = other.m_rareData->m_constantBuffers;
1673         m_rareData->m_switchJumpTables = other.m_rareData->m_switchJumpTables;
1674         m_rareData->m_stringSwitchJumpTables = other.m_rareData->m_stringSwitchJumpTables;
1675     }
1676     
1677     m_heap->m_codeBlocks.add(this);
1678     m_heap->reportExtraMemoryCost(sizeof(CodeBlock));
1679 }
1680
1681 CodeBlock::CodeBlock(ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock, JSScope* scope, PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset, unsigned firstLineColumnOffset)
1682     : m_globalObject(scope->globalObject()->vm(), ownerExecutable, scope->globalObject())
1683     , m_heap(&m_globalObject->vm().heap)
1684     , m_numCalleeRegisters(unlinkedCodeBlock->m_numCalleeRegisters)
1685     , m_numVars(unlinkedCodeBlock->m_numVars)
1686     , m_isConstructor(unlinkedCodeBlock->isConstructor())
1687     , m_shouldAlwaysBeInlined(true)
1688     , m_didFailFTLCompilation(false)
1689     , m_hasBeenCompiledWithFTL(false)
1690     , m_unlinkedCode(m_globalObject->vm(), ownerExecutable, unlinkedCodeBlock)
1691     , m_hasDebuggerStatement(false)
1692     , m_steppingMode(SteppingModeDisabled)
1693     , m_numBreakpoints(0)
1694     , m_ownerExecutable(m_globalObject->vm(), ownerExecutable, ownerExecutable)
1695     , m_vm(unlinkedCodeBlock->vm())
1696     , m_thisRegister(unlinkedCodeBlock->thisRegister())
1697     , m_scopeRegister(unlinkedCodeBlock->scopeRegister())
1698     , m_argumentsRegister(unlinkedCodeBlock->argumentsRegister())
1699     , m_lexicalEnvironmentRegister(unlinkedCodeBlock->activationRegister())
1700     , m_isStrictMode(unlinkedCodeBlock->isStrictMode())
1701     , m_needsActivation(unlinkedCodeBlock->hasActivationRegister() && unlinkedCodeBlock->codeType() == FunctionCode)
1702     , m_mayBeExecuting(false)
1703     , m_visitAggregateHasBeenCalled(false)
1704     , m_source(sourceProvider)
1705     , m_sourceOffset(sourceOffset)
1706     , m_firstLineColumnOffset(firstLineColumnOffset)
1707     , m_codeType(unlinkedCodeBlock->codeType())
1708     , m_osrExitCounter(0)
1709     , m_optimizationDelayCounter(0)
1710     , m_reoptimizationRetryCounter(0)
1711 #if ENABLE(JIT)
1712     , m_capabilityLevelState(DFG::CapabilityLevelNotSet)
1713 #endif
1714 {
1715     ASSERT(m_heap->isDeferred());
1716     ASSERT(m_scopeRegister.isLocal());
1717
1718     bool didCloneSymbolTable = false;
1719     
1720     if (SymbolTable* symbolTable = unlinkedCodeBlock->symbolTable()) {
1721         if (m_vm->typeProfiler()) {
1722             ConcurrentJITLocker locker(symbolTable->m_lock);
1723             symbolTable->prepareForTypeProfiling(locker);
1724         }
1725
1726         if (codeType() == FunctionCode && symbolTable->captureCount()) {
1727             m_symbolTable.set(*m_vm, m_ownerExecutable.get(), symbolTable->cloneCapturedNames(*m_vm));
1728             didCloneSymbolTable = true;
1729         } else
1730             m_symbolTable.set(*m_vm, m_ownerExecutable.get(), symbolTable);
1731     }
1732     
1733     ASSERT(m_source);
1734     setNumParameters(unlinkedCodeBlock->numParameters());
1735
1736     if (vm()->typeProfiler() || vm()->controlFlowProfiler())
1737         vm()->functionHasExecutedCache()->removeUnexecutedRange(m_ownerExecutable->sourceID(), m_ownerExecutable->typeProfilingStartOffset(), m_ownerExecutable->typeProfilingEndOffset());
1738
1739     setConstantRegisters(unlinkedCodeBlock->constantRegisters());
1740     if (unlinkedCodeBlock->usesGlobalObject())
1741         m_constantRegisters[unlinkedCodeBlock->globalObjectRegister().toConstantIndex()].set(*m_vm, ownerExecutable, m_globalObject.get());
1742     m_functionDecls.resizeToFit(unlinkedCodeBlock->numberOfFunctionDecls());
1743     for (size_t count = unlinkedCodeBlock->numberOfFunctionDecls(), i = 0; i < count; ++i) {
1744         UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionDecl(i);
1745         if (vm()->typeProfiler() || vm()->controlFlowProfiler())
1746             vm()->functionHasExecutedCache()->insertUnexecutedRange(m_ownerExecutable->sourceID(), unlinkedExecutable->typeProfilingStartOffset(), unlinkedExecutable->typeProfilingEndOffset());
1747         unsigned lineCount = unlinkedExecutable->lineCount();
1748         unsigned firstLine = ownerExecutable->lineNo() + unlinkedExecutable->firstLineOffset();
1749         bool startColumnIsOnOwnerStartLine = !unlinkedExecutable->firstLineOffset();
1750         unsigned startColumn = unlinkedExecutable->unlinkedBodyStartColumn() + (startColumnIsOnOwnerStartLine ? ownerExecutable->startColumn() : 1);
1751         bool endColumnIsOnStartLine = !lineCount;
1752         unsigned endColumn = unlinkedExecutable->unlinkedBodyEndColumn() + (endColumnIsOnStartLine ? startColumn : 1);
1753         unsigned startOffset = sourceOffset + unlinkedExecutable->startOffset();
1754         unsigned sourceLength = unlinkedExecutable->sourceLength();
1755         SourceCode code(m_source, startOffset, startOffset + sourceLength, firstLine, startColumn);
1756         FunctionExecutable* executable = FunctionExecutable::create(*m_vm, code, unlinkedExecutable, firstLine, firstLine + lineCount, startColumn, endColumn);
1757         m_functionDecls[i].set(*m_vm, ownerExecutable, executable);
1758     }
1759
1760     m_functionExprs.resizeToFit(unlinkedCodeBlock->numberOfFunctionExprs());
1761     for (size_t count = unlinkedCodeBlock->numberOfFunctionExprs(), i = 0; i < count; ++i) {
1762         UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionExpr(i);
1763         if (vm()->typeProfiler() || vm()->controlFlowProfiler())
1764             vm()->functionHasExecutedCache()->insertUnexecutedRange(m_ownerExecutable->sourceID(), unlinkedExecutable->typeProfilingStartOffset(), unlinkedExecutable->typeProfilingEndOffset());
1765         unsigned lineCount = unlinkedExecutable->lineCount();
1766         unsigned firstLine = ownerExecutable->lineNo() + unlinkedExecutable->firstLineOffset();
1767         bool startColumnIsOnOwnerStartLine = !unlinkedExecutable->firstLineOffset();
1768         unsigned startColumn = unlinkedExecutable->unlinkedBodyStartColumn() + (startColumnIsOnOwnerStartLine ? ownerExecutable->startColumn() : 1);
1769         bool endColumnIsOnStartLine = !lineCount;
1770         unsigned endColumn = unlinkedExecutable->unlinkedBodyEndColumn() + (endColumnIsOnStartLine ? startColumn : 1);
1771         unsigned startOffset = sourceOffset + unlinkedExecutable->startOffset();
1772         unsigned sourceLength = unlinkedExecutable->sourceLength();
1773         SourceCode code(m_source, startOffset, startOffset + sourceLength, firstLine, startColumn);
1774         FunctionExecutable* executable = FunctionExecutable::create(*m_vm, code, unlinkedExecutable, firstLine, firstLine + lineCount, startColumn, endColumn);
1775         m_functionExprs[i].set(*m_vm, ownerExecutable, executable);
1776     }
1777
1778     if (unlinkedCodeBlock->hasRareData()) {
1779         createRareDataIfNecessary();
1780         if (size_t count = unlinkedCodeBlock->constantBufferCount()) {
1781             m_rareData->m_constantBuffers.grow(count);
1782             for (size_t i = 0; i < count; i++) {
1783                 const UnlinkedCodeBlock::ConstantBuffer& buffer = unlinkedCodeBlock->constantBuffer(i);
1784                 m_rareData->m_constantBuffers[i] = buffer;
1785             }
1786         }
1787         if (size_t count = unlinkedCodeBlock->numberOfExceptionHandlers()) {
1788             m_rareData->m_exceptionHandlers.resizeToFit(count);
1789             size_t nonLocalScopeDepth = scope->depth();
1790             for (size_t i = 0; i < count; i++) {
1791                 const UnlinkedHandlerInfo& handler = unlinkedCodeBlock->exceptionHandler(i);
1792                 m_rareData->m_exceptionHandlers[i].start = handler.start;
1793                 m_rareData->m_exceptionHandlers[i].end = handler.end;
1794                 m_rareData->m_exceptionHandlers[i].target = handler.target;
1795                 m_rareData->m_exceptionHandlers[i].scopeDepth = nonLocalScopeDepth + handler.scopeDepth;
1796 #if ENABLE(JIT)
1797                 m_rareData->m_exceptionHandlers[i].nativeCode = CodeLocationLabel(MacroAssemblerCodePtr::createFromExecutableAddress(LLInt::getCodePtr(op_catch)));
1798 #endif
1799             }
1800         }
1801
1802         if (size_t count = unlinkedCodeBlock->numberOfStringSwitchJumpTables()) {
1803             m_rareData->m_stringSwitchJumpTables.grow(count);
1804             for (size_t i = 0; i < count; i++) {
1805                 UnlinkedStringJumpTable::StringOffsetTable::iterator ptr = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.begin();
1806                 UnlinkedStringJumpTable::StringOffsetTable::iterator end = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.end();
1807                 for (; ptr != end; ++ptr) {
1808                     OffsetLocation offset;
1809                     offset.branchOffset = ptr->value;
1810                     m_rareData->m_stringSwitchJumpTables[i].offsetTable.add(ptr->key, offset);
1811                 }
1812             }
1813         }
1814
1815         if (size_t count = unlinkedCodeBlock->numberOfSwitchJumpTables()) {
1816             m_rareData->m_switchJumpTables.grow(count);
1817             for (size_t i = 0; i < count; i++) {
1818                 UnlinkedSimpleJumpTable& sourceTable = unlinkedCodeBlock->switchJumpTable(i);
1819                 SimpleJumpTable& destTable = m_rareData->m_switchJumpTables[i];
1820                 destTable.branchOffsets = sourceTable.branchOffsets;
1821                 destTable.min = sourceTable.min;
1822             }
1823         }
1824     }
1825
1826     // Allocate metadata buffers for the bytecode
1827     if (size_t size = unlinkedCodeBlock->numberOfLLintCallLinkInfos())
1828         m_llintCallLinkInfos.resizeToFit(size);
1829     if (size_t size = unlinkedCodeBlock->numberOfArrayProfiles())
1830         m_arrayProfiles.grow(size);
1831     if (size_t size = unlinkedCodeBlock->numberOfArrayAllocationProfiles())
1832         m_arrayAllocationProfiles.resizeToFit(size);
1833     if (size_t size = unlinkedCodeBlock->numberOfValueProfiles())
1834         m_valueProfiles.resizeToFit(size);
1835     if (size_t size = unlinkedCodeBlock->numberOfObjectAllocationProfiles())
1836         m_objectAllocationProfiles.resizeToFit(size);
1837
1838     // Copy and translate the UnlinkedInstructions
1839     unsigned instructionCount = unlinkedCodeBlock->instructions().count();
1840     UnlinkedInstructionStream::Reader instructionReader(unlinkedCodeBlock->instructions());
1841
1842     Vector<Instruction, 0, UnsafeVectorOverflow> instructions(instructionCount);
1843     for (unsigned i = 0; !instructionReader.atEnd(); ) {
1844         const UnlinkedInstruction* pc = instructionReader.next();
1845
1846         unsigned opLength = opcodeLength(pc[0].u.opcode);
1847
1848         instructions[i] = vm()->interpreter->getOpcode(pc[0].u.opcode);
1849         for (size_t j = 1; j < opLength; ++j) {
1850             if (sizeof(int32_t) != sizeof(intptr_t))
1851                 instructions[i + j].u.pointer = 0;
1852             instructions[i + j].u.operand = pc[j].u.operand;
1853         }
1854         switch (pc[0].u.opcode) {
1855         case op_has_indexed_property: {
1856             int arrayProfileIndex = pc[opLength - 1].u.operand;
1857             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
1858
1859             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
1860             break;
1861         }
1862         case op_call_varargs:
1863         case op_construct_varargs:
1864         case op_get_by_val:
1865         case op_get_argument_by_val: {
1866             int arrayProfileIndex = pc[opLength - 2].u.operand;
1867             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
1868
1869             instructions[i + opLength - 2] = &m_arrayProfiles[arrayProfileIndex];
1870             FALLTHROUGH;
1871         }
1872         case op_get_direct_pname:
1873         case op_get_by_id: {
1874             ValueProfile* profile = &m_valueProfiles[pc[opLength - 1].u.operand];
1875             ASSERT(profile->m_bytecodeOffset == -1);
1876             profile->m_bytecodeOffset = i;
1877             instructions[i + opLength - 1] = profile;
1878             break;
1879         }
1880         case op_put_by_val: {
1881             int arrayProfileIndex = pc[opLength - 1].u.operand;
1882             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
1883             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
1884             break;
1885         }
1886         case op_put_by_val_direct: {
1887             int arrayProfileIndex = pc[opLength - 1].u.operand;
1888             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
1889             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
1890             break;
1891         }
1892
1893         case op_new_array:
1894         case op_new_array_buffer:
1895         case op_new_array_with_size: {
1896             int arrayAllocationProfileIndex = pc[opLength - 1].u.operand;
1897             instructions[i + opLength - 1] = &m_arrayAllocationProfiles[arrayAllocationProfileIndex];
1898             break;
1899         }
1900         case op_new_object: {
1901             int objectAllocationProfileIndex = pc[opLength - 1].u.operand;
1902             ObjectAllocationProfile* objectAllocationProfile = &m_objectAllocationProfiles[objectAllocationProfileIndex];
1903             int inferredInlineCapacity = pc[opLength - 2].u.operand;
1904
1905             instructions[i + opLength - 1] = objectAllocationProfile;
1906             objectAllocationProfile->initialize(*vm(),
1907                 m_ownerExecutable.get(), m_globalObject->objectPrototype(), inferredInlineCapacity);
1908             break;
1909         }
1910
1911         case op_call:
1912         case op_call_eval: {
1913             ValueProfile* profile = &m_valueProfiles[pc[opLength - 1].u.operand];
1914             ASSERT(profile->m_bytecodeOffset == -1);
1915             profile->m_bytecodeOffset = i;
1916             instructions[i + opLength - 1] = profile;
1917             int arrayProfileIndex = pc[opLength - 2].u.operand;
1918             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
1919             instructions[i + opLength - 2] = &m_arrayProfiles[arrayProfileIndex];
1920             instructions[i + 5] = &m_llintCallLinkInfos[pc[5].u.operand];
1921             break;
1922         }
1923         case op_construct: {
1924             instructions[i + 5] = &m_llintCallLinkInfos[pc[5].u.operand];
1925             ValueProfile* profile = &m_valueProfiles[pc[opLength - 1].u.operand];
1926             ASSERT(profile->m_bytecodeOffset == -1);
1927             profile->m_bytecodeOffset = i;
1928             instructions[i + opLength - 1] = profile;
1929             break;
1930         }
1931         case op_get_by_id_out_of_line:
1932         case op_get_array_length:
1933             CRASH();
1934
1935         case op_init_global_const_nop: {
1936             ASSERT(codeType() == GlobalCode);
1937             Identifier ident = identifier(pc[4].u.operand);
1938             SymbolTableEntry entry = m_globalObject->symbolTable()->get(ident.impl());
1939             if (entry.isNull())
1940                 break;
1941
1942             instructions[i + 0] = vm()->interpreter->getOpcode(op_init_global_const);
1943             instructions[i + 1] = &m_globalObject->registerAt(entry.getIndex());
1944             break;
1945         }
1946
1947         case op_resolve_scope: {
1948             const Identifier& ident = identifier(pc[3].u.operand);
1949             ResolveType type = static_cast<ResolveType>(pc[4].u.operand);
1950             if (type == LocalClosureVar) {
1951                 instructions[i + 4].u.operand = ClosureVar;
1952                 break;
1953             }
1954
1955             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), needsActivation(), scope, ident, Get, type);
1956             instructions[i + 4].u.operand = op.type;
1957             instructions[i + 5].u.operand = op.depth;
1958             if (op.lexicalEnvironment)
1959                 instructions[i + 6].u.lexicalEnvironment.set(*vm(), ownerExecutable, op.lexicalEnvironment);
1960             break;
1961         }
1962
1963         case op_get_from_scope: {
1964             ValueProfile* profile = &m_valueProfiles[pc[opLength - 1].u.operand];
1965             ASSERT(profile->m_bytecodeOffset == -1);
1966             profile->m_bytecodeOffset = i;
1967             instructions[i + opLength - 1] = profile;
1968
1969             // get_from_scope dst, scope, id, ResolveModeAndType, Structure, Operand
1970
1971             const Identifier& ident = identifier(pc[3].u.operand);
1972             ResolveModeAndType modeAndType = ResolveModeAndType(pc[4].u.operand);
1973             if (modeAndType.type() == LocalClosureVar) {
1974                 instructions[i + 4] = ResolveModeAndType(modeAndType.mode(), ClosureVar).operand();
1975                 break;
1976             }
1977
1978             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), needsActivation(), scope, ident, Get, modeAndType.type());
1979
1980             instructions[i + 4].u.operand = ResolveModeAndType(modeAndType.mode(), op.type).operand();
1981             if (op.type == GlobalVar || op.type == GlobalVarWithVarInjectionChecks)
1982                 instructions[i + 5].u.watchpointSet = op.watchpointSet;
1983             else if (op.structure)
1984                 instructions[i + 5].u.structure.set(*vm(), ownerExecutable, op.structure);
1985             instructions[i + 6].u.pointer = reinterpret_cast<void*>(op.operand);
1986
1987             break;
1988         }
1989
1990         case op_put_to_scope: {
1991             // put_to_scope scope, id, value, ResolveModeAndType, Structure, Operand
1992             const Identifier& ident = identifier(pc[2].u.operand);
1993
1994             ResolveModeAndType modeAndType = ResolveModeAndType(pc[4].u.operand);
1995             if (modeAndType.type() == LocalClosureVar) {
1996                 bool isWatchableVariable = pc[5].u.operand;
1997                 if (!isWatchableVariable) {
1998                     instructions[i + 5].u.watchpointSet = nullptr;
1999                     break;
2000                 }
2001                 StringImpl* uid = ident.impl();
2002                 RELEASE_ASSERT(didCloneSymbolTable);
2003                 if (ident != m_vm->propertyNames->arguments) {
2004                     ConcurrentJITLocker locker(m_symbolTable->m_lock);
2005                     SymbolTable::Map::iterator iter = m_symbolTable->find(locker, uid);
2006                     ASSERT(iter != m_symbolTable->end(locker));
2007                     iter->value.prepareToWatch(symbolTable());
2008                     instructions[i + 5].u.watchpointSet = iter->value.watchpointSet();
2009                 } else
2010                     instructions[i + 5].u.watchpointSet = nullptr;
2011                 break;
2012             }
2013
2014             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), needsActivation(), scope, ident, Put, modeAndType.type());
2015
2016             instructions[i + 4].u.operand = ResolveModeAndType(modeAndType.mode(), op.type).operand();
2017             if (op.type == GlobalVar || op.type == GlobalVarWithVarInjectionChecks)
2018                 instructions[i + 5].u.watchpointSet = op.watchpointSet;
2019             else if (op.type == ClosureVar || op.type == ClosureVarWithVarInjectionChecks) {
2020                 if (op.watchpointSet)
2021                     op.watchpointSet->invalidate(PutToScopeFireDetail(this, ident));
2022             } else if (op.structure)
2023                 instructions[i + 5].u.structure.set(*vm(), ownerExecutable, op.structure);
2024             instructions[i + 6].u.pointer = reinterpret_cast<void*>(op.operand);
2025
2026             break;
2027         }
2028
2029         case op_profile_type: {
2030             RELEASE_ASSERT(vm()->typeProfiler());
2031             // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType?
2032             size_t instructionOffset = i + opLength - 1;
2033             unsigned divotStart, divotEnd;
2034             GlobalVariableID globalVariableID = 0;
2035             RefPtr<TypeSet> globalTypeSet;
2036             bool shouldAnalyze = m_unlinkedCode->typeProfilerExpressionInfoForBytecodeOffset(instructionOffset, divotStart, divotEnd);
2037             VirtualRegister profileRegister(pc[1].u.operand);
2038             ProfileTypeBytecodeFlag flag = static_cast<ProfileTypeBytecodeFlag>(pc[3].u.operand);
2039             SymbolTable* symbolTable = nullptr;
2040
2041             switch (flag) {
2042             case ProfileTypeBytecodePutToScope:
2043             case ProfileTypeBytecodeGetFromScope: {
2044                 const Identifier& ident = identifier(pc[4].u.operand);
2045                 ResolveType type = static_cast<ResolveType>(pc[5].u.operand);
2046                 ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), needsActivation(), scope, ident, (flag == ProfileTypeBytecodeGetFromScope ? Get : Put), type);
2047
2048                 // FIXME: handle other values for op.type here, and also consider what to do when we can't statically determine the globalID
2049                 // https://bugs.webkit.org/show_bug.cgi?id=135184
2050                 if (op.type == ClosureVar)
2051                     symbolTable = op.lexicalEnvironment->symbolTable();
2052                 else if (op.type == GlobalVar)
2053                     symbolTable = m_globalObject.get()->symbolTable();
2054                 
2055                 if (symbolTable) {
2056                     ConcurrentJITLocker locker(symbolTable->m_lock);
2057                     // If our parent scope was created while profiling was disabled, it will not have prepared for profiling yet.
2058                     symbolTable->prepareForTypeProfiling(locker);
2059                     globalVariableID = symbolTable->uniqueIDForVariable(locker, ident.impl(), *vm());
2060                     globalTypeSet = symbolTable->globalTypeSetForVariable(locker, ident.impl(), *vm());
2061                 } else
2062                     globalVariableID = TypeProfilerNoGlobalIDExists;
2063
2064                 break;
2065             }
2066             case ProfileTypeBytecodePutToLocalScope:
2067             case ProfileTypeBytecodeGetFromLocalScope: {
2068                 const Identifier& ident = identifier(pc[4].u.operand);
2069                 symbolTable = m_symbolTable.get();
2070                 ConcurrentJITLocker locker(symbolTable->m_lock);
2071                 // If our parent scope was created while profiling was disabled, it will not have prepared for profiling yet.
2072                 symbolTable->prepareForTypeProfiling(locker);
2073                 globalVariableID = symbolTable->uniqueIDForVariable(locker, ident.impl(), *vm());
2074                 globalTypeSet = symbolTable->globalTypeSetForVariable(locker, ident.impl(), *vm());
2075
2076                 break;
2077             }
2078
2079             case ProfileTypeBytecodeHasGlobalID: {
2080                 symbolTable = m_symbolTable.get();
2081                 ConcurrentJITLocker locker(symbolTable->m_lock);
2082                 globalVariableID = symbolTable->uniqueIDForRegister(locker, profileRegister.offset(), *vm());
2083                 globalTypeSet = symbolTable->globalTypeSetForRegister(locker, profileRegister.offset(), *vm());
2084                 break;
2085             }
2086             case ProfileTypeBytecodeDoesNotHaveGlobalID: 
2087             case ProfileTypeBytecodeFunctionArgument: {
2088                 globalVariableID = TypeProfilerNoGlobalIDExists;
2089                 break;
2090             }
2091             case ProfileTypeBytecodeFunctionReturnStatement: {
2092                 RELEASE_ASSERT(ownerExecutable->isFunctionExecutable());
2093                 globalTypeSet = jsCast<FunctionExecutable*>(ownerExecutable)->returnStatementTypeSet();
2094                 globalVariableID = TypeProfilerReturnStatement;
2095                 if (!shouldAnalyze) {
2096                     // Because a return statement can be added implicitly to return undefined at the end of a function,
2097                     // and these nodes don't emit expression ranges because they aren't in the actual source text of
2098                     // the user's program, give the type profiler some range to identify these return statements.
2099                     // Currently, the text offset that is used as identification is on the open brace of the function 
2100                     // and is stored on TypeLocation's m_divotForFunctionOffsetIfReturnStatement member variable.
2101                     divotStart = divotEnd = m_sourceOffset;
2102                     shouldAnalyze = true;
2103                 }
2104                 break;
2105             }
2106             }
2107
2108             std::pair<TypeLocation*, bool> locationPair = vm()->typeProfiler()->typeLocationCache()->getTypeLocation(globalVariableID,
2109                 m_ownerExecutable->sourceID(), divotStart, divotEnd, globalTypeSet, vm());
2110             TypeLocation* location = locationPair.first;
2111             bool isNewLocation = locationPair.second;
2112
2113             if (flag == ProfileTypeBytecodeFunctionReturnStatement)
2114                 location->m_divotForFunctionOffsetIfReturnStatement = m_sourceOffset;
2115
2116             if (shouldAnalyze && isNewLocation)
2117                 vm()->typeProfiler()->insertNewLocation(location);
2118
2119             instructions[i + 2].u.location = location;
2120             break;
2121         }
2122
2123         case op_debug: {
2124             if (pc[1].u.index == DidReachBreakpoint)
2125                 m_hasDebuggerStatement = true;
2126             break;
2127         }
2128
2129         default:
2130             break;
2131         }
2132         i += opLength;
2133     }
2134
2135     if (vm()->controlFlowProfiler())
2136         insertBasicBlockBoundariesForControlFlowProfiler(instructions);
2137
2138     m_instructions = WTF::RefCountedArray<Instruction>(instructions);
2139
2140     // Set optimization thresholds only after m_instructions is initialized, since these
2141     // rely on the instruction count (and are in theory permitted to also inspect the
2142     // instruction stream to more accurate assess the cost of tier-up).
2143     optimizeAfterWarmUp();
2144     jitAfterWarmUp();
2145
2146     // If the concurrent thread will want the code block's hash, then compute it here
2147     // synchronously.
2148     if (Options::alwaysComputeHash())
2149         hash();
2150
2151     if (Options::dumpGeneratedBytecodes())
2152         dumpBytecode();
2153     
2154     m_heap->m_codeBlocks.add(this);
2155     m_heap->reportExtraMemoryCost(sizeof(CodeBlock) + m_instructions.size() * sizeof(Instruction));
2156 }
2157
2158 CodeBlock::~CodeBlock()
2159 {
2160     if (m_vm->m_perBytecodeProfiler)
2161         m_vm->m_perBytecodeProfiler->notifyDestruction(this);
2162     
2163 #if ENABLE(VERBOSE_VALUE_PROFILE)
2164     dumpValueProfiles();
2165 #endif
2166     while (m_incomingLLIntCalls.begin() != m_incomingLLIntCalls.end())
2167         m_incomingLLIntCalls.begin()->remove();
2168 #if ENABLE(JIT)
2169     // We may be destroyed before any CodeBlocks that refer to us are destroyed.
2170     // Consider that two CodeBlocks become unreachable at the same time. There
2171     // is no guarantee about the order in which the CodeBlocks are destroyed.
2172     // So, if we don't remove incoming calls, and get destroyed before the
2173     // CodeBlock(s) that have calls into us, then the CallLinkInfo vector's
2174     // destructor will try to remove nodes from our (no longer valid) linked list.
2175     while (m_incomingCalls.begin() != m_incomingCalls.end())
2176         m_incomingCalls.begin()->remove();
2177     while (m_incomingPolymorphicCalls.begin() != m_incomingPolymorphicCalls.end())
2178         m_incomingPolymorphicCalls.begin()->remove();
2179     
2180     // Note that our outgoing calls will be removed from other CodeBlocks'
2181     // m_incomingCalls linked lists through the execution of the ~CallLinkInfo
2182     // destructors.
2183
2184     for (Bag<StructureStubInfo>::iterator iter = m_stubInfos.begin(); !!iter; ++iter)
2185         (*iter)->deref();
2186 #endif // ENABLE(JIT)
2187 }
2188
2189 void CodeBlock::setNumParameters(int newValue)
2190 {
2191     m_numParameters = newValue;
2192
2193     m_argumentValueProfiles.resizeToFit(newValue);
2194 }
2195
2196 void EvalCodeCache::visitAggregate(SlotVisitor& visitor)
2197 {
2198     EvalCacheMap::iterator end = m_cacheMap.end();
2199     for (EvalCacheMap::iterator ptr = m_cacheMap.begin(); ptr != end; ++ptr)
2200         visitor.append(&ptr->value);
2201 }
2202
2203 CodeBlock* CodeBlock::specialOSREntryBlockOrNull()
2204 {
2205 #if ENABLE(FTL_JIT)
2206     if (jitType() != JITCode::DFGJIT)
2207         return 0;
2208     DFG::JITCode* jitCode = m_jitCode->dfg();
2209     return jitCode->osrEntryBlock.get();
2210 #else // ENABLE(FTL_JIT)
2211     return 0;
2212 #endif // ENABLE(FTL_JIT)
2213 }
2214
2215 void CodeBlock::visitAggregate(SlotVisitor& visitor)
2216 {
2217 #if ENABLE(PARALLEL_GC)
2218     // I may be asked to scan myself more than once, and it may even happen concurrently.
2219     // To this end, use a CAS loop to check if I've been called already. Only one thread
2220     // may proceed past this point - whichever one wins the CAS race.
2221     unsigned oldValue;
2222     do {
2223         oldValue = m_visitAggregateHasBeenCalled;
2224         if (oldValue) {
2225             // Looks like someone else won! Return immediately to ensure that we don't
2226             // trace the same CodeBlock concurrently. Doing so is hazardous since we will
2227             // be mutating the state of ValueProfiles, which contain JSValues, which can
2228             // have word-tearing on 32-bit, leading to awesome timing-dependent crashes
2229             // that are nearly impossible to track down.
2230             
2231             // Also note that it must be safe to return early as soon as we see the
2232             // value true (well, (unsigned)1), since once a GC thread is in this method
2233             // and has won the CAS race (i.e. was responsible for setting the value true)
2234             // it will definitely complete the rest of this method before declaring
2235             // termination.
2236             return;
2237         }
2238     } while (!WTF::weakCompareAndSwap(&m_visitAggregateHasBeenCalled, 0, 1));
2239 #endif // ENABLE(PARALLEL_GC)
2240     
2241     if (!!m_alternative)
2242         m_alternative->visitAggregate(visitor);
2243     
2244     if (CodeBlock* otherBlock = specialOSREntryBlockOrNull())
2245         otherBlock->visitAggregate(visitor);
2246
2247     visitor.reportExtraMemoryUsage(ownerExecutable(), sizeof(CodeBlock));
2248     if (m_jitCode)
2249         visitor.reportExtraMemoryUsage(ownerExecutable(), m_jitCode->size());
2250     if (m_instructions.size()) {
2251         // Divide by refCount() because m_instructions points to something that is shared
2252         // by multiple CodeBlocks, and we only want to count it towards the heap size once.
2253         // Having each CodeBlock report only its proportional share of the size is one way
2254         // of accomplishing this.
2255         visitor.reportExtraMemoryUsage(ownerExecutable(), m_instructions.size() * sizeof(Instruction) / m_instructions.refCount());
2256     }
2257
2258     visitor.append(&m_unlinkedCode);
2259
2260     // There are three things that may use unconditional finalizers: lazy bytecode freeing,
2261     // inline cache clearing, and jettisoning. The probability of us wanting to do at
2262     // least one of those things is probably quite close to 1. So we add one no matter what
2263     // and when it runs, it figures out whether it has any work to do.
2264     visitor.addUnconditionalFinalizer(this);
2265     
2266     m_allTransitionsHaveBeenMarked = false;
2267     
2268     if (shouldImmediatelyAssumeLivenessDuringScan()) {
2269         // This code block is live, so scan all references strongly and return.
2270         stronglyVisitStrongReferences(visitor);
2271         stronglyVisitWeakReferences(visitor);
2272         propagateTransitions(visitor);
2273         return;
2274     }
2275     
2276     // There are two things that we use weak reference harvesters for: DFG fixpoint for
2277     // jettisoning, and trying to find structures that would be live based on some
2278     // inline cache. So it makes sense to register them regardless.
2279     visitor.addWeakReferenceHarvester(this);
2280
2281 #if ENABLE(DFG_JIT)
2282     // We get here if we're live in the sense that our owner executable is live,
2283     // but we're not yet live for sure in another sense: we may yet decide that this
2284     // code block should be jettisoned based on its outgoing weak references being
2285     // stale. Set a flag to indicate that we're still assuming that we're dead, and
2286     // perform one round of determining if we're live. The GC may determine, based on
2287     // either us marking additional objects, or by other objects being marked for
2288     // other reasons, that this iteration should run again; it will notify us of this
2289     // decision by calling harvestWeakReferences().
2290     
2291     m_jitCode->dfgCommon()->livenessHasBeenProved = false;
2292     
2293     propagateTransitions(visitor);
2294     determineLiveness(visitor);
2295 #else // ENABLE(DFG_JIT)
2296     RELEASE_ASSERT_NOT_REACHED();
2297 #endif // ENABLE(DFG_JIT)
2298 }
2299
2300 bool CodeBlock::shouldImmediatelyAssumeLivenessDuringScan()
2301 {
2302 #if ENABLE(DFG_JIT)
2303     // Interpreter and Baseline JIT CodeBlocks don't need to be jettisoned when
2304     // their weak references go stale. So if a basline JIT CodeBlock gets
2305     // scanned, we can assume that this means that it's live.
2306     if (!JITCode::isOptimizingJIT(jitType()))
2307         return true;
2308
2309     // For simplicity, we don't attempt to jettison code blocks during GC if
2310     // they are executing. Instead we strongly mark their weak references to
2311     // allow them to continue to execute soundly.
2312     if (m_mayBeExecuting)
2313         return true;
2314
2315     if (Options::forceDFGCodeBlockLiveness())
2316         return true;
2317
2318     return false;
2319 #else
2320     return true;
2321 #endif
2322 }
2323
2324 bool CodeBlock::isKnownToBeLiveDuringGC()
2325 {
2326 #if ENABLE(DFG_JIT)
2327     // This should return true for:
2328     // - Code blocks that behave like normal objects - i.e. if they are referenced then they
2329     //   are live.
2330     // - Code blocks that were running on the stack.
2331     // - Code blocks that survived the last GC if the current GC is an Eden GC. This is
2332     //   because either livenessHasBeenProved would have survived as true or m_mayBeExecuting
2333     //   would survive as true.
2334     // - Code blocks that don't have any dead weak references.
2335     
2336     return shouldImmediatelyAssumeLivenessDuringScan()
2337         || m_jitCode->dfgCommon()->livenessHasBeenProved;
2338 #else
2339     return true;
2340 #endif
2341 }
2342
2343 #if ENABLE(DFG_JIT)
2344 static bool shouldMarkTransition(DFG::WeakReferenceTransition& transition)
2345 {
2346     if (transition.m_codeOrigin && !Heap::isMarked(transition.m_codeOrigin.get()))
2347         return false;
2348     
2349     if (!Heap::isMarked(transition.m_from.get()))
2350         return false;
2351     
2352     return true;
2353 }
2354 #endif // ENABLE(DFG_JIT)
2355
2356 void CodeBlock::propagateTransitions(SlotVisitor& visitor)
2357 {
2358     UNUSED_PARAM(visitor);
2359
2360     if (m_allTransitionsHaveBeenMarked)
2361         return;
2362
2363     bool allAreMarkedSoFar = true;
2364         
2365     Interpreter* interpreter = m_vm->interpreter;
2366     if (jitType() == JITCode::InterpreterThunk) {
2367         const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
2368         for (size_t i = 0; i < propertyAccessInstructions.size(); ++i) {
2369             Instruction* instruction = &instructions()[propertyAccessInstructions[i]];
2370             switch (interpreter->getOpcodeID(instruction[0].u.opcode)) {
2371             case op_put_by_id_transition_direct:
2372             case op_put_by_id_transition_normal:
2373             case op_put_by_id_transition_direct_out_of_line:
2374             case op_put_by_id_transition_normal_out_of_line: {
2375                 if (Heap::isMarked(instruction[4].u.structure.get()))
2376                     visitor.append(&instruction[6].u.structure);
2377                 else
2378                     allAreMarkedSoFar = false;
2379                 break;
2380             }
2381             default:
2382                 break;
2383             }
2384         }
2385     }
2386
2387 #if ENABLE(JIT)
2388     if (JITCode::isJIT(jitType())) {
2389         for (Bag<StructureStubInfo>::iterator iter = m_stubInfos.begin(); !!iter; ++iter) {
2390             StructureStubInfo& stubInfo = **iter;
2391             switch (stubInfo.accessType) {
2392             case access_put_by_id_transition_normal:
2393             case access_put_by_id_transition_direct: {
2394                 JSCell* origin = stubInfo.codeOrigin.codeOriginOwner();
2395                 if ((!origin || Heap::isMarked(origin))
2396                     && Heap::isMarked(stubInfo.u.putByIdTransition.previousStructure.get()))
2397                     visitor.append(&stubInfo.u.putByIdTransition.structure);
2398                 else
2399                     allAreMarkedSoFar = false;
2400                 break;
2401             }
2402
2403             case access_put_by_id_list: {
2404                 PolymorphicPutByIdList* list = stubInfo.u.putByIdList.list;
2405                 JSCell* origin = stubInfo.codeOrigin.codeOriginOwner();
2406                 if (origin && !Heap::isMarked(origin)) {
2407                     allAreMarkedSoFar = false;
2408                     break;
2409                 }
2410                 for (unsigned j = list->size(); j--;) {
2411                     PutByIdAccess& access = list->m_list[j];
2412                     if (!access.isTransition())
2413                         continue;
2414                     if (Heap::isMarked(access.oldStructure()))
2415                         visitor.append(&access.m_newStructure);
2416                     else
2417                         allAreMarkedSoFar = false;
2418                 }
2419                 break;
2420             }
2421             
2422             default:
2423                 break;
2424             }
2425         }
2426     }
2427 #endif // ENABLE(JIT)
2428     
2429 #if ENABLE(DFG_JIT)
2430     if (JITCode::isOptimizingJIT(jitType())) {
2431         DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2432         
2433         for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
2434             if (shouldMarkTransition(dfgCommon->transitions[i])) {
2435                 // If the following three things are live, then the target of the
2436                 // transition is also live:
2437                 //
2438                 // - This code block. We know it's live already because otherwise
2439                 //   we wouldn't be scanning ourselves.
2440                 //
2441                 // - The code origin of the transition. Transitions may arise from
2442                 //   code that was inlined. They are not relevant if the user's
2443                 //   object that is required for the inlinee to run is no longer
2444                 //   live.
2445                 //
2446                 // - The source of the transition. The transition checks if some
2447                 //   heap location holds the source, and if so, stores the target.
2448                 //   Hence the source must be live for the transition to be live.
2449                 //
2450                 // We also short-circuit the liveness if the structure is harmless
2451                 // to mark (i.e. its global object and prototype are both already
2452                 // live).
2453                 
2454                 visitor.append(&dfgCommon->transitions[i].m_to);
2455             } else
2456                 allAreMarkedSoFar = false;
2457         }
2458     }
2459 #endif // ENABLE(DFG_JIT)
2460     
2461     if (allAreMarkedSoFar)
2462         m_allTransitionsHaveBeenMarked = true;
2463 }
2464
2465 void CodeBlock::determineLiveness(SlotVisitor& visitor)
2466 {
2467     UNUSED_PARAM(visitor);
2468     
2469     if (shouldImmediatelyAssumeLivenessDuringScan())
2470         return;
2471     
2472 #if ENABLE(DFG_JIT)
2473     // Check if we have any remaining work to do.
2474     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2475     if (dfgCommon->livenessHasBeenProved)
2476         return;
2477     
2478     // Now check all of our weak references. If all of them are live, then we
2479     // have proved liveness and so we scan our strong references. If at end of
2480     // GC we still have not proved liveness, then this code block is toast.
2481     bool allAreLiveSoFar = true;
2482     for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
2483         if (!Heap::isMarked(dfgCommon->weakReferences[i].get())) {
2484             allAreLiveSoFar = false;
2485             break;
2486         }
2487     }
2488     if (allAreLiveSoFar) {
2489         for (unsigned i = 0; i < dfgCommon->weakStructureReferences.size(); ++i) {
2490             if (!Heap::isMarked(dfgCommon->weakStructureReferences[i].get())) {
2491                 allAreLiveSoFar = false;
2492                 break;
2493             }
2494         }
2495     }
2496     
2497     // If some weak references are dead, then this fixpoint iteration was
2498     // unsuccessful.
2499     if (!allAreLiveSoFar)
2500         return;
2501     
2502     // All weak references are live. Record this information so we don't
2503     // come back here again, and scan the strong references.
2504     dfgCommon->livenessHasBeenProved = true;
2505     stronglyVisitStrongReferences(visitor);
2506 #endif // ENABLE(DFG_JIT)
2507 }
2508
2509 void CodeBlock::visitWeakReferences(SlotVisitor& visitor)
2510 {
2511     propagateTransitions(visitor);
2512     determineLiveness(visitor);
2513 }
2514
2515 void CodeBlock::finalizeUnconditionally()
2516 {
2517     Interpreter* interpreter = m_vm->interpreter;
2518     if (JITCode::couldBeInterpreted(jitType())) {
2519         const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
2520         for (size_t size = propertyAccessInstructions.size(), i = 0; i < size; ++i) {
2521             Instruction* curInstruction = &instructions()[propertyAccessInstructions[i]];
2522             switch (interpreter->getOpcodeID(curInstruction[0].u.opcode)) {
2523             case op_get_by_id:
2524             case op_get_by_id_out_of_line:
2525             case op_put_by_id:
2526             case op_put_by_id_out_of_line:
2527                 if (!curInstruction[4].u.structure || Heap::isMarked(curInstruction[4].u.structure.get()))
2528                     break;
2529                 if (Options::verboseOSR())
2530                     dataLogF("Clearing LLInt property access with structure %p.\n", curInstruction[4].u.structure.get());
2531                 curInstruction[4].u.structure.clear();
2532                 curInstruction[5].u.operand = 0;
2533                 break;
2534             case op_put_by_id_transition_direct:
2535             case op_put_by_id_transition_normal:
2536             case op_put_by_id_transition_direct_out_of_line:
2537             case op_put_by_id_transition_normal_out_of_line:
2538                 if (Heap::isMarked(curInstruction[4].u.structure.get())
2539                     && Heap::isMarked(curInstruction[6].u.structure.get())
2540                     && Heap::isMarked(curInstruction[7].u.structureChain.get()))
2541                     break;
2542                 if (Options::verboseOSR()) {
2543                     dataLogF("Clearing LLInt put transition with structures %p -> %p, chain %p.\n",
2544                             curInstruction[4].u.structure.get(),
2545                             curInstruction[6].u.structure.get(),
2546                             curInstruction[7].u.structureChain.get());
2547                 }
2548                 curInstruction[4].u.structure.clear();
2549                 curInstruction[6].u.structure.clear();
2550                 curInstruction[7].u.structureChain.clear();
2551                 curInstruction[0].u.opcode = interpreter->getOpcode(op_put_by_id);
2552                 break;
2553             case op_get_array_length:
2554                 break;
2555             case op_to_this:
2556                 if (!curInstruction[2].u.structure || Heap::isMarked(curInstruction[2].u.structure.get()))
2557                     break;
2558                 if (Options::verboseOSR())
2559                     dataLogF("Clearing LLInt to_this with structure %p.\n", curInstruction[2].u.structure.get());
2560                 curInstruction[2].u.structure.clear();
2561                 curInstruction[3].u.toThisStatus = merge(
2562                     curInstruction[3].u.toThisStatus, ToThisClearedByGC);
2563                 break;
2564             case op_get_callee:
2565                 if (!curInstruction[2].u.jsCell || Heap::isMarked(curInstruction[2].u.jsCell.get()))
2566                     break;
2567                 if (Options::verboseOSR())
2568                     dataLogF("Clearing LLInt get callee with function %p.\n", curInstruction[2].u.jsCell.get());
2569                 curInstruction[2].u.jsCell.clear();
2570                 break;
2571             case op_resolve_scope: {
2572                 WriteBarrierBase<JSLexicalEnvironment>& lexicalEnvironment = curInstruction[6].u.lexicalEnvironment;
2573                 if (!lexicalEnvironment || Heap::isMarked(lexicalEnvironment.get()))
2574                     break;
2575                 if (Options::verboseOSR())
2576                     dataLogF("Clearing dead lexicalEnvironment %p.\n", lexicalEnvironment.get());
2577                 lexicalEnvironment.clear();
2578                 break;
2579             }
2580             case op_get_from_scope:
2581             case op_put_to_scope: {
2582                 ResolveModeAndType modeAndType =
2583                     ResolveModeAndType(curInstruction[4].u.operand);
2584                 if (modeAndType.type() == GlobalVar || modeAndType.type() == GlobalVarWithVarInjectionChecks || modeAndType.type() == LocalClosureVar)
2585                     continue;
2586                 WriteBarrierBase<Structure>& structure = curInstruction[5].u.structure;
2587                 if (!structure || Heap::isMarked(structure.get()))
2588                     break;
2589                 if (Options::verboseOSR())
2590                     dataLogF("Clearing scope access with structure %p.\n", structure.get());
2591                 structure.clear();
2592                 break;
2593             }
2594             default:
2595                 RELEASE_ASSERT_NOT_REACHED();
2596             }
2597         }
2598
2599         for (unsigned i = 0; i < m_llintCallLinkInfos.size(); ++i) {
2600             if (m_llintCallLinkInfos[i].isLinked() && !Heap::isMarked(m_llintCallLinkInfos[i].callee.get())) {
2601                 if (Options::verboseOSR())
2602                     dataLog("Clearing LLInt call from ", *this, "\n");
2603                 m_llintCallLinkInfos[i].unlink();
2604             }
2605             if (!!m_llintCallLinkInfos[i].lastSeenCallee && !Heap::isMarked(m_llintCallLinkInfos[i].lastSeenCallee.get()))
2606                 m_llintCallLinkInfos[i].lastSeenCallee.clear();
2607         }
2608     }
2609
2610 #if ENABLE(DFG_JIT)
2611     // Check if we're not live. If we are, then jettison.
2612     if (!isKnownToBeLiveDuringGC()) {
2613         if (Options::verboseOSR())
2614             dataLog(*this, " has dead weak references, jettisoning during GC.\n");
2615
2616         if (DFG::shouldShowDisassembly()) {
2617             dataLog(*this, " will be jettisoned because of the following dead references:\n");
2618             DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2619             for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
2620                 DFG::WeakReferenceTransition& transition = dfgCommon->transitions[i];
2621                 JSCell* origin = transition.m_codeOrigin.get();
2622                 JSCell* from = transition.m_from.get();
2623                 JSCell* to = transition.m_to.get();
2624                 if ((!origin || Heap::isMarked(origin)) && Heap::isMarked(from))
2625                     continue;
2626                 dataLog("    Transition under ", RawPointer(origin), ", ", RawPointer(from), " -> ", RawPointer(to), ".\n");
2627             }
2628             for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
2629                 JSCell* weak = dfgCommon->weakReferences[i].get();
2630                 if (Heap::isMarked(weak))
2631                     continue;
2632                 dataLog("    Weak reference ", RawPointer(weak), ".\n");
2633             }
2634         }
2635         
2636         jettison(Profiler::JettisonDueToWeakReference);
2637         return;
2638     }
2639 #endif // ENABLE(DFG_JIT)
2640
2641 #if ENABLE(JIT)
2642     // Handle inline caches.
2643     if (!!jitCode()) {
2644         RepatchBuffer repatchBuffer(this);
2645         
2646         for (auto iter = callLinkInfosBegin(); !!iter; ++iter)
2647             (*iter)->visitWeak(repatchBuffer);
2648
2649         for (Bag<StructureStubInfo>::iterator iter = m_stubInfos.begin(); !!iter; ++iter) {
2650             StructureStubInfo& stubInfo = **iter;
2651             
2652             if (stubInfo.visitWeakReferences(repatchBuffer))
2653                 continue;
2654             
2655             resetStubDuringGCInternal(repatchBuffer, stubInfo);
2656         }
2657     }
2658 #endif
2659 }
2660
2661 void CodeBlock::getStubInfoMap(const ConcurrentJITLocker&, StubInfoMap& result)
2662 {
2663 #if ENABLE(JIT)
2664     toHashMap(m_stubInfos, getStructureStubInfoCodeOrigin, result);
2665 #else
2666     UNUSED_PARAM(result);
2667 #endif
2668 }
2669
2670 void CodeBlock::getStubInfoMap(StubInfoMap& result)
2671 {
2672     ConcurrentJITLocker locker(m_lock);
2673     getStubInfoMap(locker, result);
2674 }
2675
2676 void CodeBlock::getCallLinkInfoMap(const ConcurrentJITLocker&, CallLinkInfoMap& result)
2677 {
2678 #if ENABLE(JIT)
2679     toHashMap(m_callLinkInfos, getCallLinkInfoCodeOrigin, result);
2680 #else
2681     UNUSED_PARAM(result);
2682 #endif
2683 }
2684
2685 void CodeBlock::getCallLinkInfoMap(CallLinkInfoMap& result)
2686 {
2687     ConcurrentJITLocker locker(m_lock);
2688     getCallLinkInfoMap(locker, result);
2689 }
2690
2691 #if ENABLE(JIT)
2692 StructureStubInfo* CodeBlock::addStubInfo()
2693 {
2694     ConcurrentJITLocker locker(m_lock);
2695     return m_stubInfos.add();
2696 }
2697
2698 StructureStubInfo* CodeBlock::findStubInfo(CodeOrigin codeOrigin)
2699 {
2700     for (StructureStubInfo* stubInfo : m_stubInfos) {
2701         if (stubInfo->codeOrigin == codeOrigin)
2702             return stubInfo;
2703     }
2704     return nullptr;
2705 }
2706
2707 CallLinkInfo* CodeBlock::addCallLinkInfo()
2708 {
2709     ConcurrentJITLocker locker(m_lock);
2710     return m_callLinkInfos.add();
2711 }
2712
2713 void CodeBlock::resetStub(StructureStubInfo& stubInfo)
2714 {
2715     if (stubInfo.accessType == access_unset)
2716         return;
2717     
2718     ConcurrentJITLocker locker(m_lock);
2719     
2720     RepatchBuffer repatchBuffer(this);
2721     resetStubInternal(repatchBuffer, stubInfo);
2722 }
2723
2724 void CodeBlock::resetStubInternal(RepatchBuffer& repatchBuffer, StructureStubInfo& stubInfo)
2725 {
2726     AccessType accessType = static_cast<AccessType>(stubInfo.accessType);
2727     
2728     if (Options::verboseOSR()) {
2729         // This can be called from GC destructor calls, so we don't try to do a full dump
2730         // of the CodeBlock.
2731         dataLog("Clearing structure cache (kind ", static_cast<int>(stubInfo.accessType), ") in ", RawPointer(this), ".\n");
2732     }
2733     
2734     RELEASE_ASSERT(JITCode::isJIT(jitType()));
2735     
2736     if (isGetByIdAccess(accessType))
2737         resetGetByID(repatchBuffer, stubInfo);
2738     else if (isPutByIdAccess(accessType))
2739         resetPutByID(repatchBuffer, stubInfo);
2740     else {
2741         RELEASE_ASSERT(isInAccess(accessType));
2742         resetIn(repatchBuffer, stubInfo);
2743     }
2744     
2745     stubInfo.reset();
2746 }
2747
2748 void CodeBlock::resetStubDuringGCInternal(RepatchBuffer& repatchBuffer, StructureStubInfo& stubInfo)
2749 {
2750     resetStubInternal(repatchBuffer, stubInfo);
2751     stubInfo.resetByGC = true;
2752 }
2753
2754 CallLinkInfo* CodeBlock::getCallLinkInfoForBytecodeIndex(unsigned index)
2755 {
2756     for (auto iter = m_callLinkInfos.begin(); !!iter; ++iter) {
2757         if ((*iter)->codeOrigin == CodeOrigin(index))
2758             return *iter;
2759     }
2760     return nullptr;
2761 }
2762 #endif
2763
2764 void CodeBlock::stronglyVisitStrongReferences(SlotVisitor& visitor)
2765 {
2766     visitor.append(&m_globalObject);
2767     visitor.append(&m_ownerExecutable);
2768     visitor.append(&m_symbolTable);
2769     visitor.append(&m_unlinkedCode);
2770     if (m_rareData)
2771         m_rareData->m_evalCodeCache.visitAggregate(visitor);
2772     visitor.appendValues(m_constantRegisters.data(), m_constantRegisters.size());
2773     for (size_t i = 0; i < m_functionExprs.size(); ++i)
2774         visitor.append(&m_functionExprs[i]);
2775     for (size_t i = 0; i < m_functionDecls.size(); ++i)
2776         visitor.append(&m_functionDecls[i]);
2777     for (unsigned i = 0; i < m_objectAllocationProfiles.size(); ++i)
2778         m_objectAllocationProfiles[i].visitAggregate(visitor);
2779
2780 #if ENABLE(DFG_JIT)
2781     if (JITCode::isOptimizingJIT(jitType())) {
2782         DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2783         if (dfgCommon->inlineCallFrames.get())
2784             dfgCommon->inlineCallFrames->visitAggregate(visitor);
2785     }
2786 #endif
2787
2788     updateAllPredictions();
2789 }
2790
2791 void CodeBlock::stronglyVisitWeakReferences(SlotVisitor& visitor)
2792 {
2793     UNUSED_PARAM(visitor);
2794
2795 #if ENABLE(DFG_JIT)
2796     if (!JITCode::isOptimizingJIT(jitType()))
2797         return;
2798     
2799     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2800
2801     for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
2802         if (!!dfgCommon->transitions[i].m_codeOrigin)
2803             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.
2804         visitor.append(&dfgCommon->transitions[i].m_from);
2805         visitor.append(&dfgCommon->transitions[i].m_to);
2806     }
2807     
2808     for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i)
2809         visitor.append(&dfgCommon->weakReferences[i]);
2810
2811     for (unsigned i = 0; i < dfgCommon->weakStructureReferences.size(); ++i)
2812         visitor.append(&dfgCommon->weakStructureReferences[i]);
2813 #endif    
2814 }
2815
2816 CodeBlock* CodeBlock::baselineAlternative()
2817 {
2818 #if ENABLE(JIT)
2819     CodeBlock* result = this;
2820     while (result->alternative())
2821         result = result->alternative();
2822     RELEASE_ASSERT(result);
2823     RELEASE_ASSERT(JITCode::isBaselineCode(result->jitType()) || result->jitType() == JITCode::None);
2824     return result;
2825 #else
2826     return this;
2827 #endif
2828 }
2829
2830 CodeBlock* CodeBlock::baselineVersion()
2831 {
2832 #if ENABLE(JIT)
2833     if (JITCode::isBaselineCode(jitType()))
2834         return this;
2835     CodeBlock* result = replacement();
2836     if (!result) {
2837         // This can happen if we're creating the original CodeBlock for an executable.
2838         // Assume that we're the baseline CodeBlock.
2839         RELEASE_ASSERT(jitType() == JITCode::None);
2840         return this;
2841     }
2842     result = result->baselineAlternative();
2843     return result;
2844 #else
2845     return this;
2846 #endif
2847 }
2848
2849 #if ENABLE(JIT)
2850 bool CodeBlock::hasOptimizedReplacement(JITCode::JITType typeToReplace)
2851 {
2852     return JITCode::isHigherTier(replacement()->jitType(), typeToReplace);
2853 }
2854
2855 bool CodeBlock::hasOptimizedReplacement()
2856 {
2857     return hasOptimizedReplacement(jitType());
2858 }
2859 #endif
2860
2861 bool CodeBlock::isCaptured(VirtualRegister operand, InlineCallFrame* inlineCallFrame) const
2862 {
2863     if (operand.isArgument())
2864         return operand.toArgument() && usesArguments();
2865
2866     if (inlineCallFrame)
2867         return inlineCallFrame->capturedVars.get(operand.toLocal());
2868
2869     // The lexical environment object isn't in the captured region, but it's "captured"
2870     // in the sense that stores to its location can be observed indirectly.
2871     if (needsActivation() && operand == activationRegister())
2872         return true;
2873
2874     // Ditto for the arguments object.
2875     if (usesArguments() && operand == argumentsRegister())
2876         return true;
2877     if (usesArguments() && operand == unmodifiedArgumentsRegister(argumentsRegister()))
2878         return true;
2879
2880     // We're in global code so there are no locals to capture
2881     if (!symbolTable())
2882         return false;
2883
2884     return symbolTable()->isCaptured(operand.offset());
2885 }
2886
2887 int CodeBlock::framePointerOffsetToGetActivationRegisters(int machineCaptureStart)
2888 {
2889     // We'll be adding this to the stack pointer to get a registers pointer that looks
2890     // like it would have looked in the baseline engine. For example, if bytecode would
2891     // have put the first captured variable at offset -5 but we put it at offset -1, then
2892     // we'll have an offset of 4.
2893     int32_t offset = 0;
2894     
2895     // Compute where we put the captured variables. This offset will point the registers
2896     // pointer directly at the first captured var.
2897     offset += machineCaptureStart;
2898     
2899     // Now compute the offset needed to make the runtime see the captured variables at the
2900     // same offset that the bytecode would have used.
2901     offset -= symbolTable()->captureStart();
2902     
2903     return offset;
2904 }
2905
2906 int CodeBlock::framePointerOffsetToGetActivationRegisters()
2907 {
2908     if (!JITCode::isOptimizingJIT(jitType()))
2909         return 0;
2910 #if ENABLE(DFG_JIT)
2911     return framePointerOffsetToGetActivationRegisters(jitCode()->dfgCommon()->machineCaptureStart);
2912 #else
2913     RELEASE_ASSERT_NOT_REACHED();
2914     return 0;
2915 #endif
2916 }
2917
2918 HandlerInfo* CodeBlock::handlerForBytecodeOffset(unsigned bytecodeOffset)
2919 {
2920     RELEASE_ASSERT(bytecodeOffset < instructions().size());
2921
2922     if (!m_rareData)
2923         return 0;
2924     
2925     Vector<HandlerInfo>& exceptionHandlers = m_rareData->m_exceptionHandlers;
2926     for (size_t i = 0; i < exceptionHandlers.size(); ++i) {
2927         // Handlers are ordered innermost first, so the first handler we encounter
2928         // that contains the source address is the correct handler to use.
2929         if (exceptionHandlers[i].start <= bytecodeOffset && exceptionHandlers[i].end > bytecodeOffset)
2930             return &exceptionHandlers[i];
2931     }
2932
2933     return 0;
2934 }
2935
2936 unsigned CodeBlock::lineNumberForBytecodeOffset(unsigned bytecodeOffset)
2937 {
2938     RELEASE_ASSERT(bytecodeOffset < instructions().size());
2939     return m_ownerExecutable->lineNo() + m_unlinkedCode->lineNumberForBytecodeOffset(bytecodeOffset);
2940 }
2941
2942 unsigned CodeBlock::columnNumberForBytecodeOffset(unsigned bytecodeOffset)
2943 {
2944     int divot;
2945     int startOffset;
2946     int endOffset;
2947     unsigned line;
2948     unsigned column;
2949     expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
2950     return column;
2951 }
2952
2953 void CodeBlock::expressionRangeForBytecodeOffset(unsigned bytecodeOffset, int& divot, int& startOffset, int& endOffset, unsigned& line, unsigned& column)
2954 {
2955     m_unlinkedCode->expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
2956     divot += m_sourceOffset;
2957     column += line ? 1 : firstLineColumnOffset();
2958     line += m_ownerExecutable->lineNo();
2959 }
2960
2961 bool CodeBlock::hasOpDebugForLineAndColumn(unsigned line, unsigned column)
2962 {
2963     Interpreter* interpreter = vm()->interpreter;
2964     const Instruction* begin = instructions().begin();
2965     const Instruction* end = instructions().end();
2966     for (const Instruction* it = begin; it != end;) {
2967         OpcodeID opcodeID = interpreter->getOpcodeID(it->u.opcode);
2968         if (opcodeID == op_debug) {
2969             unsigned bytecodeOffset = it - begin;
2970             int unused;
2971             unsigned opDebugLine;
2972             unsigned opDebugColumn;
2973             expressionRangeForBytecodeOffset(bytecodeOffset, unused, unused, unused, opDebugLine, opDebugColumn);
2974             if (line == opDebugLine && (column == Breakpoint::unspecifiedColumn || column == opDebugColumn))
2975                 return true;
2976         }
2977         it += opcodeLengths[opcodeID];
2978     }
2979     return false;
2980 }
2981
2982 void CodeBlock::shrinkToFit(ShrinkMode shrinkMode)
2983 {
2984     m_rareCaseProfiles.shrinkToFit();
2985     m_specialFastCaseProfiles.shrinkToFit();
2986     
2987     if (shrinkMode == EarlyShrink) {
2988         m_constantRegisters.shrinkToFit();
2989         
2990         if (m_rareData) {
2991             m_rareData->m_switchJumpTables.shrinkToFit();
2992             m_rareData->m_stringSwitchJumpTables.shrinkToFit();
2993         }
2994     } // else don't shrink these, because we would have already pointed pointers into these tables.
2995 }
2996
2997 unsigned CodeBlock::addOrFindConstant(JSValue v)
2998 {
2999     unsigned result;
3000     if (findConstant(v, result))
3001         return result;
3002     return addConstant(v);
3003 }
3004
3005 bool CodeBlock::findConstant(JSValue v, unsigned& index)
3006 {
3007     unsigned numberOfConstants = numberOfConstantRegisters();
3008     for (unsigned i = 0; i < numberOfConstants; ++i) {
3009         if (getConstant(FirstConstantRegisterIndex + i) == v) {
3010             index = i;
3011             return true;
3012         }
3013     }
3014     index = numberOfConstants;
3015     return false;
3016 }
3017
3018 #if ENABLE(JIT)
3019 void CodeBlock::unlinkCalls()
3020 {
3021     if (!!m_alternative)
3022         m_alternative->unlinkCalls();
3023     for (size_t i = 0; i < m_llintCallLinkInfos.size(); ++i) {
3024         if (m_llintCallLinkInfos[i].isLinked())
3025             m_llintCallLinkInfos[i].unlink();
3026     }
3027     if (m_callLinkInfos.isEmpty())
3028         return;
3029     if (!m_vm->canUseJIT())
3030         return;
3031     RepatchBuffer repatchBuffer(this);
3032     for (auto iter = m_callLinkInfos.begin(); !!iter; ++iter) {
3033         CallLinkInfo& info = **iter;
3034         if (!info.isLinked())
3035             continue;
3036         info.unlink(repatchBuffer);
3037     }
3038 }
3039
3040 void CodeBlock::linkIncomingCall(ExecState* callerFrame, CallLinkInfo* incoming)
3041 {
3042     noticeIncomingCall(callerFrame);
3043     m_incomingCalls.push(incoming);
3044 }
3045
3046 void CodeBlock::linkIncomingPolymorphicCall(ExecState* callerFrame, PolymorphicCallNode* incoming)
3047 {
3048     noticeIncomingCall(callerFrame);
3049     m_incomingPolymorphicCalls.push(incoming);
3050 }
3051 #endif // ENABLE(JIT)
3052
3053 void CodeBlock::unlinkIncomingCalls()
3054 {
3055     while (m_incomingLLIntCalls.begin() != m_incomingLLIntCalls.end())
3056         m_incomingLLIntCalls.begin()->unlink();
3057 #if ENABLE(JIT)
3058     if (m_incomingCalls.isEmpty() && m_incomingPolymorphicCalls.isEmpty())
3059         return;
3060     RepatchBuffer repatchBuffer(this);
3061     while (m_incomingCalls.begin() != m_incomingCalls.end())
3062         m_incomingCalls.begin()->unlink(repatchBuffer);
3063     while (m_incomingPolymorphicCalls.begin() != m_incomingPolymorphicCalls.end())
3064         m_incomingPolymorphicCalls.begin()->unlink(repatchBuffer);
3065 #endif // ENABLE(JIT)
3066 }
3067
3068 void CodeBlock::linkIncomingCall(ExecState* callerFrame, LLIntCallLinkInfo* incoming)
3069 {
3070     noticeIncomingCall(callerFrame);
3071     m_incomingLLIntCalls.push(incoming);
3072 }
3073
3074 void CodeBlock::clearEvalCache()
3075 {
3076     if (!!m_alternative)
3077         m_alternative->clearEvalCache();
3078     if (CodeBlock* otherBlock = specialOSREntryBlockOrNull())
3079         otherBlock->clearEvalCache();
3080     if (!m_rareData)
3081         return;
3082     m_rareData->m_evalCodeCache.clear();
3083 }
3084
3085 void CodeBlock::install()
3086 {
3087     ownerExecutable()->installCode(this);
3088 }
3089
3090 PassRefPtr<CodeBlock> CodeBlock::newReplacement()
3091 {
3092     return ownerExecutable()->newReplacementCodeBlockFor(specializationKind());
3093 }
3094
3095 const SlowArgument* CodeBlock::machineSlowArguments()
3096 {
3097     if (!JITCode::isOptimizingJIT(jitType()))
3098         return symbolTable()->slowArguments();
3099     
3100 #if ENABLE(DFG_JIT)
3101     return jitCode()->dfgCommon()->slowArguments.get();
3102 #else // ENABLE(DFG_JIT)
3103     return 0;
3104 #endif // ENABLE(DFG_JIT)
3105 }
3106
3107 #if ENABLE(JIT)
3108 CodeBlock* ProgramCodeBlock::replacement()
3109 {
3110     return jsCast<ProgramExecutable*>(ownerExecutable())->codeBlock();
3111 }
3112
3113 CodeBlock* EvalCodeBlock::replacement()
3114 {
3115     return jsCast<EvalExecutable*>(ownerExecutable())->codeBlock();
3116 }
3117
3118 CodeBlock* FunctionCodeBlock::replacement()
3119 {
3120     return jsCast<FunctionExecutable*>(ownerExecutable())->codeBlockFor(m_isConstructor ? CodeForConstruct : CodeForCall);
3121 }
3122
3123 DFG::CapabilityLevel ProgramCodeBlock::capabilityLevelInternal()
3124 {
3125     return DFG::programCapabilityLevel(this);
3126 }
3127
3128 DFG::CapabilityLevel EvalCodeBlock::capabilityLevelInternal()
3129 {
3130     return DFG::evalCapabilityLevel(this);
3131 }
3132
3133 DFG::CapabilityLevel FunctionCodeBlock::capabilityLevelInternal()
3134 {
3135     if (m_isConstructor)
3136         return DFG::functionForConstructCapabilityLevel(this);
3137     return DFG::functionForCallCapabilityLevel(this);
3138 }
3139 #endif
3140
3141 void CodeBlock::jettison(Profiler::JettisonReason reason, ReoptimizationMode mode, const FireDetail* detail)
3142 {
3143     RELEASE_ASSERT(reason != Profiler::NotJettisoned);
3144     
3145 #if ENABLE(DFG_JIT)
3146     if (DFG::shouldShowDisassembly()) {
3147         dataLog("Jettisoning ", *this);
3148         if (mode == CountReoptimization)
3149             dataLog(" and counting reoptimization");
3150         dataLog(" due to ", reason);
3151         if (detail)
3152             dataLog(", ", *detail);
3153         dataLog(".\n");
3154     }
3155     
3156     DeferGCForAWhile deferGC(*m_heap);
3157     RELEASE_ASSERT(JITCode::isOptimizingJIT(jitType()));
3158     
3159     if (Profiler::Compilation* compilation = jitCode()->dfgCommon()->compilation.get())
3160         compilation->setJettisonReason(reason, detail);
3161     
3162     // We want to accomplish two things here:
3163     // 1) Make sure that if this CodeBlock is on the stack right now, then if we return to it
3164     //    we should OSR exit at the top of the next bytecode instruction after the return.
3165     // 2) Make sure that if we call the owner executable, then we shouldn't call this CodeBlock.
3166     
3167     // This accomplishes the OSR-exit-on-return part, and does its own book-keeping about
3168     // whether the invalidation has already happened.
3169     if (!jitCode()->dfgCommon()->invalidate()) {
3170         // Nothing to do since we've already been invalidated. That means that we cannot be
3171         // the optimized replacement.
3172         RELEASE_ASSERT(this != replacement());
3173         return;
3174     }
3175     
3176     if (DFG::shouldShowDisassembly())
3177         dataLog("    Did invalidate ", *this, "\n");
3178     
3179     // Count the reoptimization if that's what the user wanted.
3180     if (mode == CountReoptimization) {
3181         // FIXME: Maybe this should call alternative().
3182         // https://bugs.webkit.org/show_bug.cgi?id=123677
3183         baselineAlternative()->countReoptimization();
3184         if (DFG::shouldShowDisassembly())
3185             dataLog("    Did count reoptimization for ", *this, "\n");
3186     }
3187     
3188     // Now take care of the entrypoint.
3189     if (this != replacement()) {
3190         // This means that we were never the entrypoint. This can happen for OSR entry code
3191         // blocks.
3192         return;
3193     }
3194     alternative()->optimizeAfterWarmUp();
3195     tallyFrequentExitSites();
3196     alternative()->install();
3197     if