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