1f9406644ee1ee5fcbd0f3a8388a52ed4a67cb18
[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     ASSERT(m_heap->isDeferred());
1508     setNumParameters(other.numParameters());
1509     optimizeAfterWarmUp();
1510     jitAfterWarmUp();
1511
1512     if (other.m_rareData) {
1513         createRareDataIfNecessary();
1514         
1515         m_rareData->m_exceptionHandlers = other.m_rareData->m_exceptionHandlers;
1516         m_rareData->m_constantBuffers = other.m_rareData->m_constantBuffers;
1517         m_rareData->m_switchJumpTables = other.m_rareData->m_switchJumpTables;
1518         m_rareData->m_stringSwitchJumpTables = other.m_rareData->m_stringSwitchJumpTables;
1519     }
1520     
1521     m_heap->m_codeBlocks.add(this);
1522     m_heap->reportExtraMemoryCost(sizeof(CodeBlock));
1523 }
1524
1525 CodeBlock::CodeBlock(ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock, JSScope* scope, PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset, unsigned firstLineColumnOffset)
1526     : m_globalObject(scope->globalObject()->vm(), ownerExecutable, scope->globalObject())
1527     , m_heap(&m_globalObject->vm().heap)
1528     , m_numCalleeRegisters(unlinkedCodeBlock->m_numCalleeRegisters)
1529     , m_numVars(unlinkedCodeBlock->m_numVars)
1530     , m_isConstructor(unlinkedCodeBlock->isConstructor())
1531     , m_shouldAlwaysBeInlined(true)
1532     , m_unlinkedCode(m_globalObject->vm(), ownerExecutable, unlinkedCodeBlock)
1533     , m_ownerExecutable(m_globalObject->vm(), ownerExecutable, ownerExecutable)
1534     , m_vm(unlinkedCodeBlock->vm())
1535     , m_thisRegister(unlinkedCodeBlock->thisRegister())
1536     , m_argumentsRegister(unlinkedCodeBlock->argumentsRegister())
1537     , m_activationRegister(unlinkedCodeBlock->activationRegister())
1538     , m_isStrictMode(unlinkedCodeBlock->isStrictMode())
1539     , m_needsActivation(unlinkedCodeBlock->needsFullScopeChain() && unlinkedCodeBlock->codeType() == FunctionCode)
1540     , m_source(sourceProvider)
1541     , m_sourceOffset(sourceOffset)
1542     , m_firstLineColumnOffset(firstLineColumnOffset)
1543     , m_codeType(unlinkedCodeBlock->codeType())
1544     , m_osrExitCounter(0)
1545     , m_optimizationDelayCounter(0)
1546     , m_reoptimizationRetryCounter(0)
1547 #if ENABLE(JIT)
1548     , m_capabilityLevelState(DFG::CapabilityLevelNotSet)
1549 #endif
1550 {
1551     ASSERT(m_heap->isDeferred());
1552
1553     ASSERT(m_source);
1554     setNumParameters(unlinkedCodeBlock->numParameters());
1555
1556 #if DUMP_CODE_BLOCK_STATISTICS
1557     liveCodeBlockSet.add(this);
1558 #endif
1559
1560     setConstantRegisters(unlinkedCodeBlock->constantRegisters());
1561     if (unlinkedCodeBlock->usesGlobalObject())
1562         m_constantRegisters[unlinkedCodeBlock->globalObjectRegister()].set(*m_vm, ownerExecutable, m_globalObject.get());
1563     m_functionDecls.grow(unlinkedCodeBlock->numberOfFunctionDecls());
1564     for (size_t count = unlinkedCodeBlock->numberOfFunctionDecls(), i = 0; i < count; ++i) {
1565         UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionDecl(i);
1566         unsigned lineCount = unlinkedExecutable->lineCount();
1567         unsigned firstLine = ownerExecutable->lineNo() + unlinkedExecutable->firstLineOffset();
1568         unsigned startColumn = unlinkedExecutable->functionStartColumn();
1569         startColumn += (unlinkedExecutable->firstLineOffset() ? 1 : ownerExecutable->startColumn());
1570         unsigned startOffset = sourceOffset + unlinkedExecutable->startOffset();
1571         unsigned sourceLength = unlinkedExecutable->sourceLength();
1572         SourceCode code(m_source, startOffset, startOffset + sourceLength, firstLine, startColumn);
1573         FunctionExecutable* executable = FunctionExecutable::create(*m_vm, code, unlinkedExecutable, firstLine, firstLine + lineCount, startColumn);
1574         m_functionDecls[i].set(*m_vm, ownerExecutable, executable);
1575     }
1576
1577     m_functionExprs.grow(unlinkedCodeBlock->numberOfFunctionExprs());
1578     for (size_t count = unlinkedCodeBlock->numberOfFunctionExprs(), i = 0; i < count; ++i) {
1579         UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionExpr(i);
1580         unsigned lineCount = unlinkedExecutable->lineCount();
1581         unsigned firstLine = ownerExecutable->lineNo() + unlinkedExecutable->firstLineOffset();
1582         unsigned startColumn = unlinkedExecutable->functionStartColumn();
1583         startColumn += (unlinkedExecutable->firstLineOffset() ? 1 : ownerExecutable->startColumn());
1584         unsigned startOffset = sourceOffset + unlinkedExecutable->startOffset();
1585         unsigned sourceLength = unlinkedExecutable->sourceLength();
1586         SourceCode code(m_source, startOffset, startOffset + sourceLength, firstLine, startColumn);
1587         FunctionExecutable* executable = FunctionExecutable::create(*m_vm, code, unlinkedExecutable, firstLine, firstLine + lineCount, startColumn);
1588         m_functionExprs[i].set(*m_vm, ownerExecutable, executable);
1589     }
1590
1591     if (unlinkedCodeBlock->hasRareData()) {
1592         createRareDataIfNecessary();
1593         if (size_t count = unlinkedCodeBlock->constantBufferCount()) {
1594             m_rareData->m_constantBuffers.grow(count);
1595             for (size_t i = 0; i < count; i++) {
1596                 const UnlinkedCodeBlock::ConstantBuffer& buffer = unlinkedCodeBlock->constantBuffer(i);
1597                 m_rareData->m_constantBuffers[i] = buffer;
1598             }
1599         }
1600         if (size_t count = unlinkedCodeBlock->numberOfExceptionHandlers()) {
1601             m_rareData->m_exceptionHandlers.grow(count);
1602             size_t nonLocalScopeDepth = scope->depth();
1603             for (size_t i = 0; i < count; i++) {
1604                 const UnlinkedHandlerInfo& handler = unlinkedCodeBlock->exceptionHandler(i);
1605                 m_rareData->m_exceptionHandlers[i].start = handler.start;
1606                 m_rareData->m_exceptionHandlers[i].end = handler.end;
1607                 m_rareData->m_exceptionHandlers[i].target = handler.target;
1608                 m_rareData->m_exceptionHandlers[i].scopeDepth = nonLocalScopeDepth + handler.scopeDepth;
1609 #if ENABLE(JIT) && ENABLE(LLINT)
1610                 m_rareData->m_exceptionHandlers[i].nativeCode = CodeLocationLabel(MacroAssemblerCodePtr::createFromExecutableAddress(LLInt::getCodePtr(llint_op_catch)));
1611 #endif
1612             }
1613         }
1614
1615         if (size_t count = unlinkedCodeBlock->numberOfStringSwitchJumpTables()) {
1616             m_rareData->m_stringSwitchJumpTables.grow(count);
1617             for (size_t i = 0; i < count; i++) {
1618                 UnlinkedStringJumpTable::StringOffsetTable::iterator ptr = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.begin();
1619                 UnlinkedStringJumpTable::StringOffsetTable::iterator end = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.end();
1620                 for (; ptr != end; ++ptr) {
1621                     OffsetLocation offset;
1622                     offset.branchOffset = ptr->value;
1623                     m_rareData->m_stringSwitchJumpTables[i].offsetTable.add(ptr->key, offset);
1624                 }
1625             }
1626         }
1627
1628         if (size_t count = unlinkedCodeBlock->numberOfSwitchJumpTables()) {
1629             m_rareData->m_switchJumpTables.grow(count);
1630             for (size_t i = 0; i < count; i++) {
1631                 UnlinkedSimpleJumpTable& sourceTable = unlinkedCodeBlock->switchJumpTable(i);
1632                 SimpleJumpTable& destTable = m_rareData->m_switchJumpTables[i];
1633                 destTable.branchOffsets = sourceTable.branchOffsets;
1634                 destTable.min = sourceTable.min;
1635             }
1636         }
1637     }
1638
1639     // Allocate metadata buffers for the bytecode
1640 #if ENABLE(LLINT)
1641     if (size_t size = unlinkedCodeBlock->numberOfLLintCallLinkInfos())
1642         m_llintCallLinkInfos.resizeToFit(size);
1643 #endif
1644 #if ENABLE(DFG_JIT)
1645     if (size_t size = unlinkedCodeBlock->numberOfArrayProfiles())
1646         m_arrayProfiles.grow(size);
1647     if (size_t size = unlinkedCodeBlock->numberOfArrayAllocationProfiles())
1648         m_arrayAllocationProfiles.grow(size);
1649     if (size_t size = unlinkedCodeBlock->numberOfValueProfiles())
1650         m_valueProfiles.grow(size);
1651 #endif
1652     if (size_t size = unlinkedCodeBlock->numberOfObjectAllocationProfiles())
1653         m_objectAllocationProfiles.grow(size);
1654
1655     // Copy and translate the UnlinkedInstructions
1656     size_t instructionCount = unlinkedCodeBlock->instructions().size();
1657     UnlinkedInstruction* pc = unlinkedCodeBlock->instructions().data();
1658     Vector<Instruction, 0, UnsafeVectorOverflow> instructions(instructionCount);
1659     for (size_t i = 0; i < unlinkedCodeBlock->instructions().size(); ) {
1660         unsigned opLength = opcodeLength(pc[i].u.opcode);
1661         instructions[i] = vm()->interpreter->getOpcode(pc[i].u.opcode);
1662         for (size_t j = 1; j < opLength; ++j) {
1663             if (sizeof(int32_t) != sizeof(intptr_t))
1664                 instructions[i + j].u.pointer = 0;
1665             instructions[i + j].u.operand = pc[i + j].u.operand;
1666         }
1667         switch (pc[i].u.opcode) {
1668 #if ENABLE(DFG_JIT)
1669         case op_get_by_val:
1670         case op_get_argument_by_val: {
1671             int arrayProfileIndex = pc[i + opLength - 2].u.operand;
1672             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
1673
1674             instructions[i + opLength - 2] = &m_arrayProfiles[arrayProfileIndex];
1675             // fallthrough
1676         }
1677         case op_to_this:
1678         case op_get_by_id:
1679         case op_call_varargs:
1680         case op_get_callee: {
1681             ValueProfile* profile = &m_valueProfiles[pc[i + opLength - 1].u.operand];
1682             ASSERT(profile->m_bytecodeOffset == -1);
1683             profile->m_bytecodeOffset = i;
1684             instructions[i + opLength - 1] = profile;
1685             break;
1686         }
1687         case op_put_by_val: {
1688             int arrayProfileIndex = pc[i + opLength - 1].u.operand;
1689             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
1690             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
1691             break;
1692         }
1693
1694         case op_new_array:
1695         case op_new_array_buffer:
1696         case op_new_array_with_size: {
1697             int arrayAllocationProfileIndex = pc[i + opLength - 1].u.operand;
1698             instructions[i + opLength - 1] = &m_arrayAllocationProfiles[arrayAllocationProfileIndex];
1699             break;
1700         }
1701 #endif
1702         case op_new_object: {
1703             int objectAllocationProfileIndex = pc[i + opLength - 1].u.operand;
1704             ObjectAllocationProfile* objectAllocationProfile = &m_objectAllocationProfiles[objectAllocationProfileIndex];
1705             int inferredInlineCapacity = pc[i + opLength - 2].u.operand;
1706
1707             instructions[i + opLength - 1] = objectAllocationProfile;
1708             objectAllocationProfile->initialize(*vm(),
1709                 m_ownerExecutable.get(), m_globalObject->objectPrototype(), inferredInlineCapacity);
1710             break;
1711         }
1712
1713         case op_call:
1714         case op_call_eval: {
1715 #if ENABLE(DFG_JIT)
1716             ValueProfile* profile = &m_valueProfiles[pc[i + opLength - 1].u.operand];
1717             ASSERT(profile->m_bytecodeOffset == -1);
1718             profile->m_bytecodeOffset = i;
1719             instructions[i + opLength - 1] = profile;
1720             int arrayProfileIndex = pc[i + opLength - 2].u.operand;
1721             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
1722             instructions[i + opLength - 2] = &m_arrayProfiles[arrayProfileIndex];
1723 #endif
1724 #if ENABLE(LLINT)
1725             instructions[i + 5] = &m_llintCallLinkInfos[pc[i + 5].u.operand];
1726 #endif
1727             break;
1728         }
1729         case op_construct: {
1730 #if ENABLE(LLINT)
1731             instructions[i + 5] = &m_llintCallLinkInfos[pc[i + 5].u.operand];
1732 #endif
1733 #if ENABLE(DFG_JIT)
1734             ValueProfile* profile = &m_valueProfiles[pc[i + opLength - 1].u.operand];
1735             ASSERT(profile->m_bytecodeOffset == -1);
1736             profile->m_bytecodeOffset = i;
1737             instructions[i + opLength - 1] = profile;
1738 #endif
1739             break;
1740         }
1741         case op_get_by_id_out_of_line:
1742         case op_get_by_id_self:
1743         case op_get_by_id_proto:
1744         case op_get_by_id_chain:
1745         case op_get_by_id_getter_self:
1746         case op_get_by_id_getter_proto:
1747         case op_get_by_id_getter_chain:
1748         case op_get_by_id_custom_self:
1749         case op_get_by_id_custom_proto:
1750         case op_get_by_id_custom_chain:
1751         case op_get_by_id_generic:
1752         case op_get_array_length:
1753         case op_get_string_length:
1754             CRASH();
1755
1756         case op_init_global_const_nop: {
1757             ASSERT(codeType() == GlobalCode);
1758             Identifier ident = identifier(pc[i + 4].u.operand);
1759             SymbolTableEntry entry = m_globalObject->symbolTable()->get(ident.impl());
1760             if (entry.isNull())
1761                 break;
1762
1763             // It's likely that we'll write to this var, so notify now and avoid the overhead of doing so at runtime.
1764             entry.notifyWrite();
1765
1766             instructions[i + 0] = vm()->interpreter->getOpcode(op_init_global_const);
1767             instructions[i + 1] = &m_globalObject->registerAt(entry.getIndex());
1768             break;
1769         }
1770
1771         case op_resolve_scope: {
1772             const Identifier& ident = identifier(pc[i + 2].u.operand);
1773             ResolveType type = static_cast<ResolveType>(pc[i + 3].u.operand);
1774
1775             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), scope, ident, Get, type);
1776             instructions[i + 3].u.operand = op.type;
1777             instructions[i + 4].u.operand = op.depth;
1778             break;
1779         }
1780
1781         case op_get_from_scope: {
1782 #if ENABLE(VALUE_PROFILER)
1783             ValueProfile* profile = &m_valueProfiles[pc[i + opLength - 1].u.operand];
1784             ASSERT(profile->m_bytecodeOffset == -1);
1785             profile->m_bytecodeOffset = i;
1786             instructions[i + opLength - 1] = profile;
1787 #endif
1788
1789             // get_from_scope dst, scope, id, ResolveModeAndType, Structure, Operand
1790             const Identifier& ident = identifier(pc[i + 3].u.operand);
1791             ResolveModeAndType modeAndType = ResolveModeAndType(pc[i + 4].u.operand);
1792             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), scope, ident, Get, modeAndType.type());
1793
1794             instructions[i + 4].u.operand = ResolveModeAndType(modeAndType.mode(), op.type).operand();
1795             if (op.structure)
1796                 instructions[i + 5].u.structure.set(*vm(), ownerExecutable, op.structure);
1797             instructions[i + 6].u.pointer = reinterpret_cast<void*>(op.operand);
1798             break;
1799         }
1800
1801         case op_put_to_scope: {
1802             // put_to_scope scope, id, value, ResolveModeAndType, Structure, Operand
1803             const Identifier& ident = identifier(pc[i + 2].u.operand);
1804             ResolveModeAndType modeAndType = ResolveModeAndType(pc[i + 4].u.operand);
1805             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), scope, ident, Put, modeAndType.type());
1806
1807             instructions[i + 4].u.operand = ResolveModeAndType(modeAndType.mode(), op.type).operand();
1808             if (op.structure)
1809                 instructions[i + 5].u.structure.set(*vm(), ownerExecutable, op.structure);
1810             instructions[i + 6].u.pointer = reinterpret_cast<void*>(op.operand);
1811             break;
1812         }
1813
1814         case op_debug: {
1815             instructions[i + 4] = columnNumberForBytecodeOffset(i);
1816             break;
1817         }
1818
1819         default:
1820             break;
1821         }
1822         i += opLength;
1823     }
1824     m_instructions = WTF::RefCountedArray<Instruction>(instructions);
1825
1826     // Set optimization thresholds only after m_instructions is initialized, since these
1827     // rely on the instruction count (and are in theory permitted to also inspect the
1828     // instruction stream to more accurate assess the cost of tier-up).
1829     optimizeAfterWarmUp();
1830     jitAfterWarmUp();
1831
1832     // If the concurrent thread will want the code block's hash, then compute it here
1833     // synchronously.
1834     if (Options::showDisassembly()
1835         || Options::showDFGDisassembly()
1836         || Options::dumpBytecodeAtDFGTime()
1837         || Options::verboseCompilation()
1838         || Options::logCompilationChanges()
1839         || Options::validateGraph()
1840         || Options::validateGraphAtEachPhase()
1841         || Options::verboseOSR()
1842         || Options::verboseCompilationQueue()
1843         || Options::reportCompileTimes()
1844         || Options::verboseCFA())
1845         hash();
1846
1847     if (Options::dumpGeneratedBytecodes())
1848         dumpBytecode();
1849     m_heap->m_codeBlocks.add(this);
1850     m_heap->reportExtraMemoryCost(sizeof(CodeBlock) + m_instructions.size() * sizeof(Instruction));
1851 }
1852
1853 CodeBlock::~CodeBlock()
1854 {
1855     if (m_vm->m_perBytecodeProfiler)
1856         m_vm->m_perBytecodeProfiler->notifyDestruction(this);
1857     
1858 #if ENABLE(VERBOSE_VALUE_PROFILE)
1859     dumpValueProfiles();
1860 #endif
1861
1862 #if ENABLE(LLINT)    
1863     while (m_incomingLLIntCalls.begin() != m_incomingLLIntCalls.end())
1864         m_incomingLLIntCalls.begin()->remove();
1865 #endif // ENABLE(LLINT)
1866 #if ENABLE(JIT)
1867     // We may be destroyed before any CodeBlocks that refer to us are destroyed.
1868     // Consider that two CodeBlocks become unreachable at the same time. There
1869     // is no guarantee about the order in which the CodeBlocks are destroyed.
1870     // So, if we don't remove incoming calls, and get destroyed before the
1871     // CodeBlock(s) that have calls into us, then the CallLinkInfo vector's
1872     // destructor will try to remove nodes from our (no longer valid) linked list.
1873     while (m_incomingCalls.begin() != m_incomingCalls.end())
1874         m_incomingCalls.begin()->remove();
1875     
1876     // Note that our outgoing calls will be removed from other CodeBlocks'
1877     // m_incomingCalls linked lists through the execution of the ~CallLinkInfo
1878     // destructors.
1879
1880     for (size_t size = m_structureStubInfos.size(), i = 0; i < size; ++i)
1881         m_structureStubInfos[i].deref();
1882 #endif // ENABLE(JIT)
1883
1884 #if DUMP_CODE_BLOCK_STATISTICS
1885     liveCodeBlockSet.remove(this);
1886 #endif
1887 }
1888
1889 void CodeBlock::setNumParameters(int newValue)
1890 {
1891     m_numParameters = newValue;
1892
1893 #if ENABLE(VALUE_PROFILER)
1894     m_argumentValueProfiles.resizeToFit(newValue);
1895 #endif
1896 }
1897
1898 void EvalCodeCache::visitAggregate(SlotVisitor& visitor)
1899 {
1900     EvalCacheMap::iterator end = m_cacheMap.end();
1901     for (EvalCacheMap::iterator ptr = m_cacheMap.begin(); ptr != end; ++ptr)
1902         visitor.append(&ptr->value);
1903 }
1904
1905 void CodeBlock::visitAggregate(SlotVisitor& visitor)
1906 {
1907 #if ENABLE(PARALLEL_GC)
1908     // I may be asked to scan myself more than once, and it may even happen concurrently.
1909     // To this end, use a CAS loop to check if I've been called already. Only one thread
1910     // may proceed past this point - whichever one wins the CAS race.
1911     unsigned oldValue;
1912     do {
1913         oldValue = m_visitAggregateHasBeenCalled;
1914         if (oldValue) {
1915             // Looks like someone else won! Return immediately to ensure that we don't
1916             // trace the same CodeBlock concurrently. Doing so is hazardous since we will
1917             // be mutating the state of ValueProfiles, which contain JSValues, which can
1918             // have word-tearing on 32-bit, leading to awesome timing-dependent crashes
1919             // that are nearly impossible to track down.
1920             
1921             // Also note that it must be safe to return early as soon as we see the
1922             // value true (well, (unsigned)1), since once a GC thread is in this method
1923             // and has won the CAS race (i.e. was responsible for setting the value true)
1924             // it will definitely complete the rest of this method before declaring
1925             // termination.
1926             return;
1927         }
1928     } while (!WTF::weakCompareAndSwap(&m_visitAggregateHasBeenCalled, 0, 1));
1929 #endif // ENABLE(PARALLEL_GC)
1930     
1931     if (!!m_alternative)
1932         m_alternative->visitAggregate(visitor);
1933
1934     visitor.reportExtraMemoryUsage(sizeof(CodeBlock));
1935     if (m_jitCode)
1936         visitor.reportExtraMemoryUsage(m_jitCode->size());
1937     if (m_instructions.size()) {
1938         // Divide by refCount() because m_instructions points to something that is shared
1939         // by multiple CodeBlocks, and we only want to count it towards the heap size once.
1940         // Having each CodeBlock report only its proportional share of the size is one way
1941         // of accomplishing this.
1942         visitor.reportExtraMemoryUsage(m_instructions.size() * sizeof(Instruction) / m_instructions.refCount());
1943     }
1944
1945     visitor.append(&m_unlinkedCode);
1946
1947     // There are three things that may use unconditional finalizers: lazy bytecode freeing,
1948     // inline cache clearing, and jettisoning. The probability of us wanting to do at
1949     // least one of those things is probably quite close to 1. So we add one no matter what
1950     // and when it runs, it figures out whether it has any work to do.
1951     visitor.addUnconditionalFinalizer(this);
1952     
1953     // There are two things that we use weak reference harvesters for: DFG fixpoint for
1954     // jettisoning, and trying to find structures that would be live based on some
1955     // inline cache. So it makes sense to register them regardless.
1956     visitor.addWeakReferenceHarvester(this);
1957     m_allTransitionsHaveBeenMarked = false;
1958     
1959     if (shouldImmediatelyAssumeLivenessDuringScan()) {
1960         // This code block is live, so scan all references strongly and return.
1961         stronglyVisitStrongReferences(visitor);
1962         stronglyVisitWeakReferences(visitor);
1963         propagateTransitions(visitor);
1964         return;
1965     }
1966     
1967 #if ENABLE(DFG_JIT)
1968     // We get here if we're live in the sense that our owner executable is live,
1969     // but we're not yet live for sure in another sense: we may yet decide that this
1970     // code block should be jettisoned based on its outgoing weak references being
1971     // stale. Set a flag to indicate that we're still assuming that we're dead, and
1972     // perform one round of determining if we're live. The GC may determine, based on
1973     // either us marking additional objects, or by other objects being marked for
1974     // other reasons, that this iteration should run again; it will notify us of this
1975     // decision by calling harvestWeakReferences().
1976     
1977     m_jitCode->dfgCommon()->livenessHasBeenProved = false;
1978     
1979     propagateTransitions(visitor);
1980     determineLiveness(visitor);
1981 #else // ENABLE(DFG_JIT)
1982     RELEASE_ASSERT_NOT_REACHED();
1983 #endif // ENABLE(DFG_JIT)
1984 }
1985
1986 void CodeBlock::propagateTransitions(SlotVisitor& visitor)
1987 {
1988     UNUSED_PARAM(visitor);
1989
1990     if (m_allTransitionsHaveBeenMarked)
1991         return;
1992
1993     bool allAreMarkedSoFar = true;
1994         
1995 #if ENABLE(LLINT)
1996     Interpreter* interpreter = m_vm->interpreter;
1997     if (jitType() == JITCode::InterpreterThunk) {
1998         const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
1999         for (size_t i = 0; i < propertyAccessInstructions.size(); ++i) {
2000             Instruction* instruction = &instructions()[propertyAccessInstructions[i]];
2001             switch (interpreter->getOpcodeID(instruction[0].u.opcode)) {
2002             case op_put_by_id_transition_direct:
2003             case op_put_by_id_transition_normal:
2004             case op_put_by_id_transition_direct_out_of_line:
2005             case op_put_by_id_transition_normal_out_of_line: {
2006                 if (Heap::isMarked(instruction[4].u.structure.get()))
2007                     visitor.append(&instruction[6].u.structure);
2008                 else
2009                     allAreMarkedSoFar = false;
2010                 break;
2011             }
2012             default:
2013                 break;
2014             }
2015         }
2016     }
2017 #endif // ENABLE(LLINT)
2018
2019 #if ENABLE(JIT)
2020     if (JITCode::isJIT(jitType())) {
2021         for (unsigned i = 0; i < m_structureStubInfos.size(); ++i) {
2022             StructureStubInfo& stubInfo = m_structureStubInfos[i];
2023             switch (stubInfo.accessType) {
2024             case access_put_by_id_transition_normal:
2025             case access_put_by_id_transition_direct: {
2026                 JSCell* origin = stubInfo.codeOrigin.codeOriginOwner();
2027                 if ((!origin || Heap::isMarked(origin))
2028                     && Heap::isMarked(stubInfo.u.putByIdTransition.previousStructure.get()))
2029                     visitor.append(&stubInfo.u.putByIdTransition.structure);
2030                 else
2031                     allAreMarkedSoFar = false;
2032                 break;
2033             }
2034
2035             case access_put_by_id_list: {
2036                 PolymorphicPutByIdList* list = stubInfo.u.putByIdList.list;
2037                 JSCell* origin = stubInfo.codeOrigin.codeOriginOwner();
2038                 if (origin && !Heap::isMarked(origin)) {
2039                     allAreMarkedSoFar = false;
2040                     break;
2041                 }
2042                 for (unsigned j = list->size(); j--;) {
2043                     PutByIdAccess& access = list->m_list[j];
2044                     if (!access.isTransition())
2045                         continue;
2046                     if (Heap::isMarked(access.oldStructure()))
2047                         visitor.append(&access.m_newStructure);
2048                     else
2049                         allAreMarkedSoFar = false;
2050                 }
2051                 break;
2052             }
2053             
2054             default:
2055                 break;
2056             }
2057         }
2058     }
2059 #endif // ENABLE(JIT)
2060     
2061 #if ENABLE(DFG_JIT)
2062     if (JITCode::isOptimizingJIT(jitType())) {
2063         DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2064         for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
2065             if ((!dfgCommon->transitions[i].m_codeOrigin
2066                  || Heap::isMarked(dfgCommon->transitions[i].m_codeOrigin.get()))
2067                 && Heap::isMarked(dfgCommon->transitions[i].m_from.get())) {
2068                 // If the following three things are live, then the target of the
2069                 // transition is also live:
2070                 // - This code block. We know it's live already because otherwise
2071                 //   we wouldn't be scanning ourselves.
2072                 // - The code origin of the transition. Transitions may arise from
2073                 //   code that was inlined. They are not relevant if the user's
2074                 //   object that is required for the inlinee to run is no longer
2075                 //   live.
2076                 // - The source of the transition. The transition checks if some
2077                 //   heap location holds the source, and if so, stores the target.
2078                 //   Hence the source must be live for the transition to be live.
2079                 visitor.append(&dfgCommon->transitions[i].m_to);
2080             } else
2081                 allAreMarkedSoFar = false;
2082         }
2083     }
2084 #endif // ENABLE(DFG_JIT)
2085     
2086     if (allAreMarkedSoFar)
2087         m_allTransitionsHaveBeenMarked = true;
2088 }
2089
2090 void CodeBlock::determineLiveness(SlotVisitor& visitor)
2091 {
2092     UNUSED_PARAM(visitor);
2093     
2094     if (shouldImmediatelyAssumeLivenessDuringScan())
2095         return;
2096     
2097 #if ENABLE(DFG_JIT)
2098     // Check if we have any remaining work to do.
2099     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2100     if (dfgCommon->livenessHasBeenProved)
2101         return;
2102     
2103     // Now check all of our weak references. If all of them are live, then we
2104     // have proved liveness and so we scan our strong references. If at end of
2105     // GC we still have not proved liveness, then this code block is toast.
2106     bool allAreLiveSoFar = true;
2107     for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
2108         if (!Heap::isMarked(dfgCommon->weakReferences[i].get())) {
2109             allAreLiveSoFar = false;
2110             break;
2111         }
2112     }
2113     
2114     // If some weak references are dead, then this fixpoint iteration was
2115     // unsuccessful.
2116     if (!allAreLiveSoFar)
2117         return;
2118     
2119     // All weak references are live. Record this information so we don't
2120     // come back here again, and scan the strong references.
2121     dfgCommon->livenessHasBeenProved = true;
2122     stronglyVisitStrongReferences(visitor);
2123 #endif // ENABLE(DFG_JIT)
2124 }
2125
2126 void CodeBlock::visitWeakReferences(SlotVisitor& visitor)
2127 {
2128     propagateTransitions(visitor);
2129     determineLiveness(visitor);
2130 }
2131
2132 void CodeBlock::finalizeUnconditionally()
2133 {
2134 #if ENABLE(LLINT)
2135     Interpreter* interpreter = m_vm->interpreter;
2136     if (JITCode::couldBeInterpreted(jitType())) {
2137         const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
2138         for (size_t size = propertyAccessInstructions.size(), i = 0; i < size; ++i) {
2139             Instruction* curInstruction = &instructions()[propertyAccessInstructions[i]];
2140             switch (interpreter->getOpcodeID(curInstruction[0].u.opcode)) {
2141             case op_get_by_id:
2142             case op_get_by_id_out_of_line:
2143             case op_put_by_id:
2144             case op_put_by_id_out_of_line:
2145                 if (!curInstruction[4].u.structure || Heap::isMarked(curInstruction[4].u.structure.get()))
2146                     break;
2147                 if (Options::verboseOSR())
2148                     dataLogF("Clearing LLInt property access with structure %p.\n", curInstruction[4].u.structure.get());
2149                 curInstruction[4].u.structure.clear();
2150                 curInstruction[5].u.operand = 0;
2151                 break;
2152             case op_put_by_id_transition_direct:
2153             case op_put_by_id_transition_normal:
2154             case op_put_by_id_transition_direct_out_of_line:
2155             case op_put_by_id_transition_normal_out_of_line:
2156                 if (Heap::isMarked(curInstruction[4].u.structure.get())
2157                     && Heap::isMarked(curInstruction[6].u.structure.get())
2158                     && Heap::isMarked(curInstruction[7].u.structureChain.get()))
2159                     break;
2160                 if (Options::verboseOSR()) {
2161                     dataLogF("Clearing LLInt put transition with structures %p -> %p, chain %p.\n",
2162                             curInstruction[4].u.structure.get(),
2163                             curInstruction[6].u.structure.get(),
2164                             curInstruction[7].u.structureChain.get());
2165                 }
2166                 curInstruction[4].u.structure.clear();
2167                 curInstruction[6].u.structure.clear();
2168                 curInstruction[7].u.structureChain.clear();
2169                 curInstruction[0].u.opcode = interpreter->getOpcode(op_put_by_id);
2170                 break;
2171             case op_get_array_length:
2172                 break;
2173             case op_get_from_scope:
2174             case op_put_to_scope: {
2175                 WriteBarrierBase<Structure>& structure = curInstruction[5].u.structure;
2176                 if (!structure || Heap::isMarked(structure.get()))
2177                     break;
2178                 if (Options::verboseOSR())
2179                     dataLogF("Clearing LLInt scope access with structure %p.\n", structure.get());
2180                 structure.clear();
2181                 break;
2182             }
2183             default:
2184                 RELEASE_ASSERT_NOT_REACHED();
2185             }
2186         }
2187
2188         for (unsigned i = 0; i < m_llintCallLinkInfos.size(); ++i) {
2189             if (m_llintCallLinkInfos[i].isLinked() && !Heap::isMarked(m_llintCallLinkInfos[i].callee.get())) {
2190                 if (Options::verboseOSR())
2191                     dataLog("Clearing LLInt call from ", *this, "\n");
2192                 m_llintCallLinkInfos[i].unlink();
2193             }
2194             if (!!m_llintCallLinkInfos[i].lastSeenCallee && !Heap::isMarked(m_llintCallLinkInfos[i].lastSeenCallee.get()))
2195                 m_llintCallLinkInfos[i].lastSeenCallee.clear();
2196         }
2197     }
2198 #endif // ENABLE(LLINT)
2199
2200 #if ENABLE(DFG_JIT)
2201     // Check if we're not live. If we are, then jettison.
2202     if (!(shouldImmediatelyAssumeLivenessDuringScan() || m_jitCode->dfgCommon()->livenessHasBeenProved)) {
2203         if (Options::verboseOSR())
2204             dataLog(*this, " has dead weak references, jettisoning during GC.\n");
2205
2206         if (DFG::shouldShowDisassembly()) {
2207             dataLog(*this, " will be jettisoned because of the following dead references:\n");
2208             DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2209             for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
2210                 DFG::WeakReferenceTransition& transition = dfgCommon->transitions[i];
2211                 JSCell* origin = transition.m_codeOrigin.get();
2212                 JSCell* from = transition.m_from.get();
2213                 JSCell* to = transition.m_to.get();
2214                 if ((!origin || Heap::isMarked(origin)) && Heap::isMarked(from))
2215                     continue;
2216                 dataLog("    Transition under ", RawPointer(origin), ", ", RawPointer(from), " -> ", RawPointer(to), ".\n");
2217             }
2218             for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
2219                 JSCell* weak = dfgCommon->weakReferences[i].get();
2220                 if (Heap::isMarked(weak))
2221                     continue;
2222                 dataLog("    Weak reference ", RawPointer(weak), ".\n");
2223             }
2224         }
2225         
2226         jettison();
2227         return;
2228     }
2229 #endif // ENABLE(DFG_JIT)
2230
2231 #if ENABLE(JIT)
2232     // Handle inline caches.
2233     if (!!jitCode()) {
2234         RepatchBuffer repatchBuffer(this);
2235         for (unsigned i = 0; i < numberOfCallLinkInfos(); ++i) {
2236             if (callLinkInfo(i).isLinked()) {
2237                 if (ClosureCallStubRoutine* stub = callLinkInfo(i).stub.get()) {
2238                     if (!Heap::isMarked(stub->structure())
2239                         || !Heap::isMarked(stub->executable())) {
2240                         if (Options::verboseOSR()) {
2241                             dataLog(
2242                                 "Clearing closure call from ", *this, " to ",
2243                                 stub->executable()->hashFor(callLinkInfo(i).specializationKind()),
2244                                 ", stub routine ", RawPointer(stub), ".\n");
2245                         }
2246                         callLinkInfo(i).unlink(*m_vm, repatchBuffer);
2247                     }
2248                 } else if (!Heap::isMarked(callLinkInfo(i).callee.get())) {
2249                     if (Options::verboseOSR()) {
2250                         dataLog(
2251                             "Clearing call from ", *this, " to ",
2252                             RawPointer(callLinkInfo(i).callee.get()), " (",
2253                             callLinkInfo(i).callee.get()->executable()->hashFor(
2254                                 callLinkInfo(i).specializationKind()),
2255                             ").\n");
2256                     }
2257                     callLinkInfo(i).unlink(*m_vm, repatchBuffer);
2258                 }
2259             }
2260             if (!!callLinkInfo(i).lastSeenCallee
2261                 && !Heap::isMarked(callLinkInfo(i).lastSeenCallee.get()))
2262                 callLinkInfo(i).lastSeenCallee.clear();
2263         }
2264         for (size_t size = m_structureStubInfos.size(), i = 0; i < size; ++i) {
2265             StructureStubInfo& stubInfo = m_structureStubInfos[i];
2266             
2267             if (stubInfo.visitWeakReferences())
2268                 continue;
2269             
2270             resetStubDuringGCInternal(repatchBuffer, stubInfo);
2271         }
2272     }
2273 #endif
2274 }
2275
2276 #if ENABLE(JIT)
2277 void CodeBlock::resetStub(StructureStubInfo& stubInfo)
2278 {
2279     if (stubInfo.accessType == access_unset)
2280         return;
2281     
2282     RepatchBuffer repatchBuffer(this);
2283     resetStubInternal(repatchBuffer, stubInfo);
2284 }
2285
2286 void CodeBlock::resetStubInternal(RepatchBuffer& repatchBuffer, StructureStubInfo& stubInfo)
2287 {
2288     AccessType accessType = static_cast<AccessType>(stubInfo.accessType);
2289     
2290     if (Options::verboseOSR()) {
2291         // This can be called from GC destructor calls, so we don't try to do a full dump
2292         // of the CodeBlock.
2293         dataLog("Clearing structure cache (kind ", static_cast<int>(stubInfo.accessType), ") in ", RawPointer(this), ".\n");
2294     }
2295
2296     switch (jitType()) {
2297     case JITCode::BaselineJIT:
2298         if (isGetByIdAccess(accessType))
2299             JIT::resetPatchGetById(repatchBuffer, &stubInfo);
2300         else {
2301             RELEASE_ASSERT(isPutByIdAccess(accessType));
2302             JIT::resetPatchPutById(repatchBuffer, &stubInfo);
2303         }
2304         break;
2305     case JITCode::DFGJIT:
2306         if (isGetByIdAccess(accessType))
2307             DFG::dfgResetGetByID(repatchBuffer, stubInfo);
2308         else if (isPutByIdAccess(accessType))
2309             DFG::dfgResetPutByID(repatchBuffer, stubInfo);
2310         else {
2311             RELEASE_ASSERT(isInAccess(accessType));
2312             DFG::dfgResetIn(repatchBuffer, stubInfo);
2313         }
2314         break;
2315     default:
2316         RELEASE_ASSERT_NOT_REACHED();
2317         break;
2318     }
2319     
2320     stubInfo.reset();
2321 }
2322
2323 void CodeBlock::resetStubDuringGCInternal(RepatchBuffer& repatchBuffer, StructureStubInfo& stubInfo)
2324 {
2325     resetStubInternal(repatchBuffer, stubInfo);
2326     stubInfo.resetByGC = true;
2327 }
2328 #endif
2329
2330 void CodeBlock::stronglyVisitStrongReferences(SlotVisitor& visitor)
2331 {
2332     visitor.append(&m_globalObject);
2333     visitor.append(&m_ownerExecutable);
2334     visitor.append(&m_unlinkedCode);
2335     if (m_rareData)
2336         m_rareData->m_evalCodeCache.visitAggregate(visitor);
2337     visitor.appendValues(m_constantRegisters.data(), m_constantRegisters.size());
2338     for (size_t i = 0; i < m_functionExprs.size(); ++i)
2339         visitor.append(&m_functionExprs[i]);
2340     for (size_t i = 0; i < m_functionDecls.size(); ++i)
2341         visitor.append(&m_functionDecls[i]);
2342     for (unsigned i = 0; i < m_objectAllocationProfiles.size(); ++i)
2343         m_objectAllocationProfiles[i].visitAggregate(visitor);
2344
2345     updateAllPredictions(Collection);
2346 }
2347
2348 void CodeBlock::stronglyVisitWeakReferences(SlotVisitor& visitor)
2349 {
2350     UNUSED_PARAM(visitor);
2351
2352 #if ENABLE(DFG_JIT)
2353     if (!JITCode::isOptimizingJIT(jitType()))
2354         return;
2355     
2356     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2357
2358     for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
2359         if (!!dfgCommon->transitions[i].m_codeOrigin)
2360             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.
2361         visitor.append(&dfgCommon->transitions[i].m_from);
2362         visitor.append(&dfgCommon->transitions[i].m_to);
2363     }
2364     
2365     for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i)
2366         visitor.append(&dfgCommon->weakReferences[i]);
2367 #endif    
2368 }
2369
2370 CodeBlock* CodeBlock::baselineVersion()
2371 {
2372     if (JITCode::isBaselineCode(jitType()))
2373         return this;
2374 #if ENABLE(JIT)
2375     CodeBlock* result = replacement();
2376     while (result->alternative())
2377         result = result->alternative();
2378     RELEASE_ASSERT(result);
2379     RELEASE_ASSERT(JITCode::isBaselineCode(result->jitType()));
2380     return result;
2381 #else
2382     RELEASE_ASSERT_NOT_REACHED();
2383     return 0;
2384 #endif
2385 }
2386
2387 #if ENABLE(JIT)
2388 bool CodeBlock::hasOptimizedReplacement()
2389 {
2390     ASSERT(JITCode::isBaselineCode(jitType()));
2391     bool result = JITCode::isHigherTier(replacement()->jitType(), jitType());
2392     if (result)
2393         ASSERT(JITCode::isOptimizingJIT(replacement()->jitType()));
2394     else {
2395         ASSERT(JITCode::isBaselineCode(replacement()->jitType()));
2396         ASSERT(replacement() == this);
2397     }
2398     return result;
2399 }
2400 #endif
2401
2402 HandlerInfo* CodeBlock::handlerForBytecodeOffset(unsigned bytecodeOffset)
2403 {
2404     RELEASE_ASSERT(bytecodeOffset < instructions().size());
2405
2406     if (!m_rareData)
2407         return 0;
2408     
2409     Vector<HandlerInfo>& exceptionHandlers = m_rareData->m_exceptionHandlers;
2410     for (size_t i = 0; i < exceptionHandlers.size(); ++i) {
2411         // Handlers are ordered innermost first, so the first handler we encounter
2412         // that contains the source address is the correct handler to use.
2413         if (exceptionHandlers[i].start <= bytecodeOffset && exceptionHandlers[i].end > bytecodeOffset)
2414             return &exceptionHandlers[i];
2415     }
2416
2417     return 0;
2418 }
2419
2420 unsigned CodeBlock::lineNumberForBytecodeOffset(unsigned bytecodeOffset)
2421 {
2422     RELEASE_ASSERT(bytecodeOffset < instructions().size());
2423     return m_ownerExecutable->lineNo() + m_unlinkedCode->lineNumberForBytecodeOffset(bytecodeOffset);
2424 }
2425
2426 unsigned CodeBlock::columnNumberForBytecodeOffset(unsigned bytecodeOffset)
2427 {
2428     int divot;
2429     int startOffset;
2430     int endOffset;
2431     unsigned line;
2432     unsigned column;
2433     expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
2434     return column;
2435 }
2436
2437 void CodeBlock::expressionRangeForBytecodeOffset(unsigned bytecodeOffset, int& divot, int& startOffset, int& endOffset, unsigned& line, unsigned& column)
2438 {
2439     m_unlinkedCode->expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
2440     divot += m_sourceOffset;
2441     column += line ? 1 : firstLineColumnOffset();
2442     line += m_ownerExecutable->lineNo();
2443 }
2444
2445 void CodeBlock::shrinkToFit(ShrinkMode shrinkMode)
2446 {
2447 #if ENABLE(JIT)
2448     m_structureStubInfos.shrinkToFit();
2449     m_callLinkInfos.shrinkToFit();
2450 #endif
2451 #if ENABLE(VALUE_PROFILER)
2452     m_rareCaseProfiles.shrinkToFit();
2453     m_specialFastCaseProfiles.shrinkToFit();
2454 #endif
2455     
2456     if (shrinkMode == EarlyShrink) {
2457         m_additionalIdentifiers.shrinkToFit();
2458         m_functionDecls.shrinkToFit();
2459         m_functionExprs.shrinkToFit();
2460         m_constantRegisters.shrinkToFit();
2461         
2462         if (m_rareData) {
2463             m_rareData->m_switchJumpTables.shrinkToFit();
2464             m_rareData->m_stringSwitchJumpTables.shrinkToFit();
2465         }
2466     } // else don't shrink these, because we would have already pointed pointers into these tables.
2467
2468     if (m_rareData) {
2469         m_rareData->m_exceptionHandlers.shrinkToFit();
2470 #if ENABLE(JIT)
2471         m_rareData->m_callReturnIndexVector.shrinkToFit();
2472 #endif
2473 #if ENABLE(DFG_JIT)
2474         m_rareData->m_inlineCallFrames.shrinkToFit();
2475         m_rareData->m_codeOrigins.shrinkToFit();
2476 #endif
2477     }
2478 }
2479
2480 void CodeBlock::createActivation(CallFrame* callFrame)
2481 {
2482     ASSERT(codeType() == FunctionCode);
2483     ASSERT(needsFullScopeChain());
2484     ASSERT(!callFrame->uncheckedR(activationRegister()).jsValue());
2485     JSActivation* activation = JSActivation::create(callFrame->vm(), callFrame, this);
2486     callFrame->uncheckedR(activationRegister()) = JSValue(activation);
2487     callFrame->setScope(activation);
2488 }
2489
2490 unsigned CodeBlock::addOrFindConstant(JSValue v)
2491 {
2492     unsigned result;
2493     if (findConstant(v, result))
2494         return result;
2495     return addConstant(v);
2496 }
2497
2498 bool CodeBlock::findConstant(JSValue v, unsigned& index)
2499 {
2500     unsigned numberOfConstants = numberOfConstantRegisters();
2501     for (unsigned i = 0; i < numberOfConstants; ++i) {
2502         if (getConstant(FirstConstantRegisterIndex + i) == v) {
2503             index = i;
2504             return true;
2505         }
2506     }
2507     index = numberOfConstants;
2508     return false;
2509 }
2510
2511 #if ENABLE(JIT)
2512 void CodeBlock::unlinkCalls()
2513 {
2514     if (!!m_alternative)
2515         m_alternative->unlinkCalls();
2516 #if ENABLE(LLINT)
2517     for (size_t i = 0; i < m_llintCallLinkInfos.size(); ++i) {
2518         if (m_llintCallLinkInfos[i].isLinked())
2519             m_llintCallLinkInfos[i].unlink();
2520     }
2521 #endif
2522     if (!m_callLinkInfos.size())
2523         return;
2524     if (!m_vm->canUseJIT())
2525         return;
2526     RepatchBuffer repatchBuffer(this);
2527     for (size_t i = 0; i < m_callLinkInfos.size(); i++) {
2528         if (!m_callLinkInfos[i].isLinked())
2529             continue;
2530         m_callLinkInfos[i].unlink(*m_vm, repatchBuffer);
2531     }
2532 }
2533
2534 void CodeBlock::linkIncomingCall(ExecState* callerFrame, CallLinkInfo* incoming)
2535 {
2536     noticeIncomingCall(callerFrame);
2537     m_incomingCalls.push(incoming);
2538 }
2539 #endif // ENABLE(JIT)
2540
2541 void CodeBlock::unlinkIncomingCalls()
2542 {
2543 #if ENABLE(LLINT)
2544     while (m_incomingLLIntCalls.begin() != m_incomingLLIntCalls.end())
2545         m_incomingLLIntCalls.begin()->unlink();
2546 #endif // ENABLE(LLINT)
2547 #if ENABLE(JIT)
2548     if (m_incomingCalls.isEmpty())
2549         return;
2550     RepatchBuffer repatchBuffer(this);
2551     while (m_incomingCalls.begin() != m_incomingCalls.end())
2552         m_incomingCalls.begin()->unlink(*m_vm, repatchBuffer);
2553 #endif // ENABLE(JIT)
2554 }
2555
2556 #if ENABLE(LLINT)
2557 void CodeBlock::linkIncomingCall(ExecState* callerFrame, LLIntCallLinkInfo* incoming)
2558 {
2559     noticeIncomingCall(callerFrame);
2560     m_incomingLLIntCalls.push(incoming);
2561 }
2562 #endif // ENABLE(LLINT)
2563
2564 #if ENABLE(JIT)
2565 ClosureCallStubRoutine* CodeBlock::findClosureCallForReturnPC(ReturnAddressPtr returnAddress)
2566 {
2567     for (unsigned i = m_callLinkInfos.size(); i--;) {
2568         CallLinkInfo& info = m_callLinkInfos[i];
2569         if (!info.stub)
2570             continue;
2571         if (!info.stub->code().executableMemory()->contains(returnAddress.value()))
2572             continue;
2573
2574         RELEASE_ASSERT(info.stub->codeOrigin().bytecodeIndex != CodeOrigin::invalidBytecodeIndex);
2575         return info.stub.get();
2576     }
2577     
2578     // The stub routine may have been jettisoned. This is rare, but we have to handle it.
2579     const JITStubRoutineSet& set = m_vm->heap.jitStubRoutines();
2580     for (unsigned i = set.size(); i--;) {
2581         GCAwareJITStubRoutine* genericStub = set.at(i);
2582         if (!genericStub->isClosureCall())
2583             continue;
2584         ClosureCallStubRoutine* stub = static_cast<ClosureCallStubRoutine*>(genericStub);
2585         if (!stub->code().executableMemory()->contains(returnAddress.value()))
2586             continue;
2587         RELEASE_ASSERT(stub->codeOrigin().bytecodeIndex != CodeOrigin::invalidBytecodeIndex);
2588         return stub;
2589     }
2590     
2591     return 0;
2592 }
2593 #endif
2594
2595 unsigned CodeBlock::bytecodeOffset(ExecState* exec, ReturnAddressPtr returnAddress)
2596 {
2597     UNUSED_PARAM(exec);
2598     UNUSED_PARAM(returnAddress);
2599 #if ENABLE(LLINT)
2600 #if !ENABLE(LLINT_C_LOOP)
2601     // When using the JIT, we could have addresses that are not bytecode
2602     // addresses. We check if the return address is in the LLint glue and
2603     // opcode handlers range here to ensure that we are looking at bytecode
2604     // before attempting to convert the return address into a bytecode offset.
2605     //
2606     // In the case of the C Loop LLInt, the JIT is disabled, and the only
2607     // valid return addresses should be bytecode PCs. So, we can and need to
2608     // forego this check because when we do not ENABLE(COMPUTED_GOTO_OPCODES),
2609     // then the bytecode "PC"s are actually the opcodeIDs and are not bounded
2610     // by llint_begin and llint_end.
2611     if (returnAddress.value() >= LLInt::getCodePtr(llint_begin)
2612         && returnAddress.value() <= LLInt::getCodePtr(llint_end))
2613 #endif
2614     {
2615         RELEASE_ASSERT(exec->codeBlock());
2616         RELEASE_ASSERT(exec->codeBlock() == this);
2617         RELEASE_ASSERT(JITCode::isBaselineCode(jitType()));
2618         Instruction* instruction = exec->currentVPC();
2619         RELEASE_ASSERT(instruction);
2620
2621         return bytecodeOffset(instruction);
2622     }
2623 #endif // !ENABLE(LLINT)
2624
2625 #if ENABLE(JIT)
2626     if (!m_rareData)
2627         return 1;
2628     Vector<CallReturnOffsetToBytecodeOffset, 0, UnsafeVectorOverflow>& callIndices = m_rareData->m_callReturnIndexVector;
2629     if (!callIndices.size())
2630         return 1;
2631     
2632     if (jitCode()->contains(returnAddress.value())) {
2633         unsigned callReturnOffset = jitCode()->offsetOf(returnAddress.value());
2634         CallReturnOffsetToBytecodeOffset* result =
2635             binarySearch<CallReturnOffsetToBytecodeOffset, unsigned>(
2636                 callIndices, callIndices.size(), callReturnOffset, getCallReturnOffset);
2637         RELEASE_ASSERT(result->callReturnOffset == callReturnOffset);
2638         RELEASE_ASSERT(result->bytecodeOffset < instructionCount());
2639         return result->bytecodeOffset;
2640     }
2641     ClosureCallStubRoutine* closureInfo = findClosureCallForReturnPC(returnAddress);
2642     CodeOrigin origin = closureInfo->codeOrigin();
2643     while (InlineCallFrame* inlineCallFrame = origin.inlineCallFrame) {
2644         if (inlineCallFrame->baselineCodeBlock() == this)
2645             break;
2646         origin = inlineCallFrame->caller;
2647         RELEASE_ASSERT(origin.bytecodeIndex != CodeOrigin::invalidBytecodeIndex);
2648     }
2649     RELEASE_ASSERT(origin.bytecodeIndex != CodeOrigin::invalidBytecodeIndex);
2650     unsigned bytecodeIndex = origin.bytecodeIndex;
2651     RELEASE_ASSERT(bytecodeIndex < instructionCount());
2652     return bytecodeIndex;
2653 #endif // ENABLE(JIT)
2654
2655 #if !ENABLE(LLINT) && !ENABLE(JIT)
2656     return 1;
2657 #endif
2658 }
2659
2660 void CodeBlock::clearEvalCache()
2661 {
2662     if (!!m_alternative)
2663         m_alternative->clearEvalCache();
2664     if (!m_rareData)
2665         return;
2666     m_rareData->m_evalCodeCache.clear();
2667 }
2668
2669 template<typename T, size_t inlineCapacity, typename U, typename V>
2670 inline void replaceExistingEntries(Vector<T, inlineCapacity, U>& target, Vector<T, inlineCapacity, V>& source)
2671 {
2672     ASSERT(target.size() <= source.size());
2673     for (size_t i = 0; i < target.size(); ++i)
2674         target[i] = source[i];
2675 }
2676
2677 void CodeBlock::copyPostParseDataFrom(CodeBlock* alternative)
2678 {
2679     if (!alternative)
2680         return;
2681     
2682     replaceExistingEntries(m_constantRegisters, alternative->m_constantRegisters);
2683     replaceExistingEntries(m_functionDecls, alternative->m_functionDecls);
2684     replaceExistingEntries(m_functionExprs, alternative->m_functionExprs);
2685     if (!!m_rareData && !!alternative->m_rareData)
2686         replaceExistingEntries(m_rareData->m_constantBuffers, alternative->m_rareData->m_constantBuffers);
2687 }
2688
2689 void CodeBlock::copyPostParseDataFromAlternative()
2690 {
2691     copyPostParseDataFrom(m_alternative.get());
2692 }
2693
2694 void CodeBlock::install()
2695 {
2696     ownerExecutable()->installCode(this);
2697 }
2698
2699 PassRefPtr<CodeBlock> CodeBlock::newReplacement()
2700 {
2701     return ownerExecutable()->newReplacementCodeBlockFor(specializationKind());
2702 }
2703
2704 #if ENABLE(JIT)
2705 void CodeBlock::reoptimize()
2706 {
2707     ASSERT(replacement() != this);
2708     ASSERT(replacement()->alternative() == this);
2709     if (DFG::shouldShowDisassembly())
2710         dataLog(*replacement(), " will be jettisoned due to reoptimization of ", *this, ".\n");
2711     replacement()->jettison();
2712     countReoptimization();
2713 }
2714
2715 CodeBlock* ProgramCodeBlock::replacement()
2716 {
2717     return jsCast<ProgramExecutable*>(ownerExecutable())->codeBlock();
2718 }
2719
2720 CodeBlock* EvalCodeBlock::replacement()
2721 {
2722     return jsCast<EvalExecutable*>(ownerExecutable())->codeBlock();
2723 }
2724
2725 CodeBlock* FunctionCodeBlock::replacement()
2726 {
2727     return jsCast<FunctionExecutable*>(ownerExecutable())->codeBlockFor(m_isConstructor ? CodeForConstruct : CodeForCall);
2728 }
2729
2730 DFG::CapabilityLevel ProgramCodeBlock::capabilityLevelInternal()
2731 {
2732     return DFG::programCapabilityLevel(this);
2733 }
2734
2735 DFG::CapabilityLevel EvalCodeBlock::capabilityLevelInternal()
2736 {
2737     return DFG::evalCapabilityLevel(this);
2738 }
2739
2740 DFG::CapabilityLevel FunctionCodeBlock::capabilityLevelInternal()
2741 {
2742     if (m_isConstructor)
2743         return DFG::functionForConstructCapabilityLevel(this);
2744     return DFG::functionForCallCapabilityLevel(this);
2745 }
2746
2747 void CodeBlock::jettison()
2748 {
2749     DeferGC deferGC(*m_heap);
2750     ASSERT(JITCode::isOptimizingJIT(jitType()));
2751     ASSERT(this == replacement());
2752     alternative()->optimizeAfterWarmUp();
2753     tallyFrequentExitSites();
2754     if (DFG::shouldShowDisassembly())
2755         dataLog("Jettisoning ", *this, ".\n");
2756     alternative()->install();
2757 }
2758 #endif
2759
2760 JSGlobalObject* CodeBlock::globalObjectFor(CodeOrigin codeOrigin)
2761 {
2762     if (!codeOrigin.inlineCallFrame)
2763         return globalObject();
2764     return jsCast<FunctionExecutable*>(codeOrigin.inlineCallFrame->executable.get())->eitherCodeBlock()->globalObject();
2765 }
2766
2767 void CodeBlock::noticeIncomingCall(ExecState* callerFrame)
2768 {
2769     CodeBlock* callerCodeBlock = callerFrame->codeBlock();
2770     
2771     if (Options::verboseCallLink())
2772         dataLog("Noticing call link from ", *callerCodeBlock, " to ", *this, "\n");
2773     
2774     if (!m_shouldAlwaysBeInlined)
2775         return;
2776
2777 #if ENABLE(DFG_JIT)
2778     if (!hasBaselineJITProfiling())
2779         return;
2780
2781     if (!DFG::mightInlineFunction(this))
2782         return;
2783
2784     if (!canInline(m_capabilityLevelState))
2785         return;
2786
2787     if (callerCodeBlock->jitType() == JITCode::InterpreterThunk) {
2788         // If the caller is still in the interpreter, then we can't expect inlining to
2789         // happen anytime soon. Assume it's profitable to optimize it separately. This
2790         // ensures that a function is SABI only if it is called no more frequently than
2791         // any of its callers.
2792         m_shouldAlwaysBeInlined = false;
2793         if (Options::verboseCallLink())
2794             dataLog("    Marking SABI because caller is in LLInt.\n");
2795         return;
2796     }
2797     
2798     if (callerCodeBlock->codeType() != FunctionCode) {
2799         // If the caller is either eval or global code, assume that that won't be
2800         // optimized anytime soon. For eval code this is particularly true since we
2801         // delay eval optimization by a *lot*.
2802         m_shouldAlwaysBeInlined = false;
2803         if (Options::verboseCallLink())
2804             dataLog("    Marking SABI because caller is not a function.\n");
2805         return;
2806     }
2807     
2808     ExecState* frame = callerFrame;
2809     for (unsigned i = Options::maximumInliningDepth(); i--; frame = frame->callerFrame()) {
2810         if (frame->hasHostCallFrameFlag())
2811             break;
2812         if (frame->codeBlock() == this) {
2813             // Recursive calls won't be inlined.
2814             if (Options::verboseCallLink())
2815                 dataLog("    Marking SABI because recursion was detected.\n");
2816             m_shouldAlwaysBeInlined = false;
2817             return;
2818         }
2819     }
2820     
2821     RELEASE_ASSERT(callerCodeBlock->m_capabilityLevelState != DFG::CapabilityLevelNotSet);
2822     
2823     if (canCompile(callerCodeBlock->m_capabilityLevelState))
2824         return;
2825     
2826     if (Options::verboseCallLink())
2827         dataLog("    Marking SABI because the caller is not a DFG candidate.\n");
2828     
2829     m_shouldAlwaysBeInlined = false;
2830 #endif
2831 }
2832
2833 #if ENABLE(JIT)
2834 unsigned CodeBlock::reoptimizationRetryCounter() const
2835 {
2836     ASSERT(m_reoptimizationRetryCounter <= Options::reoptimizationRetryCounterMax());
2837     return m_reoptimizationRetryCounter;
2838 }
2839
2840 void CodeBlock::countReoptimization()
2841 {
2842     m_reoptimizationRetryCounter++;
2843     if (m_reoptimizationRetryCounter > Options::reoptimizationRetryCounterMax())
2844         m_reoptimizationRetryCounter = Options::reoptimizationRetryCounterMax();
2845 }
2846
2847 unsigned CodeBlock::numberOfDFGCompiles()
2848 {
2849     ASSERT(JITCode::isBaselineCode(jitType()));
2850     return (JITCode::isOptimizingJIT(replacement()->jitType()) ? 1 : 0) + m_reoptimizationRetryCounter;
2851 }
2852
2853 int32_t CodeBlock::codeTypeThresholdMultiplier() const
2854 {
2855     if (codeType() == EvalCode)
2856         return Options::evalThresholdMultiplier();
2857     
2858     return 1;
2859 }
2860
2861 double CodeBlock::optimizationThresholdScalingFactor()
2862 {
2863     // This expression arises from doing a least-squares fit of
2864     //
2865     // F[x_] =: a * Sqrt[x + b] + Abs[c * x] + d
2866     //
2867     // against the data points:
2868     //
2869     //    x       F[x_]
2870     //    10       0.9          (smallest reasonable code block)
2871     //   200       1.0          (typical small-ish code block)
2872     //   320       1.2          (something I saw in 3d-cube that I wanted to optimize)
2873     //  1268       5.0          (something I saw in 3d-cube that I didn't want to optimize)
2874     //  4000       5.5          (random large size, used to cause the function to converge to a shallow curve of some sort)
2875     // 10000       6.0          (similar to above)
2876     //
2877     // I achieve the minimization using the following Mathematica code:
2878     //
2879     // MyFunctionTemplate[x_, a_, b_, c_, d_] := a*Sqrt[x + b] + Abs[c*x] + d
2880     //
2881     // samples = {{10, 0.9}, {200, 1}, {320, 1.2}, {1268, 5}, {4000, 5.5}, {10000, 6}}
2882     //
2883     // solution = 
2884     //     Minimize[Plus @@ ((MyFunctionTemplate[#[[1]], a, b, c, d] - #[[2]])^2 & /@ samples),
2885     //         {a, b, c, d}][[2]]
2886     //
2887     // And the code below (to initialize a, b, c, d) is generated by:
2888     //
2889     // Print["const double " <> ToString[#[[1]]] <> " = " <>
2890     //     If[#[[2]] < 0.00001, "0.0", ToString[#[[2]]]] <> ";"] & /@ solution
2891     //
2892     // We've long known the following to be true:
2893     // - Small code blocks are cheap to optimize and so we should do it sooner rather
2894     //   than later.
2895     // - Large code blocks are expensive to optimize and so we should postpone doing so,
2896     //   and sometimes have a large enough threshold that we never optimize them.
2897     // - The difference in cost is not totally linear because (a) just invoking the
2898     //   DFG incurs some base cost and (b) for large code blocks there is enough slop
2899     //   in the correlation between instruction count and the actual compilation cost
2900     //   that for those large blocks, the instruction count should not have a strong
2901     //   influence on our threshold.
2902     //
2903     // I knew the goals but I didn't know how to achieve them; so I picked an interesting
2904     // example where the heuristics were right (code block in 3d-cube with instruction
2905     // count 320, which got compiled early as it should have been) and one where they were
2906     // totally wrong (code block in 3d-cube with instruction count 1268, which was expensive
2907     // to compile and didn't run often enough to warrant compilation in my opinion), and
2908     // then threw in additional data points that represented my own guess of what our
2909     // heuristics should do for some round-numbered examples.
2910     //
2911     // The expression to which I decided to fit the data arose because I started with an
2912     // affine function, and then did two things: put the linear part in an Abs to ensure
2913     // that the fit didn't end up choosing a negative value of c (which would result in
2914     // the function turning over and going negative for large x) and I threw in a Sqrt
2915     // term because Sqrt represents my intution that the function should be more sensitive
2916     // to small changes in small values of x, but less sensitive when x gets large.
2917     
2918     // Note that the current fit essentially eliminates the linear portion of the
2919     // expression (c == 0.0).
2920     const double a = 0.061504;
2921     const double b = 1.02406;
2922     const double c = 0.0;
2923     const double d = 0.825914;
2924     
2925     double instructionCount = this->instructionCount();
2926     
2927     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.
2928     
2929     double result = d + a * sqrt(instructionCount + b) + c * instructionCount;
2930     if (Options::verboseOSR()) {
2931         dataLog(
2932             *this, ": instruction count is ", instructionCount,
2933             ", scaling execution counter by ", result, " * ", codeTypeThresholdMultiplier(),
2934             "\n");
2935     }
2936     return result * codeTypeThresholdMultiplier();
2937 }
2938
2939 static int32_t clipThreshold(double threshold)
2940 {
2941     if (threshold < 1.0)
2942         return 1;
2943     
2944     if (threshold > static_cast<double>(std::numeric_limits<int32_t>::max()))
2945         return std::numeric_limits<int32_t>::max();
2946     
2947     return static_cast<int32_t>(threshold);
2948 }
2949
2950 int32_t CodeBlock::adjustedCounterValue(int32_t desiredThreshold)
2951 {
2952     return clipThreshold(
2953         static_cast<double>(desiredThreshold) *
2954         optimizationThresholdScalingFactor() *
2955         (1 << reoptimizationRetryCounter()));
2956 }
2957
2958 bool CodeBlock::checkIfOptimizationThresholdReached()
2959 {
2960 #if ENABLE(DFG_JIT)
2961     if (DFG::Worklist* worklist = m_vm->worklist.get()) {
2962         if (worklist->compilationState(DFG::CompilationKey(this, DFG::DFGMode))
2963             == DFG::Worklist::Compiled) {
2964             optimizeNextInvocation();
2965             return true;
2966         }
2967     }
2968 #endif
2969     
2970     return m_jitExecuteCounter.checkIfThresholdCrossedAndSet(this);
2971 }
2972
2973 void CodeBlock::optimizeNextInvocation()
2974 {
2975     if (Options::verboseOSR())
2976         dataLog(*this, ": Optimizing next invocation.\n");
2977     m_jitExecuteCounter.setNewThreshold(0, this);
2978 }
2979
2980 void CodeBlock::dontOptimizeAnytimeSoon()
2981 {
2982     if (Options::verboseOSR())
2983         dataLog(*this, ": Not optimizing anytime soon.\n");
2984     m_jitExecuteCounter.deferIndefinitely();
2985 }
2986
2987 void CodeBlock::optimizeAfterWarmUp()
2988 {
2989     if (Options::verboseOSR())
2990         dataLog(*this, ": Optimizing after warm-up.\n");
2991 #if ENABLE(DFG_JIT)
2992     m_jitExecuteCounter.setNewThreshold(
2993         adjustedCounterValue(Options::thresholdForOptimizeAfterWarmUp()), this);
2994 #endif
2995 }
2996
2997 void CodeBlock::optimizeAfterLongWarmUp()
2998 {
2999     if (Options::verboseOSR())
3000         dataLog(*this, ": Optimizing after long warm-up.\n");
3001 #if ENABLE(DFG_JIT)
3002     m_jitExecuteCounter.setNewThreshold(
3003         adjustedCounterValue(Options::thresholdForOptimizeAfterLongWarmUp()), this);
3004 #endif
3005 }
3006
3007 void CodeBlock::optimizeSoon()
3008 {
3009     if (Options::verboseOSR())
3010         dataLog(*this, ": Optimizing soon.\n");
3011 #if ENABLE(DFG_JIT)
3012     m_jitExecuteCounter.setNewThreshold(
3013         adjustedCounterValue(Options::thresholdForOptimizeSoon()), this);
3014 #endif
3015 }
3016
3017 void CodeBlock::forceOptimizationSlowPathConcurrently()
3018 {
3019     if (Options::verboseOSR())
3020         dataLog(*this, ": Forcing slow path concurrently.\n");
3021     m_jitExecuteCounter.forceSlowPathConcurrently();
3022 }
3023
3024 #if ENABLE(DFG_JIT)
3025 void CodeBlock::setOptimizationThresholdBasedOnCompilationResult(CompilationResult result)
3026 {
3027     RELEASE_ASSERT(jitType() == JITCode::BaselineJIT);
3028     RELEASE_ASSERT((result == CompilationSuccessful) == (replacement() != this));
3029     switch (result) {
3030     case CompilationSuccessful:
3031         RELEASE_ASSERT(JITCode::isOptimizingJIT(replacement()->jitType()));
3032         optimizeNextInvocation();
3033         break;
3034     case CompilationFailed:
3035         dontOptimizeAnytimeSoon();
3036         break;
3037     case CompilationDeferred:
3038         // We'd like to do dontOptimizeAnytimeSoon() but we cannot because
3039         // forceOptimizationSlowPathConcurrently() is inherently racy. It won't
3040         // necessarily guarantee anything. So, we make sure that even if that
3041         // function ends up being a no-op, we still eventually retry and realize
3042         // that we have optimized code ready.
3043         optimizeAfterWarmUp();
3044         break;
3045     case CompilationInvalidated:
3046         // Retry with exponential backoff.
3047         countReoptimization();
3048         optimizeAfterWarmUp();
3049         break;
3050     default:
3051         RELEASE_ASSERT_NOT_REACHED();
3052         break;
3053     }
3054 }
3055
3056 #endif
3057     
3058 static bool structureStubInfoLessThan(const StructureStubInfo& a, const StructureStubInfo& b)
3059 {
3060     return a.callReturnLocation.executableAddress() < b.callReturnLocation.executableAddress();
3061 }
3062
3063 void CodeBlock::sortStructureStubInfos()
3064 {
3065     std::sort(m_structureStubInfos.begin(), m_structureStubInfos.end(), structureStubInfoLessThan);
3066 }
3067
3068 uint32_t CodeBlock::adjustedExitCountThreshold(uint32_t desiredThreshold)
3069 {
3070     ASSERT(JITCode::isOptimizingJIT(jitType()));
3071     // Compute this the lame way so we don't saturate. This is called infrequently
3072     // enough that this loop won't hurt us.
3073     unsigned result = desiredThreshold;
3074     for (unsigned n = baselineVersion()->reoptimizationRetryCounter(); n--;) {
3075         unsigned newResult = result << 1;
3076         if (newResult < result)
3077             return std::numeric_limits<uint32_t>::max();
3078         result = newResult;
3079     }
3080     return result;
3081 }
3082
3083 uint32_t CodeBlock::exitCountThresholdForReoptimization()
3084 {
3085     return adjustedExitCountThreshold(Options::osrExitCountForReoptimization() * codeTypeThresholdMultiplier());
3086 }
3087
3088 uint32_t CodeBlock::exitCountThresholdForReoptimizationFromLoop()
3089 {
3090     return adjustedExitCountThreshold(Options::osrExitCountForReoptimizationFromLoop() * codeTypeThresholdMultiplier());
3091 }
3092
3093 bool CodeBlock::shouldReoptimizeNow()
3094 {
3095     return osrExitCounter() >= exitCountThresholdForReoptimization();
3096 }
3097
3098 bool CodeBlock::shouldReoptimizeFromLoopNow()
3099 {
3100     return osrExitCounter() >= exitCountThresholdForReoptimizationFromLoop();
3101 }
3102 #endif
3103
3104 #if ENABLE(VALUE_PROFILER)
3105 ArrayProfile* CodeBlock::getArrayProfile(unsigned bytecodeOffset)
3106 {
3107     for (unsigned i = 0; i < m_arrayProfiles.size(); ++i) {
3108         if (m_arrayProfiles[i].bytecodeOffset() == bytecodeOffset)
3109             return &m_arrayProfiles[i];
3110     }
3111     return 0;
3112 }
3113
3114 ArrayProfile* CodeBlock::getOrAddArrayProfile(unsigned bytecodeOffset)
3115 {
3116     ArrayProfile* result = getArrayProfile(bytecodeOffset);
3117     if (result)
3118         return result;
3119     return addArrayProfile(bytecodeOffset);
3120 }
3121
3122 void CodeBlock::updateAllPredictionsAndCountLiveness(
3123     OperationInProgress operation, unsigned& numberOfLiveNonArgumentValueProfiles, unsigned& numberOfSamplesInProfiles)
3124 {
3125     ConcurrentJITLocker locker(m_lock);
3126     
3127     numberOfLiveNonArgumentValueProfiles = 0;
3128     numberOfSamplesInProfiles = 0; // If this divided by ValueProfile::numberOfBuckets equals numberOfValueProfiles() then value profiles are full.
3129     for (unsigned i = 0; i < totalNumberOfValueProfiles(); ++i) {
3130         ValueProfile* profile = getFromAllValueProfiles(i);
3131         unsigned numSamples = profile->totalNumberOfSamples();
3132         if (numSamples > ValueProfile::numberOfBuckets)
3133             numSamples = ValueProfile::numberOfBuckets; // We don't want profiles that are extremely hot to be given more weight.
3134         numberOfSamplesInProfiles += numSamples;
3135         if (profile->m_bytecodeOffset < 0) {
3136             profile->computeUpdatedPrediction(locker, operation);
3137             continue;
3138         }
3139         if (profile->numberOfSamples() || profile->m_prediction != SpecNone)
3140             numberOfLiveNonArgumentValueProfiles++;
3141         profile->computeUpdatedPrediction(locker, operation);
3142     }
3143     
3144 #if ENABLE(DFG_JIT)
3145     m_lazyOperandValueProfiles.computeUpdatedPredictions(locker, operation);
3146 #endif
3147 }
3148
3149 void CodeBlock::updateAllValueProfilePredictions(OperationInProgress operation)
3150 {
3151     unsigned ignoredValue1, ignoredValue2;
3152     updateAllPredictionsAndCountLiveness(operation, ignoredValue1, ignoredValue2);
3153 }
3154
3155 void CodeBlock::updateAllArrayPredictions()
3156 {
3157     ConcurrentJITLocker locker(m_lock);
3158     
3159     for (unsigned i = m_arrayProfiles.size(); i--;)
3160         m_arrayProfiles[i].computeUpdatedPrediction(locker, this);
3161     
3162     // Don't count these either, for similar reasons.
3163     for (unsigned i = m_arrayAllocationProfiles.size(); i--;)
3164         m_arrayAllocationProfiles[i].updateIndexingType();
3165 }
3166
3167 void CodeBlock::updateAllPredictions(OperationInProgress operation)
3168 {
3169     updateAllValueProfilePredictions(operation);
3170     updateAllArrayPredictions();
3171 }
3172
3173 bool CodeBlock::shouldOptimizeNow()
3174 {
3175     if (Options::verboseOSR())
3176         dataLog("Considering optimizing ", *this, "...\n");
3177
3178 #if ENABLE(VERBOSE_VALUE_PROFILE)
3179     dumpValueProfiles();
3180 #endif
3181
3182     if (m_optimizationDelayCounter >= Options::maximumOptimizationDelay())
3183         return true;
3184     
3185     updateAllArrayPredictions();
3186     
3187     unsigned numberOfLiveNonArgumentValueProfiles;
3188     unsigned numberOfSamplesInProfiles;
3189     updateAllPredictionsAndCountLiveness(NoOperation, numberOfLiveNonArgumentValueProfiles, numberOfSamplesInProfiles);
3190
3191     if (Options::verboseOSR()) {
3192         dataLogF(
3193             "Profile hotness: %lf (%u / %u), %lf (%u / %u)\n",
3194             (double)numberOfLiveNonArgumentValueProfiles / numberOfValueProfiles(),
3195             numberOfLiveNonArgumentValueProfiles, numberOfValueProfiles(),
3196             (double)numberOfSamplesInProfiles / ValueProfile::numberOfBuckets / numberOfValueProfiles(),
3197             numberOfSamplesInProfiles, ValueProfile::numberOfBuckets * numberOfValueProfiles());
3198     }
3199
3200     if ((!numberOfValueProfiles() || (double)numberOfLiveNonArgumentValueProfiles / numberOfValueProfiles() >= Options::desiredProfileLivenessRate())
3201         && (!totalNumberOfValueProfiles() || (double)numberOfSamplesInProfiles / ValueProfile::numberOfBuckets / totalNumberOfValueProfiles() >= Options::desiredProfileFullnessRate())
3202         && static_cast<unsigned>(m_optimizationDelayCounter) + 1 >= Options::minimumOptimizationDelay())
3203         return true;
3204     
3205     ASSERT(m_optimizationDelayCounter < std::numeric_limits<uint8_t>::max());
3206     m_optimizationDelayCounter++;
3207     optimizeAfterWarmUp();
3208     return false;
3209 }
3210 #endif
3211
3212 #if ENABLE(DFG_JIT)
3213 void CodeBlock::tallyFrequentExitSites()
3214 {
3215     ASSERT(JITCode::isOptimizingJIT(jitType()));
3216     ASSERT(alternative()->jitType() == JITCode::BaselineJIT);
3217     
3218     CodeBlock* profiledBlock = alternative();
3219     
3220     switch (jitType()) {
3221     case JITCode::DFGJIT: {
3222         DFG::JITCode* jitCode = m_jitCode->dfg();
3223         for (unsigned i = 0; i < jitCode->osrExit.size(); ++i) {
3224             DFG::OSRExit& exit = jitCode->osrExit[i];
3225             
3226             if (!exit.considerAddingAsFrequentExitSite(profiledBlock))
3227                 continue;
3228             
3229 #if DFG_ENABLE(DEBUG_VERBOSE)
3230             dataLog("OSR exit #", i, " (bc#", exit.m_codeOrigin.bytecodeIndex, ", ", exit.m_kind, ") for ", *this, " occurred frequently: counting as frequent exit site.\n");
3231 #endif
3232         }
3233         break;
3234     }
3235
3236 #if ENABLE(FTL_JIT)
3237     case JITCode::FTLJIT: {
3238         // There is no easy way to avoid duplicating this code since the FTL::JITCode::osrExit
3239         // vector contains a totally different type, that just so happens to behave like
3240         // DFG::JITCode::osrExit.
3241         FTL::JITCode* jitCode = m_jitCode->ftl();
3242         for (unsigned i = 0; i < jitCode->osrExit.size(); ++i) {
3243             FTL::OSRExit& exit = jitCode->osrExit[i];
3244             
3245             if (!exit.considerAddingAsFrequentExitSite(profiledBlock))
3246                 continue;
3247             
3248 #if DFG_ENABLE(DEBUG_VERBOSE)
3249             dataLog("OSR exit #", i, " (bc#", exit.m_codeOrigin.bytecodeIndex, ", ", exit.m_kind, ") for ", *this, " occurred frequently: counting as frequent exit site.\n");
3250 #endif
3251         }
3252         break;
3253     }
3254 #endif
3255         
3256     default:
3257         RELEASE_ASSERT_NOT_REACHED();
3258         break;
3259     }
3260 }
3261 #endif // ENABLE(DFG_JIT)
3262
3263 #if ENABLE(VERBOSE_VALUE_PROFILE)
3264 void CodeBlock::dumpValueProfiles()
3265 {
3266     dataLog("ValueProfile for ", *this, ":\n");
3267     for (unsigned i = 0; i < totalNumberOfValueProfiles(); ++i) {
3268         ValueProfile* profile = getFromAllValueProfiles(i);
3269         if (profile->m_bytecodeOffset < 0) {
3270             ASSERT(profile->m_bytecodeOffset == -1);
3271             dataLogF("   arg = %u: ", i);
3272         } else
3273             dataLogF("   bc = %d: ", profile->m_bytecodeOffset);
3274         if (!profile->numberOfSamples() && profile->m_prediction == SpecNone) {
3275             dataLogF("<empty>\n");
3276             continue;
3277         }
3278         profile->dump(WTF::dataFile());
3279         dataLogF("\n");
3280     }
3281     dataLog("RareCaseProfile for ", *this, ":\n");
3282     for (unsigned i = 0; i < numberOfRareCaseProfiles(); ++i) {
3283         RareCaseProfile* profile = rareCaseProfile(i);
3284         dataLogF("   bc = %d: %u\n", profile->m_bytecodeOffset, profile->m_counter);
3285     }
3286     dataLog("SpecialFastCaseProfile for ", *this, ":\n");
3287     for (unsigned i = 0; i < numberOfSpecialFastCaseProfiles(); ++i) {
3288         RareCaseProfile* profile = specialFastCaseProfile(i);
3289         dataLogF("   bc = %d: %u\n", profile->m_bytecodeOffset, profile->m_counter);
3290     }
3291 }
3292 #endif // ENABLE(VERBOSE_VALUE_PROFILE)
3293
3294 size_t CodeBlock::predictedMachineCodeSize()
3295 {
3296     // This will be called from CodeBlock::CodeBlock before either m_vm or the
3297     // instructions have been initialized. It's OK to return 0 because what will really
3298     // matter is the recomputation of this value when the slow path is triggered.
3299     if (!m_vm)
3300         return 0;
3301     
3302     if (!m_vm->machineCodeBytesPerBytecodeWordForBaselineJIT)
3303         return 0; // It's as good of a prediction as we'll get.
3304     
3305     // Be conservative: return a size that will be an overestimation 84% of the time.
3306     double multiplier = m_vm->machineCodeBytesPerBytecodeWordForBaselineJIT.mean() +
3307         m_vm->machineCodeBytesPerBytecodeWordForBaselineJIT.standardDeviation();
3308     
3309     // Be paranoid: silently reject bogus multipiers. Silently doing the "wrong" thing
3310     // here is OK, since this whole method is just a heuristic.
3311     if (multiplier < 0 || multiplier > 1000)
3312         return 0;
3313     
3314     double doubleResult = multiplier * m_instructions.size();
3315     
3316     // Be even more paranoid: silently reject values that won't fit into a size_t. If
3317     // the function is so huge that we can't even fit it into virtual memory then we
3318     // should probably have some other guards in place to prevent us from even getting
3319     // to this point.
3320     if (doubleResult > std::numeric_limits<size_t>::max())
3321         return 0;
3322     
3323     return static_cast<size_t>(doubleResult);
3324 }
3325
3326 bool CodeBlock::usesOpcode(OpcodeID opcodeID)
3327 {
3328     Interpreter* interpreter = vm()->interpreter;
3329     Instruction* instructionsBegin = instructions().begin();
3330     unsigned instructionCount = instructions().size();
3331     
3332     for (unsigned bytecodeOffset = 0; bytecodeOffset < instructionCount; ) {
3333         switch (interpreter->getOpcodeID(instructionsBegin[bytecodeOffset].u.opcode)) {
3334 #define DEFINE_OP(curOpcode, length)        \
3335         case curOpcode:                     \
3336             if (curOpcode == opcodeID)      \
3337                 return true;                \
3338             bytecodeOffset += length;       \
3339             break;
3340             FOR_EACH_OPCODE_ID(DEFINE_OP)
3341 #undef DEFINE_OP
3342         default:
3343             RELEASE_ASSERT_NOT_REACHED();
3344             break;
3345         }
3346     }
3347     
3348     return false;
3349 }
3350
3351 String CodeBlock::nameForRegister(int registerNumber)
3352 {
3353     ConcurrentJITLocker locker(symbolTable()->m_lock);
3354     SymbolTable::Map::iterator end = symbolTable()->end(locker);
3355     for (SymbolTable::Map::iterator ptr = symbolTable()->begin(locker); ptr != end; ++ptr) {
3356         if (ptr->value.getIndex() == registerNumber) {
3357             // FIXME: This won't work from the compilation thread.
3358             // https://bugs.webkit.org/show_bug.cgi?id=115300
3359             return String(ptr->key);
3360         }
3361     }
3362     if (needsActivation() && registerNumber == activationRegister())
3363         return ASCIILiteral("activation");
3364     if (registerNumber == thisRegister())
3365         return ASCIILiteral("this");
3366     if (usesArguments()) {
3367         if (registerNumber == argumentsRegister())
3368             return ASCIILiteral("arguments");
3369         if (unmodifiedArgumentsRegister(argumentsRegister()) == registerNumber)
3370             return ASCIILiteral("real arguments");
3371     }
3372     if (registerNumber < 0) {
3373         int argumentPosition = -registerNumber;
3374         argumentPosition -= JSStack::CallFrameHeaderSize + 1;
3375         return String::format("arguments[%3d]", argumentPosition - 1).impl();
3376     }
3377     return "";
3378 }
3379
3380 } // namespace JSC