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