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