DFG should be able to set watchpoints on global variables
[WebKit-https.git] / Source / JavaScriptCore / bytecode / CodeBlock.cpp
1 /*
2  * Copyright (C) 2008, 2009, 2010 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 "DFGCapabilities.h"
35 #include "DFGNode.h"
36 #include "DFGRepatch.h"
37 #include "Debugger.h"
38 #include "Interpreter.h"
39 #include "JIT.h"
40 #include "JITStubs.h"
41 #include "JSActivation.h"
42 #include "JSFunction.h"
43 #include "JSStaticScopeObject.h"
44 #include "JSValue.h"
45 #include "LowLevelInterpreter.h"
46 #include "MethodCallLinkStatus.h"
47 #include "RepatchBuffer.h"
48 #include "UStringConcatenate.h"
49 #include <stdio.h>
50 #include <wtf/StringExtras.h>
51
52 #if ENABLE(DFG_JIT)
53 #include "DFGOperations.h"
54 #endif
55
56 #define DUMP_CODE_BLOCK_STATISTICS 0
57
58 namespace JSC {
59
60 #if ENABLE(DFG_JIT)
61 using namespace DFG;
62 #endif
63
64 static UString escapeQuotes(const UString& str)
65 {
66     UString result = str;
67     size_t pos = 0;
68     while ((pos = result.find('\"', pos)) != notFound) {
69         result = makeUString(result.substringSharingImpl(0, pos), "\"\\\"\"", result.substringSharingImpl(pos + 1));
70         pos += 4;
71     }
72     return result;
73 }
74
75 static UString valueToSourceString(ExecState* exec, JSValue val)
76 {
77     if (!val)
78         return "0";
79
80     if (val.isString())
81         return makeUString("\"", escapeQuotes(val.toString(exec)->value(exec)), "\"");
82
83     return val.description();
84 }
85
86 static CString constantName(ExecState* exec, int k, JSValue value)
87 {
88     return makeUString(valueToSourceString(exec, value), "(@k", UString::number(k - FirstConstantRegisterIndex), ")").utf8();
89 }
90
91 static CString idName(int id0, const Identifier& ident)
92 {
93     return makeUString(ident.ustring(), "(@id", UString::number(id0), ")").utf8();
94 }
95
96 CString CodeBlock::registerName(ExecState* exec, int r) const
97 {
98     if (r == missingThisObjectMarker())
99         return "<null>";
100
101     if (isConstantRegisterIndex(r))
102         return constantName(exec, r, getConstant(r));
103
104     return makeUString("r", UString::number(r)).utf8();
105 }
106
107 static UString regexpToSourceString(RegExp* regExp)
108 {
109     char postfix[5] = { '/', 0, 0, 0, 0 };
110     int index = 1;
111     if (regExp->global())
112         postfix[index++] = 'g';
113     if (regExp->ignoreCase())
114         postfix[index++] = 'i';
115     if (regExp->multiline())
116         postfix[index] = 'm';
117
118     return makeUString("/", regExp->pattern(), postfix);
119 }
120
121 static CString regexpName(int re, RegExp* regexp)
122 {
123     return makeUString(regexpToSourceString(regexp), "(@re", UString::number(re), ")").utf8();
124 }
125
126 static UString pointerToSourceString(void* p)
127 {
128     char buffer[2 + 2 * sizeof(void*) + 1]; // 0x [two characters per byte] \0
129     snprintf(buffer, sizeof(buffer), "%p", p);
130     return buffer;
131 }
132
133 NEVER_INLINE static const char* debugHookName(int debugHookID)
134 {
135     switch (static_cast<DebugHookID>(debugHookID)) {
136         case DidEnterCallFrame:
137             return "didEnterCallFrame";
138         case WillLeaveCallFrame:
139             return "willLeaveCallFrame";
140         case WillExecuteStatement:
141             return "willExecuteStatement";
142         case WillExecuteProgram:
143             return "willExecuteProgram";
144         case DidExecuteProgram:
145             return "didExecuteProgram";
146         case DidReachBreakpoint:
147             return "didReachBreakpoint";
148     }
149
150     ASSERT_NOT_REACHED();
151     return "";
152 }
153
154 void CodeBlock::printUnaryOp(ExecState* exec, int location, Vector<Instruction>::const_iterator& it, const char* op)
155 {
156     int r0 = (++it)->u.operand;
157     int r1 = (++it)->u.operand;
158
159     dataLog("[%4d] %s\t\t %s, %s\n", location, op, registerName(exec, r0).data(), registerName(exec, r1).data());
160 }
161
162 void CodeBlock::printBinaryOp(ExecState* exec, int location, Vector<Instruction>::const_iterator& it, const char* op)
163 {
164     int r0 = (++it)->u.operand;
165     int r1 = (++it)->u.operand;
166     int r2 = (++it)->u.operand;
167     dataLog("[%4d] %s\t\t %s, %s, %s\n", location, op, registerName(exec, r0).data(), registerName(exec, r1).data(), registerName(exec, r2).data());
168 }
169
170 void CodeBlock::printConditionalJump(ExecState* exec, const Vector<Instruction>::const_iterator&, Vector<Instruction>::const_iterator& it, int location, const char* op)
171 {
172     int r0 = (++it)->u.operand;
173     int offset = (++it)->u.operand;
174     dataLog("[%4d] %s\t\t %s, %d(->%d)\n", location, op, registerName(exec, r0).data(), offset, location + offset);
175 }
176
177 void CodeBlock::printGetByIdOp(ExecState* exec, int location, Vector<Instruction>::const_iterator& it)
178 {
179     const char* op;
180     switch (exec->interpreter()->getOpcodeID(it->u.opcode)) {
181     case op_get_by_id:
182         op = "get_by_id";
183         break;
184     case op_get_by_id_self:
185         op = "get_by_id_self";
186         break;
187     case op_get_by_id_proto:
188         op = "get_by_id_proto";
189         break;
190     case op_get_by_id_chain:
191         op = "get_by_id_chain";
192         break;
193     case op_get_by_id_getter_self:
194         op = "get_by_id_getter_self";
195         break;
196     case op_get_by_id_getter_proto:
197         op = "get_by_id_getter_proto";
198         break;
199     case op_get_by_id_getter_chain:
200         op = "get_by_id_getter_chain";
201         break;
202     case op_get_by_id_custom_self:
203         op = "get_by_id_custom_self";
204         break;
205     case op_get_by_id_custom_proto:
206         op = "get_by_id_custom_proto";
207         break;
208     case op_get_by_id_custom_chain:
209         op = "get_by_id_custom_chain";
210         break;
211     case op_get_by_id_generic:
212         op = "get_by_id_generic";
213         break;
214     case op_get_array_length:
215         op = "array_length";
216         break;
217     case op_get_string_length:
218         op = "string_length";
219         break;
220     default:
221         ASSERT_NOT_REACHED();
222         op = 0;
223     }
224     int r0 = (++it)->u.operand;
225     int r1 = (++it)->u.operand;
226     int id0 = (++it)->u.operand;
227     dataLog("[%4d] %s\t %s, %s, %s", location, op, registerName(exec, r0).data(), registerName(exec, r1).data(), idName(id0, m_identifiers[id0]).data());
228     it += 5;
229 }
230
231 static void dumpStructure(const char* name, ExecState* exec, Structure* structure, Identifier& ident)
232 {
233     if (!structure)
234         return;
235     
236     dataLog("%s = %p", name, structure);
237     
238     size_t offset = structure->get(exec->globalData(), ident);
239     if (offset != notFound)
240         dataLog(" (offset = %lu)", static_cast<unsigned long>(offset));
241 }
242
243 static void dumpChain(ExecState* exec, StructureChain* chain, Identifier& ident)
244 {
245     dataLog("chain = %p: [", chain);
246     bool first = true;
247     for (WriteBarrier<Structure>* currentStructure = chain->head();
248          *currentStructure;
249          ++currentStructure) {
250         if (first)
251             first = false;
252         else
253             dataLog(", ");
254         dumpStructure("struct", exec, currentStructure->get(), ident);
255     }
256     dataLog("]");
257 }
258
259 void CodeBlock::printGetByIdCacheStatus(ExecState* exec, int location)
260 {
261     Instruction* instruction = instructions().begin() + location;
262
263     if (exec->interpreter()->getOpcodeID(instruction[0].u.opcode) == op_method_check)
264         instruction++;
265     
266     Identifier& ident = identifier(instruction[3].u.operand);
267     
268 #if ENABLE(LLINT)
269     Structure* structure = instruction[4].u.structure.get();
270     dataLog(" llint(");
271     dumpStructure("struct", exec, structure, ident);
272     dataLog(")");
273 #endif
274
275 #if ENABLE(JIT)
276     if (numberOfStructureStubInfos()) {
277         dataLog(" jit(");
278         StructureStubInfo& stubInfo = getStubInfo(location);
279         if (!stubInfo.seen)
280             dataLog("not seen");
281         else {
282             Structure* baseStructure = 0;
283             Structure* prototypeStructure = 0;
284             StructureChain* chain = 0;
285             PolymorphicAccessStructureList* structureList = 0;
286             int listSize = 0;
287             
288             switch (stubInfo.accessType) {
289             case access_get_by_id_self:
290                 dataLog("self");
291                 baseStructure = stubInfo.u.getByIdSelf.baseObjectStructure.get();
292                 break;
293             case access_get_by_id_proto:
294                 dataLog("proto");
295                 baseStructure = stubInfo.u.getByIdProto.baseObjectStructure.get();
296                 prototypeStructure = stubInfo.u.getByIdProto.prototypeStructure.get();
297                 break;
298             case access_get_by_id_chain:
299                 dataLog("chain");
300                 baseStructure = stubInfo.u.getByIdChain.baseObjectStructure.get();
301                 chain = stubInfo.u.getByIdChain.chain.get();
302                 break;
303             case access_get_by_id_self_list:
304                 dataLog("self_list");
305                 structureList = stubInfo.u.getByIdSelfList.structureList;
306                 listSize = stubInfo.u.getByIdSelfList.listSize;
307                 break;
308             case access_get_by_id_proto_list:
309                 dataLog("proto_list");
310                 structureList = stubInfo.u.getByIdProtoList.structureList;
311                 listSize = stubInfo.u.getByIdProtoList.listSize;
312                 break;
313             case access_unset:
314                 dataLog("unset");
315                 break;
316             case access_get_by_id_generic:
317                 dataLog("generic");
318                 break;
319             case access_get_array_length:
320                 dataLog("array_length");
321                 break;
322             case access_get_string_length:
323                 dataLog("string_length");
324                 break;
325             default:
326                 ASSERT_NOT_REACHED();
327                 break;
328             }
329             
330             if (baseStructure) {
331                 dataLog(", ");
332                 dumpStructure("struct", exec, baseStructure, ident);
333             }
334             
335             if (prototypeStructure) {
336                 dataLog(", ");
337                 dumpStructure("prototypeStruct", exec, baseStructure, ident);
338             }
339             
340             if (chain) {
341                 dataLog(", ");
342                 dumpChain(exec, chain, ident);
343             }
344             
345             if (structureList) {
346                 dataLog(", list = %p: [", structureList);
347                 for (int i = 0; i < listSize; ++i) {
348                     if (i)
349                         dataLog(", ");
350                     dataLog("(");
351                     dumpStructure("base", exec, structureList->list[i].base.get(), ident);
352                     if (structureList->list[i].isChain) {
353                         if (structureList->list[i].u.chain.get()) {
354                             dataLog(", ");
355                             dumpChain(exec, structureList->list[i].u.chain.get(), ident);
356                         }
357                     } else {
358                         if (structureList->list[i].u.proto.get()) {
359                             dataLog(", ");
360                             dumpStructure("proto", exec, structureList->list[i].u.proto.get(), ident);
361                         }
362                     }
363                     dataLog(")");
364                 }
365                 dataLog("]");
366             }
367         }
368         dataLog(")");
369     }
370 #endif
371 }
372
373 void CodeBlock::printCallOp(ExecState* exec, int location, Vector<Instruction>::const_iterator& it, const char* op, CacheDumpMode cacheDumpMode)
374 {
375     int func = (++it)->u.operand;
376     int argCount = (++it)->u.operand;
377     int registerOffset = (++it)->u.operand;
378     dataLog("[%4d] %s\t %s, %d, %d", location, op, registerName(exec, func).data(), argCount, registerOffset);
379     if (cacheDumpMode == DumpCaches) {
380 #if ENABLE(LLINT)
381         LLIntCallLinkInfo* callLinkInfo = it[1].u.callLinkInfo;
382         if (callLinkInfo->lastSeenCallee) {
383             dataLog(" llint(%p, exec %p)",
384                     callLinkInfo->lastSeenCallee.get(),
385                     callLinkInfo->lastSeenCallee->executable());
386         } else
387             dataLog(" llint(not set)");
388 #endif
389 #if ENABLE(JIT)
390         if (numberOfCallLinkInfos()) {
391             JSFunction* target = getCallLinkInfo(location).lastSeenCallee.get();
392             if (target)
393                 dataLog(" jit(%p, exec %p)", target, target->executable());
394             else
395                 dataLog(" jit(not set)");
396         }
397 #endif
398     }
399     dataLog("\n");
400     it += 2;
401 }
402
403 void CodeBlock::printPutByIdOp(ExecState* exec, int location, Vector<Instruction>::const_iterator& it, const char* op)
404 {
405     int r0 = (++it)->u.operand;
406     int id0 = (++it)->u.operand;
407     int r1 = (++it)->u.operand;
408     dataLog("[%4d] %s\t %s, %s, %s\n", location, op, registerName(exec, r0).data(), idName(id0, m_identifiers[id0]).data(), registerName(exec, r1).data());
409     it += 5;
410 }
411
412 #if ENABLE(JIT)
413 static bool isGlobalResolve(OpcodeID opcodeID)
414 {
415     return opcodeID == op_resolve_global || opcodeID == op_resolve_global_dynamic;
416 }
417
418 static unsigned instructionOffsetForNth(ExecState* exec, const RefCountedArray<Instruction>& instructions, int nth, bool (*predicate)(OpcodeID))
419 {
420     size_t i = 0;
421     while (i < instructions.size()) {
422         OpcodeID currentOpcode = exec->interpreter()->getOpcodeID(instructions[i].u.opcode);
423         if (predicate(currentOpcode)) {
424             if (!--nth)
425                 return i;
426         }
427         i += opcodeLengths[currentOpcode];
428     }
429
430     ASSERT_NOT_REACHED();
431     return 0;
432 }
433
434 static void printGlobalResolveInfo(const GlobalResolveInfo& resolveInfo, unsigned instructionOffset)
435 {
436     dataLog("  [%4d] %s: %s\n", instructionOffset, "resolve_global", pointerToSourceString(resolveInfo.structure).utf8().data());
437 }
438 #endif
439
440 void CodeBlock::printStructure(const char* name, const Instruction* vPC, int operand)
441 {
442     unsigned instructionOffset = vPC - instructions().begin();
443     dataLog("  [%4d] %s: %s\n", instructionOffset, name, pointerToSourceString(vPC[operand].u.structure).utf8().data());
444 }
445
446 void CodeBlock::printStructures(const Instruction* vPC)
447 {
448     Interpreter* interpreter = m_globalData->interpreter;
449     unsigned instructionOffset = vPC - instructions().begin();
450
451     if (vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id)) {
452         printStructure("get_by_id", vPC, 4);
453         return;
454     }
455     if (vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_self)) {
456         printStructure("get_by_id_self", vPC, 4);
457         return;
458     }
459     if (vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_proto)) {
460         dataLog("  [%4d] %s: %s, %s\n", instructionOffset, "get_by_id_proto", pointerToSourceString(vPC[4].u.structure).utf8().data(), pointerToSourceString(vPC[5].u.structure).utf8().data());
461         return;
462     }
463     if (vPC[0].u.opcode == interpreter->getOpcode(op_put_by_id_transition)) {
464         dataLog("  [%4d] %s: %s, %s, %s\n", instructionOffset, "put_by_id_transition", pointerToSourceString(vPC[4].u.structure).utf8().data(), pointerToSourceString(vPC[5].u.structure).utf8().data(), pointerToSourceString(vPC[6].u.structureChain).utf8().data());
465         return;
466     }
467     if (vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_chain)) {
468         dataLog("  [%4d] %s: %s, %s\n", instructionOffset, "get_by_id_chain", pointerToSourceString(vPC[4].u.structure).utf8().data(), pointerToSourceString(vPC[5].u.structureChain).utf8().data());
469         return;
470     }
471     if (vPC[0].u.opcode == interpreter->getOpcode(op_put_by_id)) {
472         printStructure("put_by_id", vPC, 4);
473         return;
474     }
475     if (vPC[0].u.opcode == interpreter->getOpcode(op_put_by_id_replace)) {
476         printStructure("put_by_id_replace", vPC, 4);
477         return;
478     }
479     if (vPC[0].u.opcode == interpreter->getOpcode(op_resolve_global)) {
480         printStructure("resolve_global", vPC, 4);
481         return;
482     }
483     if (vPC[0].u.opcode == interpreter->getOpcode(op_resolve_global_dynamic)) {
484         printStructure("resolve_global_dynamic", vPC, 4);
485         return;
486     }
487
488     // These m_instructions doesn't ref Structures.
489     ASSERT(vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_generic) || vPC[0].u.opcode == interpreter->getOpcode(op_put_by_id_generic) || vPC[0].u.opcode == interpreter->getOpcode(op_call) || vPC[0].u.opcode == interpreter->getOpcode(op_call_eval) || vPC[0].u.opcode == interpreter->getOpcode(op_construct));
490 }
491
492 void CodeBlock::dump(ExecState* exec)
493 {
494     size_t instructionCount = 0;
495
496     for (size_t i = 0; i < instructions().size(); i += opcodeLengths[exec->interpreter()->getOpcodeID(instructions()[i].u.opcode)])
497         ++instructionCount;
498
499     dataLog(
500         "%lu m_instructions; %lu bytes at %p (%s); %d parameter(s); %d callee register(s); %d variable(s)",
501         static_cast<unsigned long>(instructions().size()),
502         static_cast<unsigned long>(instructions().size() * sizeof(Instruction)),
503         this, codeTypeToString(codeType()), m_numParameters, m_numCalleeRegisters,
504         m_numVars);
505     if (m_numCapturedVars)
506         dataLog("; %d captured var(s)", m_numCapturedVars);
507     if (usesArguments()) {
508         dataLog(
509             "; uses arguments, in r%d, r%d",
510             argumentsRegister(),
511             unmodifiedArgumentsRegister(argumentsRegister()));
512     }
513     if (needsFullScopeChain() && codeType() == FunctionCode)
514         dataLog("; activation in r%d", activationRegister());
515     dataLog("\n\n");
516
517     Vector<Instruction>::const_iterator begin = instructions().begin();
518     Vector<Instruction>::const_iterator end = instructions().end();
519     for (Vector<Instruction>::const_iterator it = begin; it != end; ++it)
520         dump(exec, begin, it);
521
522     if (!m_identifiers.isEmpty()) {
523         dataLog("\nIdentifiers:\n");
524         size_t i = 0;
525         do {
526             dataLog("  id%u = %s\n", static_cast<unsigned>(i), m_identifiers[i].ustring().utf8().data());
527             ++i;
528         } while (i != m_identifiers.size());
529     }
530
531     if (!m_constantRegisters.isEmpty()) {
532         dataLog("\nConstants:\n");
533         size_t i = 0;
534         do {
535             dataLog("   k%u = %s\n", static_cast<unsigned>(i), valueToSourceString(exec, m_constantRegisters[i].get()).utf8().data());
536             ++i;
537         } while (i < m_constantRegisters.size());
538     }
539
540     if (m_rareData && !m_rareData->m_regexps.isEmpty()) {
541         dataLog("\nm_regexps:\n");
542         size_t i = 0;
543         do {
544             dataLog("  re%u = %s\n", static_cast<unsigned>(i), regexpToSourceString(m_rareData->m_regexps[i].get()).utf8().data());
545             ++i;
546         } while (i < m_rareData->m_regexps.size());
547     }
548
549 #if ENABLE(JIT)
550     if (!m_globalResolveInfos.isEmpty() || !m_structureStubInfos.isEmpty())
551         dataLog("\nStructures:\n");
552
553     if (!m_globalResolveInfos.isEmpty()) {
554         size_t i = 0;
555         do {
556              printGlobalResolveInfo(m_globalResolveInfos[i], instructionOffsetForNth(exec, instructions(), i + 1, isGlobalResolve));
557              ++i;
558         } while (i < m_globalResolveInfos.size());
559     }
560 #endif
561 #if ENABLE(CLASSIC_INTERPRETER)
562     if (!m_globalResolveInstructions.isEmpty() || !m_propertyAccessInstructions.isEmpty())
563         dataLog("\nStructures:\n");
564
565     if (!m_globalResolveInstructions.isEmpty()) {
566         size_t i = 0;
567         do {
568              printStructures(&instructions()[m_globalResolveInstructions[i]]);
569              ++i;
570         } while (i < m_globalResolveInstructions.size());
571     }
572     if (!m_propertyAccessInstructions.isEmpty()) {
573         size_t i = 0;
574         do {
575             printStructures(&instructions()[m_propertyAccessInstructions[i]]);
576              ++i;
577         } while (i < m_propertyAccessInstructions.size());
578     }
579 #endif
580
581     if (m_rareData && !m_rareData->m_exceptionHandlers.isEmpty()) {
582         dataLog("\nException Handlers:\n");
583         unsigned i = 0;
584         do {
585             dataLog("\t %d: { start: [%4d] end: [%4d] target: [%4d] }\n", i + 1, m_rareData->m_exceptionHandlers[i].start, m_rareData->m_exceptionHandlers[i].end, m_rareData->m_exceptionHandlers[i].target);
586             ++i;
587         } while (i < m_rareData->m_exceptionHandlers.size());
588     }
589     
590     if (m_rareData && !m_rareData->m_immediateSwitchJumpTables.isEmpty()) {
591         dataLog("Immediate Switch Jump Tables:\n");
592         unsigned i = 0;
593         do {
594             dataLog("  %1d = {\n", i);
595             int entry = 0;
596             Vector<int32_t>::const_iterator end = m_rareData->m_immediateSwitchJumpTables[i].branchOffsets.end();
597             for (Vector<int32_t>::const_iterator iter = m_rareData->m_immediateSwitchJumpTables[i].branchOffsets.begin(); iter != end; ++iter, ++entry) {
598                 if (!*iter)
599                     continue;
600                 dataLog("\t\t%4d => %04d\n", entry + m_rareData->m_immediateSwitchJumpTables[i].min, *iter);
601             }
602             dataLog("      }\n");
603             ++i;
604         } while (i < m_rareData->m_immediateSwitchJumpTables.size());
605     }
606     
607     if (m_rareData && !m_rareData->m_characterSwitchJumpTables.isEmpty()) {
608         dataLog("\nCharacter Switch Jump Tables:\n");
609         unsigned i = 0;
610         do {
611             dataLog("  %1d = {\n", i);
612             int entry = 0;
613             Vector<int32_t>::const_iterator end = m_rareData->m_characterSwitchJumpTables[i].branchOffsets.end();
614             for (Vector<int32_t>::const_iterator iter = m_rareData->m_characterSwitchJumpTables[i].branchOffsets.begin(); iter != end; ++iter, ++entry) {
615                 if (!*iter)
616                     continue;
617                 ASSERT(!((i + m_rareData->m_characterSwitchJumpTables[i].min) & ~0xFFFF));
618                 UChar ch = static_cast<UChar>(entry + m_rareData->m_characterSwitchJumpTables[i].min);
619                 dataLog("\t\t\"%s\" => %04d\n", UString(&ch, 1).utf8().data(), *iter);
620         }
621             dataLog("      }\n");
622             ++i;
623         } while (i < m_rareData->m_characterSwitchJumpTables.size());
624     }
625     
626     if (m_rareData && !m_rareData->m_stringSwitchJumpTables.isEmpty()) {
627         dataLog("\nString Switch Jump Tables:\n");
628         unsigned i = 0;
629         do {
630             dataLog("  %1d = {\n", i);
631             StringJumpTable::StringOffsetTable::const_iterator end = m_rareData->m_stringSwitchJumpTables[i].offsetTable.end();
632             for (StringJumpTable::StringOffsetTable::const_iterator iter = m_rareData->m_stringSwitchJumpTables[i].offsetTable.begin(); iter != end; ++iter)
633                 dataLog("\t\t\"%s\" => %04d\n", UString(iter->first).utf8().data(), iter->second.branchOffset);
634             dataLog("      }\n");
635             ++i;
636         } while (i < m_rareData->m_stringSwitchJumpTables.size());
637     }
638
639     dataLog("\n");
640 }
641
642 void CodeBlock::dump(ExecState* exec, const Vector<Instruction>::const_iterator& begin, Vector<Instruction>::const_iterator& it)
643 {
644     int location = it - begin;
645     switch (exec->interpreter()->getOpcodeID(it->u.opcode)) {
646         case op_enter: {
647             dataLog("[%4d] enter\n", location);
648             break;
649         }
650         case op_create_activation: {
651             int r0 = (++it)->u.operand;
652             dataLog("[%4d] create_activation %s\n", location, registerName(exec, r0).data());
653             break;
654         }
655         case op_create_arguments: {
656             int r0 = (++it)->u.operand;
657             dataLog("[%4d] create_arguments\t %s\n", location, registerName(exec, r0).data());
658             break;
659         }
660         case op_init_lazy_reg: {
661             int r0 = (++it)->u.operand;
662             dataLog("[%4d] init_lazy_reg\t %s\n", location, registerName(exec, r0).data());
663             break;
664         }
665         case op_create_this: {
666             int r0 = (++it)->u.operand;
667             dataLog("[%4d] create_this %s\n", location, registerName(exec, r0).data());
668             break;
669         }
670         case op_convert_this: {
671             int r0 = (++it)->u.operand;
672             dataLog("[%4d] convert_this\t %s\n", location, registerName(exec, r0).data());
673             ++it; // Skip value profile.
674             break;
675         }
676         case op_new_object: {
677             int r0 = (++it)->u.operand;
678             dataLog("[%4d] new_object\t %s\n", location, registerName(exec, r0).data());
679             break;
680         }
681         case op_new_array: {
682             int dst = (++it)->u.operand;
683             int argv = (++it)->u.operand;
684             int argc = (++it)->u.operand;
685             dataLog("[%4d] new_array\t %s, %s, %d\n", location, registerName(exec, dst).data(), registerName(exec, argv).data(), argc);
686             break;
687         }
688         case op_new_array_buffer: {
689             int dst = (++it)->u.operand;
690             int argv = (++it)->u.operand;
691             int argc = (++it)->u.operand;
692             dataLog("[%4d] new_array_buffer %s, %d, %d\n", location, registerName(exec, dst).data(), argv, argc);
693             break;
694         }
695         case op_new_regexp: {
696             int r0 = (++it)->u.operand;
697             int re0 = (++it)->u.operand;
698             dataLog("[%4d] new_regexp\t %s, ", location, registerName(exec, r0).data());
699             if (r0 >=0 && r0 < (int)numberOfRegExps())
700                 dataLog("%s\n", regexpName(re0, regexp(re0)).data());
701             else
702                 dataLog("bad_regexp(%d)\n", re0);
703             break;
704         }
705         case op_mov: {
706             int r0 = (++it)->u.operand;
707             int r1 = (++it)->u.operand;
708             dataLog("[%4d] mov\t\t %s, %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data());
709             break;
710         }
711         case op_not: {
712             printUnaryOp(exec, location, it, "not");
713             break;
714         }
715         case op_eq: {
716             printBinaryOp(exec, location, it, "eq");
717             break;
718         }
719         case op_eq_null: {
720             printUnaryOp(exec, location, it, "eq_null");
721             break;
722         }
723         case op_neq: {
724             printBinaryOp(exec, location, it, "neq");
725             break;
726         }
727         case op_neq_null: {
728             printUnaryOp(exec, location, it, "neq_null");
729             break;
730         }
731         case op_stricteq: {
732             printBinaryOp(exec, location, it, "stricteq");
733             break;
734         }
735         case op_nstricteq: {
736             printBinaryOp(exec, location, it, "nstricteq");
737             break;
738         }
739         case op_less: {
740             printBinaryOp(exec, location, it, "less");
741             break;
742         }
743         case op_lesseq: {
744             printBinaryOp(exec, location, it, "lesseq");
745             break;
746         }
747         case op_greater: {
748             printBinaryOp(exec, location, it, "greater");
749             break;
750         }
751         case op_greatereq: {
752             printBinaryOp(exec, location, it, "greatereq");
753             break;
754         }
755         case op_pre_inc: {
756             int r0 = (++it)->u.operand;
757             dataLog("[%4d] pre_inc\t\t %s\n", location, registerName(exec, r0).data());
758             break;
759         }
760         case op_pre_dec: {
761             int r0 = (++it)->u.operand;
762             dataLog("[%4d] pre_dec\t\t %s\n", location, registerName(exec, r0).data());
763             break;
764         }
765         case op_post_inc: {
766             printUnaryOp(exec, location, it, "post_inc");
767             break;
768         }
769         case op_post_dec: {
770             printUnaryOp(exec, location, it, "post_dec");
771             break;
772         }
773         case op_to_jsnumber: {
774             printUnaryOp(exec, location, it, "to_jsnumber");
775             break;
776         }
777         case op_negate: {
778             printUnaryOp(exec, location, it, "negate");
779             break;
780         }
781         case op_add: {
782             printBinaryOp(exec, location, it, "add");
783             ++it;
784             break;
785         }
786         case op_mul: {
787             printBinaryOp(exec, location, it, "mul");
788             ++it;
789             break;
790         }
791         case op_div: {
792             printBinaryOp(exec, location, it, "div");
793             ++it;
794             break;
795         }
796         case op_mod: {
797             printBinaryOp(exec, location, it, "mod");
798             break;
799         }
800         case op_sub: {
801             printBinaryOp(exec, location, it, "sub");
802             ++it;
803             break;
804         }
805         case op_lshift: {
806             printBinaryOp(exec, location, it, "lshift");
807             break;            
808         }
809         case op_rshift: {
810             printBinaryOp(exec, location, it, "rshift");
811             break;
812         }
813         case op_urshift: {
814             printBinaryOp(exec, location, it, "urshift");
815             break;
816         }
817         case op_bitand: {
818             printBinaryOp(exec, location, it, "bitand");
819             ++it;
820             break;
821         }
822         case op_bitxor: {
823             printBinaryOp(exec, location, it, "bitxor");
824             ++it;
825             break;
826         }
827         case op_bitor: {
828             printBinaryOp(exec, location, it, "bitor");
829             ++it;
830             break;
831         }
832         case op_check_has_instance: {
833             int base = (++it)->u.operand;
834             dataLog("[%4d] check_has_instance\t\t %s\n", location, registerName(exec, base).data());
835             break;
836         }
837         case op_instanceof: {
838             int r0 = (++it)->u.operand;
839             int r1 = (++it)->u.operand;
840             int r2 = (++it)->u.operand;
841             int r3 = (++it)->u.operand;
842             dataLog("[%4d] instanceof\t\t %s, %s, %s, %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), registerName(exec, r2).data(), registerName(exec, r3).data());
843             break;
844         }
845         case op_typeof: {
846             printUnaryOp(exec, location, it, "typeof");
847             break;
848         }
849         case op_is_undefined: {
850             printUnaryOp(exec, location, it, "is_undefined");
851             break;
852         }
853         case op_is_boolean: {
854             printUnaryOp(exec, location, it, "is_boolean");
855             break;
856         }
857         case op_is_number: {
858             printUnaryOp(exec, location, it, "is_number");
859             break;
860         }
861         case op_is_string: {
862             printUnaryOp(exec, location, it, "is_string");
863             break;
864         }
865         case op_is_object: {
866             printUnaryOp(exec, location, it, "is_object");
867             break;
868         }
869         case op_is_function: {
870             printUnaryOp(exec, location, it, "is_function");
871             break;
872         }
873         case op_in: {
874             printBinaryOp(exec, location, it, "in");
875             break;
876         }
877         case op_resolve: {
878             int r0 = (++it)->u.operand;
879             int id0 = (++it)->u.operand;
880             dataLog("[%4d] resolve\t\t %s, %s\n", location, registerName(exec, r0).data(), idName(id0, m_identifiers[id0]).data());
881             it++;
882             break;
883         }
884         case op_resolve_skip: {
885             int r0 = (++it)->u.operand;
886             int id0 = (++it)->u.operand;
887             int skipLevels = (++it)->u.operand;
888             dataLog("[%4d] resolve_skip\t %s, %s, %d\n", location, registerName(exec, r0).data(), idName(id0, m_identifiers[id0]).data(), skipLevels);
889             it++;
890             break;
891         }
892         case op_resolve_global: {
893             int r0 = (++it)->u.operand;
894             int id0 = (++it)->u.operand;
895             dataLog("[%4d] resolve_global\t %s, %s\n", location, registerName(exec, r0).data(), idName(id0, m_identifiers[id0]).data());
896             it += 3;
897             break;
898         }
899         case op_resolve_global_dynamic: {
900             int r0 = (++it)->u.operand;
901             int id0 = (++it)->u.operand;
902             JSValue scope = JSValue((++it)->u.jsCell.get());
903             ++it;
904             int depth = (++it)->u.operand;
905             dataLog("[%4d] resolve_global_dynamic\t %s, %s, %s, %d\n", location, registerName(exec, r0).data(), valueToSourceString(exec, scope).utf8().data(), idName(id0, m_identifiers[id0]).data(), depth);
906             ++it;
907             break;
908         }
909         case op_get_scoped_var: {
910             int r0 = (++it)->u.operand;
911             int index = (++it)->u.operand;
912             int skipLevels = (++it)->u.operand;
913             dataLog("[%4d] get_scoped_var\t %s, %d, %d\n", location, registerName(exec, r0).data(), index, skipLevels);
914             it++;
915             break;
916         }
917         case op_put_scoped_var: {
918             int index = (++it)->u.operand;
919             int skipLevels = (++it)->u.operand;
920             int r0 = (++it)->u.operand;
921             dataLog("[%4d] put_scoped_var\t %d, %d, %s\n", location, index, skipLevels, registerName(exec, r0).data());
922             break;
923         }
924         case op_get_global_var: {
925             int r0 = (++it)->u.operand;
926             WriteBarrier<Unknown>* registerPointer = (++it)->u.registerPointer;
927             dataLog("[%4d] get_global_var\t %s, g%d(%p)\n", location, registerName(exec, r0).data(), m_globalObject->findRegisterIndex(registerPointer), registerPointer);
928             it++;
929             break;
930         }
931         case op_get_global_var_watchable: {
932             int r0 = (++it)->u.operand;
933             WriteBarrier<Unknown>* registerPointer = (++it)->u.registerPointer;
934             dataLog("[%4d] get_global_var_watchable\t %s, g%d(%p)\n", location, registerName(exec, r0).data(), m_globalObject->findRegisterIndex(registerPointer), registerPointer);
935             it++;
936             it++;
937             break;
938         }
939         case op_put_global_var: {
940             WriteBarrier<Unknown>* registerPointer = (++it)->u.registerPointer;
941             int r0 = (++it)->u.operand;
942             dataLog("[%4d] put_global_var\t g%d(%p), %s\n", location, m_globalObject->findRegisterIndex(registerPointer), registerPointer, registerName(exec, r0).data());
943             break;
944         }
945         case op_put_global_var_check: {
946             WriteBarrier<Unknown>* registerPointer = (++it)->u.registerPointer;
947             int r0 = (++it)->u.operand;
948             dataLog("[%4d] put_global_var_check\t g%d(%p), %s\n", location, m_globalObject->findRegisterIndex(registerPointer), registerPointer, registerName(exec, r0).data());
949             it++;
950             it++;
951             break;
952         }
953         case op_resolve_base: {
954             int r0 = (++it)->u.operand;
955             int id0 = (++it)->u.operand;
956             int isStrict = (++it)->u.operand;
957             dataLog("[%4d] resolve_base%s\t %s, %s\n", location, isStrict ? "_strict" : "", registerName(exec, r0).data(), idName(id0, m_identifiers[id0]).data());
958             it++;
959             break;
960         }
961         case op_ensure_property_exists: {
962             int r0 = (++it)->u.operand;
963             int id0 = (++it)->u.operand;
964             dataLog("[%4d] ensure_property_exists\t %s, %s\n", location, registerName(exec, r0).data(), idName(id0, m_identifiers[id0]).data());
965             break;
966         }
967         case op_resolve_with_base: {
968             int r0 = (++it)->u.operand;
969             int r1 = (++it)->u.operand;
970             int id0 = (++it)->u.operand;
971             dataLog("[%4d] resolve_with_base %s, %s, %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), idName(id0, m_identifiers[id0]).data());
972             it++;
973             break;
974         }
975         case op_resolve_with_this: {
976             int r0 = (++it)->u.operand;
977             int r1 = (++it)->u.operand;
978             int id0 = (++it)->u.operand;
979             dataLog("[%4d] resolve_with_this %s, %s, %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), idName(id0, m_identifiers[id0]).data());
980             it++;
981             break;
982         }
983         case op_get_by_id:
984         case op_get_by_id_self:
985         case op_get_by_id_proto:
986         case op_get_by_id_chain:
987         case op_get_by_id_getter_self:
988         case op_get_by_id_getter_proto:
989         case op_get_by_id_getter_chain:
990         case op_get_by_id_custom_self:
991         case op_get_by_id_custom_proto:
992         case op_get_by_id_custom_chain:
993         case op_get_by_id_generic:
994         case op_get_array_length:
995         case op_get_string_length: {
996             printGetByIdOp(exec, location, it);
997             printGetByIdCacheStatus(exec, location);
998             dataLog("\n");
999             break;
1000         }
1001         case op_get_arguments_length: {
1002             printUnaryOp(exec, location, it, "get_arguments_length");
1003             it++;
1004             break;
1005         }
1006         case op_put_by_id: {
1007             printPutByIdOp(exec, location, it, "put_by_id");
1008             break;
1009         }
1010         case op_put_by_id_replace: {
1011             printPutByIdOp(exec, location, it, "put_by_id_replace");
1012             break;
1013         }
1014         case op_put_by_id_transition: {
1015             printPutByIdOp(exec, location, it, "put_by_id_transition");
1016             break;
1017         }
1018         case op_put_by_id_transition_direct: {
1019             printPutByIdOp(exec, location, it, "put_by_id_transition_direct");
1020             break;
1021         }
1022         case op_put_by_id_transition_normal: {
1023             printPutByIdOp(exec, location, it, "put_by_id_transition_normal");
1024             break;
1025         }
1026         case op_put_by_id_generic: {
1027             printPutByIdOp(exec, location, it, "put_by_id_generic");
1028             break;
1029         }
1030         case op_put_getter_setter: {
1031             int r0 = (++it)->u.operand;
1032             int id0 = (++it)->u.operand;
1033             int r1 = (++it)->u.operand;
1034             int r2 = (++it)->u.operand;
1035             dataLog("[%4d] put_getter_setter\t %s, %s, %s, %s\n", location, registerName(exec, r0).data(), idName(id0, m_identifiers[id0]).data(), registerName(exec, r1).data(), registerName(exec, r2).data());
1036             break;
1037         }
1038         case op_method_check: {
1039             dataLog("[%4d] method_check", location);
1040 #if ENABLE(JIT)
1041             if (numberOfMethodCallLinkInfos()) {
1042                 MethodCallLinkInfo& methodCall = getMethodCallLinkInfo(location);
1043                 dataLog(" jit(");
1044                 if (!methodCall.seen)
1045                     dataLog("not seen");
1046                 else {
1047                     // Use the fact that MethodCallLinkStatus already does smart things
1048                     // for decoding seen method calls.
1049                     MethodCallLinkStatus status = MethodCallLinkStatus::computeFor(this, location);
1050                     if (!status)
1051                         dataLog("not set");
1052                     else {
1053                         dataLog("function = %p (executable = ", status.function());
1054                         JSCell* functionAsCell = getJSFunction(status.function());
1055                         if (functionAsCell)
1056                             dataLog("%p", jsCast<JSFunction*>(functionAsCell)->executable());
1057                         else
1058                             dataLog("N/A");
1059                         dataLog("), struct = %p", status.structure());
1060                         if (status.needsPrototypeCheck())
1061                             dataLog(", prototype = %p, struct = %p", status.prototype(), status.prototypeStructure());
1062                     }
1063                 }
1064                 dataLog(")");
1065             }
1066 #endif
1067             dataLog("\n");
1068             ++it;
1069             printGetByIdOp(exec, location, it);
1070             printGetByIdCacheStatus(exec, location);
1071             dataLog("\n");
1072             break;
1073         }
1074         case op_del_by_id: {
1075             int r0 = (++it)->u.operand;
1076             int r1 = (++it)->u.operand;
1077             int id0 = (++it)->u.operand;
1078             dataLog("[%4d] del_by_id\t %s, %s, %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), idName(id0, m_identifiers[id0]).data());
1079             break;
1080         }
1081         case op_get_by_val: {
1082             int r0 = (++it)->u.operand;
1083             int r1 = (++it)->u.operand;
1084             int r2 = (++it)->u.operand;
1085             dataLog("[%4d] get_by_val\t %s, %s, %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), registerName(exec, r2).data());
1086             it++;
1087             break;
1088         }
1089         case op_get_argument_by_val: {
1090             int r0 = (++it)->u.operand;
1091             int r1 = (++it)->u.operand;
1092             int r2 = (++it)->u.operand;
1093             dataLog("[%4d] get_argument_by_val\t %s, %s, %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), registerName(exec, r2).data());
1094             ++it;
1095             break;
1096         }
1097         case op_get_by_pname: {
1098             int r0 = (++it)->u.operand;
1099             int r1 = (++it)->u.operand;
1100             int r2 = (++it)->u.operand;
1101             int r3 = (++it)->u.operand;
1102             int r4 = (++it)->u.operand;
1103             int r5 = (++it)->u.operand;
1104             dataLog("[%4d] get_by_pname\t %s, %s, %s, %s, %s, %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), registerName(exec, r2).data(), registerName(exec, r3).data(), registerName(exec, r4).data(), registerName(exec, r5).data());
1105             break;
1106         }
1107         case op_put_by_val: {
1108             int r0 = (++it)->u.operand;
1109             int r1 = (++it)->u.operand;
1110             int r2 = (++it)->u.operand;
1111             dataLog("[%4d] put_by_val\t %s, %s, %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), registerName(exec, r2).data());
1112             break;
1113         }
1114         case op_del_by_val: {
1115             int r0 = (++it)->u.operand;
1116             int r1 = (++it)->u.operand;
1117             int r2 = (++it)->u.operand;
1118             dataLog("[%4d] del_by_val\t %s, %s, %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), registerName(exec, r2).data());
1119             break;
1120         }
1121         case op_put_by_index: {
1122             int r0 = (++it)->u.operand;
1123             unsigned n0 = (++it)->u.operand;
1124             int r1 = (++it)->u.operand;
1125             dataLog("[%4d] put_by_index\t %s, %u, %s\n", location, registerName(exec, r0).data(), n0, registerName(exec, r1).data());
1126             break;
1127         }
1128         case op_jmp: {
1129             int offset = (++it)->u.operand;
1130             dataLog("[%4d] jmp\t\t %d(->%d)\n", location, offset, location + offset);
1131             break;
1132         }
1133         case op_loop: {
1134             int offset = (++it)->u.operand;
1135             dataLog("[%4d] loop\t\t %d(->%d)\n", location, offset, location + offset);
1136             break;
1137         }
1138         case op_jtrue: {
1139             printConditionalJump(exec, begin, it, location, "jtrue");
1140             break;
1141         }
1142         case op_loop_if_true: {
1143             printConditionalJump(exec, begin, it, location, "loop_if_true");
1144             break;
1145         }
1146         case op_loop_if_false: {
1147             printConditionalJump(exec, begin, it, location, "loop_if_false");
1148             break;
1149         }
1150         case op_jfalse: {
1151             printConditionalJump(exec, begin, it, location, "jfalse");
1152             break;
1153         }
1154         case op_jeq_null: {
1155             printConditionalJump(exec, begin, it, location, "jeq_null");
1156             break;
1157         }
1158         case op_jneq_null: {
1159             printConditionalJump(exec, begin, it, location, "jneq_null");
1160             break;
1161         }
1162         case op_jneq_ptr: {
1163             int r0 = (++it)->u.operand;
1164             void* pointer = (++it)->u.pointer;
1165             int offset = (++it)->u.operand;
1166             dataLog("[%4d] jneq_ptr\t\t %s, %p, %d(->%d)\n", location, registerName(exec, r0).data(), pointer, offset, location + offset);
1167             break;
1168         }
1169         case op_jless: {
1170             int r0 = (++it)->u.operand;
1171             int r1 = (++it)->u.operand;
1172             int offset = (++it)->u.operand;
1173             dataLog("[%4d] jless\t\t %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), offset, location + offset);
1174             break;
1175         }
1176         case op_jlesseq: {
1177             int r0 = (++it)->u.operand;
1178             int r1 = (++it)->u.operand;
1179             int offset = (++it)->u.operand;
1180             dataLog("[%4d] jlesseq\t\t %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), offset, location + offset);
1181             break;
1182         }
1183         case op_jgreater: {
1184             int r0 = (++it)->u.operand;
1185             int r1 = (++it)->u.operand;
1186             int offset = (++it)->u.operand;
1187             dataLog("[%4d] jgreater\t\t %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), offset, location + offset);
1188             break;
1189         }
1190         case op_jgreatereq: {
1191             int r0 = (++it)->u.operand;
1192             int r1 = (++it)->u.operand;
1193             int offset = (++it)->u.operand;
1194             dataLog("[%4d] jgreatereq\t\t %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), offset, location + offset);
1195             break;
1196         }
1197         case op_jnless: {
1198             int r0 = (++it)->u.operand;
1199             int r1 = (++it)->u.operand;
1200             int offset = (++it)->u.operand;
1201             dataLog("[%4d] jnless\t\t %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), offset, location + offset);
1202             break;
1203         }
1204         case op_jnlesseq: {
1205             int r0 = (++it)->u.operand;
1206             int r1 = (++it)->u.operand;
1207             int offset = (++it)->u.operand;
1208             dataLog("[%4d] jnlesseq\t\t %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), offset, location + offset);
1209             break;
1210         }
1211         case op_jngreater: {
1212             int r0 = (++it)->u.operand;
1213             int r1 = (++it)->u.operand;
1214             int offset = (++it)->u.operand;
1215             dataLog("[%4d] jngreater\t\t %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), offset, location + offset);
1216             break;
1217         }
1218         case op_jngreatereq: {
1219             int r0 = (++it)->u.operand;
1220             int r1 = (++it)->u.operand;
1221             int offset = (++it)->u.operand;
1222             dataLog("[%4d] jngreatereq\t\t %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), offset, location + offset);
1223             break;
1224         }
1225         case op_loop_if_less: {
1226             int r0 = (++it)->u.operand;
1227             int r1 = (++it)->u.operand;
1228             int offset = (++it)->u.operand;
1229             dataLog("[%4d] loop_if_less\t %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), offset, location + offset);
1230             break;
1231         }
1232         case op_loop_if_lesseq: {
1233             int r0 = (++it)->u.operand;
1234             int r1 = (++it)->u.operand;
1235             int offset = (++it)->u.operand;
1236             dataLog("[%4d] loop_if_lesseq\t %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), offset, location + offset);
1237             break;
1238         }
1239         case op_loop_if_greater: {
1240             int r0 = (++it)->u.operand;
1241             int r1 = (++it)->u.operand;
1242             int offset = (++it)->u.operand;
1243             dataLog("[%4d] loop_if_greater\t %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), offset, location + offset);
1244             break;
1245         }
1246         case op_loop_if_greatereq: {
1247             int r0 = (++it)->u.operand;
1248             int r1 = (++it)->u.operand;
1249             int offset = (++it)->u.operand;
1250             dataLog("[%4d] loop_if_greatereq\t %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), offset, location + offset);
1251             break;
1252         }
1253         case op_loop_hint: {
1254             dataLog("[%4d] loop_hint\n", location);
1255             break;
1256         }
1257         case op_switch_imm: {
1258             int tableIndex = (++it)->u.operand;
1259             int defaultTarget = (++it)->u.operand;
1260             int scrutineeRegister = (++it)->u.operand;
1261             dataLog("[%4d] switch_imm\t %d, %d(->%d), %s\n", location, tableIndex, defaultTarget, location + defaultTarget, registerName(exec, scrutineeRegister).data());
1262             break;
1263         }
1264         case op_switch_char: {
1265             int tableIndex = (++it)->u.operand;
1266             int defaultTarget = (++it)->u.operand;
1267             int scrutineeRegister = (++it)->u.operand;
1268             dataLog("[%4d] switch_char\t %d, %d(->%d), %s\n", location, tableIndex, defaultTarget, location + defaultTarget, registerName(exec, scrutineeRegister).data());
1269             break;
1270         }
1271         case op_switch_string: {
1272             int tableIndex = (++it)->u.operand;
1273             int defaultTarget = (++it)->u.operand;
1274             int scrutineeRegister = (++it)->u.operand;
1275             dataLog("[%4d] switch_string\t %d, %d(->%d), %s\n", location, tableIndex, defaultTarget, location + defaultTarget, registerName(exec, scrutineeRegister).data());
1276             break;
1277         }
1278         case op_new_func: {
1279             int r0 = (++it)->u.operand;
1280             int f0 = (++it)->u.operand;
1281             int shouldCheck = (++it)->u.operand;
1282             dataLog("[%4d] new_func\t\t %s, f%d, %s\n", location, registerName(exec, r0).data(), f0, shouldCheck ? "<Checked>" : "<Unchecked>");
1283             break;
1284         }
1285         case op_new_func_exp: {
1286             int r0 = (++it)->u.operand;
1287             int f0 = (++it)->u.operand;
1288             dataLog("[%4d] new_func_exp\t %s, f%d\n", location, registerName(exec, r0).data(), f0);
1289             break;
1290         }
1291         case op_call: {
1292             printCallOp(exec, location, it, "call", DumpCaches);
1293             break;
1294         }
1295         case op_call_eval: {
1296             printCallOp(exec, location, it, "call_eval", DontDumpCaches);
1297             break;
1298         }
1299         case op_call_varargs: {
1300             int callee = (++it)->u.operand;
1301             int thisValue = (++it)->u.operand;
1302             int arguments = (++it)->u.operand;
1303             int firstFreeRegister = (++it)->u.operand;
1304             dataLog("[%4d] call_varargs\t %s, %s, %s, %d\n", location, registerName(exec, callee).data(), registerName(exec, thisValue).data(), registerName(exec, arguments).data(), firstFreeRegister);
1305             break;
1306         }
1307         case op_tear_off_activation: {
1308             int r0 = (++it)->u.operand;
1309             int r1 = (++it)->u.operand;
1310             dataLog("[%4d] tear_off_activation\t %s, %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data());
1311             break;
1312         }
1313         case op_tear_off_arguments: {
1314             int r0 = (++it)->u.operand;
1315             dataLog("[%4d] tear_off_arguments %s\n", location, registerName(exec, r0).data());
1316             break;
1317         }
1318         case op_ret: {
1319             int r0 = (++it)->u.operand;
1320             dataLog("[%4d] ret\t\t %s\n", location, registerName(exec, r0).data());
1321             break;
1322         }
1323         case op_call_put_result: {
1324             int r0 = (++it)->u.operand;
1325             dataLog("[%4d] call_put_result\t\t %s\n", location, registerName(exec, r0).data());
1326             it++;
1327             break;
1328         }
1329         case op_ret_object_or_this: {
1330             int r0 = (++it)->u.operand;
1331             int r1 = (++it)->u.operand;
1332             dataLog("[%4d] constructor_ret\t\t %s %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data());
1333             break;
1334         }
1335         case op_construct: {
1336             printCallOp(exec, location, it, "construct", DumpCaches);
1337             break;
1338         }
1339         case op_strcat: {
1340             int r0 = (++it)->u.operand;
1341             int r1 = (++it)->u.operand;
1342             int count = (++it)->u.operand;
1343             dataLog("[%4d] strcat\t\t %s, %s, %d\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), count);
1344             break;
1345         }
1346         case op_to_primitive: {
1347             int r0 = (++it)->u.operand;
1348             int r1 = (++it)->u.operand;
1349             dataLog("[%4d] to_primitive\t %s, %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data());
1350             break;
1351         }
1352         case op_get_pnames: {
1353             int r0 = it[1].u.operand;
1354             int r1 = it[2].u.operand;
1355             int r2 = it[3].u.operand;
1356             int r3 = it[4].u.operand;
1357             int offset = it[5].u.operand;
1358             dataLog("[%4d] get_pnames\t %s, %s, %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), registerName(exec, r2).data(), registerName(exec, r3).data(), offset, location + offset);
1359             it += OPCODE_LENGTH(op_get_pnames) - 1;
1360             break;
1361         }
1362         case op_next_pname: {
1363             int dest = it[1].u.operand;
1364             int base = it[2].u.operand;
1365             int i = it[3].u.operand;
1366             int size = it[4].u.operand;
1367             int iter = it[5].u.operand;
1368             int offset = it[6].u.operand;
1369             dataLog("[%4d] next_pname\t %s, %s, %s, %s, %s, %d(->%d)\n", location, registerName(exec, dest).data(), registerName(exec, base).data(), registerName(exec, i).data(), registerName(exec, size).data(), registerName(exec, iter).data(), offset, location + offset);
1370             it += OPCODE_LENGTH(op_next_pname) - 1;
1371             break;
1372         }
1373         case op_push_scope: {
1374             int r0 = (++it)->u.operand;
1375             dataLog("[%4d] push_scope\t %s\n", location, registerName(exec, r0).data());
1376             break;
1377         }
1378         case op_pop_scope: {
1379             dataLog("[%4d] pop_scope\n", location);
1380             break;
1381         }
1382         case op_push_new_scope: {
1383             int r0 = (++it)->u.operand;
1384             int id0 = (++it)->u.operand;
1385             int r1 = (++it)->u.operand;
1386             dataLog("[%4d] push_new_scope \t%s, %s, %s\n", location, registerName(exec, r0).data(), idName(id0, m_identifiers[id0]).data(), registerName(exec, r1).data());
1387             break;
1388         }
1389         case op_jmp_scopes: {
1390             int scopeDelta = (++it)->u.operand;
1391             int offset = (++it)->u.operand;
1392             dataLog("[%4d] jmp_scopes\t^%d, %d(->%d)\n", location, scopeDelta, offset, location + offset);
1393             break;
1394         }
1395         case op_catch: {
1396             int r0 = (++it)->u.operand;
1397             dataLog("[%4d] catch\t\t %s\n", location, registerName(exec, r0).data());
1398             break;
1399         }
1400         case op_throw: {
1401             int r0 = (++it)->u.operand;
1402             dataLog("[%4d] throw\t\t %s\n", location, registerName(exec, r0).data());
1403             break;
1404         }
1405         case op_throw_reference_error: {
1406             int k0 = (++it)->u.operand;
1407             dataLog("[%4d] throw_reference_error\t %s\n", location, constantName(exec, k0, getConstant(k0)).data());
1408             break;
1409         }
1410         case op_debug: {
1411             int debugHookID = (++it)->u.operand;
1412             int firstLine = (++it)->u.operand;
1413             int lastLine = (++it)->u.operand;
1414             dataLog("[%4d] debug\t\t %s, %d, %d\n", location, debugHookName(debugHookID), firstLine, lastLine);
1415             break;
1416         }
1417         case op_profile_will_call: {
1418             int function = (++it)->u.operand;
1419             dataLog("[%4d] profile_will_call %s\n", location, registerName(exec, function).data());
1420             break;
1421         }
1422         case op_profile_did_call: {
1423             int function = (++it)->u.operand;
1424             dataLog("[%4d] profile_did_call\t %s\n", location, registerName(exec, function).data());
1425             break;
1426         }
1427         case op_end: {
1428             int r0 = (++it)->u.operand;
1429             dataLog("[%4d] end\t\t %s\n", location, registerName(exec, r0).data());
1430             break;
1431         }
1432     }
1433 }
1434
1435 #if DUMP_CODE_BLOCK_STATISTICS
1436 static HashSet<CodeBlock*> liveCodeBlockSet;
1437 #endif
1438
1439 #define FOR_EACH_MEMBER_VECTOR(macro) \
1440     macro(instructions) \
1441     macro(globalResolveInfos) \
1442     macro(structureStubInfos) \
1443     macro(callLinkInfos) \
1444     macro(linkedCallerList) \
1445     macro(identifiers) \
1446     macro(functionExpressions) \
1447     macro(constantRegisters)
1448
1449 #define FOR_EACH_MEMBER_VECTOR_RARE_DATA(macro) \
1450     macro(regexps) \
1451     macro(functions) \
1452     macro(exceptionHandlers) \
1453     macro(immediateSwitchJumpTables) \
1454     macro(characterSwitchJumpTables) \
1455     macro(stringSwitchJumpTables) \
1456     macro(evalCodeCache) \
1457     macro(expressionInfo) \
1458     macro(lineInfo) \
1459     macro(callReturnIndexVector)
1460
1461 template<typename T>
1462 static size_t sizeInBytes(const Vector<T>& vector)
1463 {
1464     return vector.capacity() * sizeof(T);
1465 }
1466
1467 void CodeBlock::dumpStatistics()
1468 {
1469 #if DUMP_CODE_BLOCK_STATISTICS
1470     #define DEFINE_VARS(name) size_t name##IsNotEmpty = 0; size_t name##TotalSize = 0;
1471         FOR_EACH_MEMBER_VECTOR(DEFINE_VARS)
1472         FOR_EACH_MEMBER_VECTOR_RARE_DATA(DEFINE_VARS)
1473     #undef DEFINE_VARS
1474
1475     // Non-vector data members
1476     size_t evalCodeCacheIsNotEmpty = 0;
1477
1478     size_t symbolTableIsNotEmpty = 0;
1479     size_t symbolTableTotalSize = 0;
1480
1481     size_t hasRareData = 0;
1482
1483     size_t isFunctionCode = 0;
1484     size_t isGlobalCode = 0;
1485     size_t isEvalCode = 0;
1486
1487     HashSet<CodeBlock*>::const_iterator end = liveCodeBlockSet.end();
1488     for (HashSet<CodeBlock*>::const_iterator it = liveCodeBlockSet.begin(); it != end; ++it) {
1489         CodeBlock* codeBlock = *it;
1490
1491         #define GET_STATS(name) if (!codeBlock->m_##name.isEmpty()) { name##IsNotEmpty++; name##TotalSize += sizeInBytes(codeBlock->m_##name); }
1492             FOR_EACH_MEMBER_VECTOR(GET_STATS)
1493         #undef GET_STATS
1494
1495         if (!codeBlock->m_symbolTable.isEmpty()) {
1496             symbolTableIsNotEmpty++;
1497             symbolTableTotalSize += (codeBlock->m_symbolTable.capacity() * (sizeof(SymbolTable::KeyType) + sizeof(SymbolTable::MappedType)));
1498         }
1499
1500         if (codeBlock->m_rareData) {
1501             hasRareData++;
1502             #define GET_STATS(name) if (!codeBlock->m_rareData->m_##name.isEmpty()) { name##IsNotEmpty++; name##TotalSize += sizeInBytes(codeBlock->m_rareData->m_##name); }
1503                 FOR_EACH_MEMBER_VECTOR_RARE_DATA(GET_STATS)
1504             #undef GET_STATS
1505
1506             if (!codeBlock->m_rareData->m_evalCodeCache.isEmpty())
1507                 evalCodeCacheIsNotEmpty++;
1508         }
1509
1510         switch (codeBlock->codeType()) {
1511             case FunctionCode:
1512                 ++isFunctionCode;
1513                 break;
1514             case GlobalCode:
1515                 ++isGlobalCode;
1516                 break;
1517             case EvalCode:
1518                 ++isEvalCode;
1519                 break;
1520         }
1521     }
1522
1523     size_t totalSize = 0;
1524
1525     #define GET_TOTAL_SIZE(name) totalSize += name##TotalSize;
1526         FOR_EACH_MEMBER_VECTOR(GET_TOTAL_SIZE)
1527         FOR_EACH_MEMBER_VECTOR_RARE_DATA(GET_TOTAL_SIZE)
1528     #undef GET_TOTAL_SIZE
1529
1530     totalSize += symbolTableTotalSize;
1531     totalSize += (liveCodeBlockSet.size() * sizeof(CodeBlock));
1532
1533     dataLog("Number of live CodeBlocks: %d\n", liveCodeBlockSet.size());
1534     dataLog("Size of a single CodeBlock [sizeof(CodeBlock)]: %zu\n", sizeof(CodeBlock));
1535     dataLog("Size of all CodeBlocks: %zu\n", totalSize);
1536     dataLog("Average size of a CodeBlock: %zu\n", totalSize / liveCodeBlockSet.size());
1537
1538     dataLog("Number of FunctionCode CodeBlocks: %zu (%.3f%%)\n", isFunctionCode, static_cast<double>(isFunctionCode) * 100.0 / liveCodeBlockSet.size());
1539     dataLog("Number of GlobalCode CodeBlocks: %zu (%.3f%%)\n", isGlobalCode, static_cast<double>(isGlobalCode) * 100.0 / liveCodeBlockSet.size());
1540     dataLog("Number of EvalCode CodeBlocks: %zu (%.3f%%)\n", isEvalCode, static_cast<double>(isEvalCode) * 100.0 / liveCodeBlockSet.size());
1541
1542     dataLog("Number of CodeBlocks with rare data: %zu (%.3f%%)\n", hasRareData, static_cast<double>(hasRareData) * 100.0 / liveCodeBlockSet.size());
1543
1544     #define PRINT_STATS(name) dataLog("Number of CodeBlocks with " #name ": %zu\n", name##IsNotEmpty); dataLog("Size of all " #name ": %zu\n", name##TotalSize); 
1545         FOR_EACH_MEMBER_VECTOR(PRINT_STATS)
1546         FOR_EACH_MEMBER_VECTOR_RARE_DATA(PRINT_STATS)
1547     #undef PRINT_STATS
1548
1549     dataLog("Number of CodeBlocks with evalCodeCache: %zu\n", evalCodeCacheIsNotEmpty);
1550     dataLog("Number of CodeBlocks with symbolTable: %zu\n", symbolTableIsNotEmpty);
1551
1552     dataLog("Size of all symbolTables: %zu\n", symbolTableTotalSize);
1553
1554 #else
1555     dataLog("Dumping CodeBlock statistics is not enabled.\n");
1556 #endif
1557 }
1558
1559 CodeBlock::CodeBlock(CopyParsedBlockTag, CodeBlock& other, SymbolTable* symTab)
1560     : m_globalObject(other.m_globalObject)
1561     , m_heap(other.m_heap)
1562     , m_numCalleeRegisters(other.m_numCalleeRegisters)
1563     , m_numVars(other.m_numVars)
1564     , m_numCapturedVars(other.m_numCapturedVars)
1565     , m_isConstructor(other.m_isConstructor)
1566     , m_ownerExecutable(*other.m_globalData, other.m_ownerExecutable.get(), other.m_ownerExecutable.get())
1567     , m_globalData(other.m_globalData)
1568     , m_instructions(other.m_instructions)
1569     , m_thisRegister(other.m_thisRegister)
1570     , m_argumentsRegister(other.m_argumentsRegister)
1571     , m_activationRegister(other.m_activationRegister)
1572     , m_needsFullScopeChain(other.m_needsFullScopeChain)
1573     , m_usesEval(other.m_usesEval)
1574     , m_isNumericCompareFunction(other.m_isNumericCompareFunction)
1575     , m_isStrictMode(other.m_isStrictMode)
1576     , m_codeType(other.m_codeType)
1577     , m_source(other.m_source)
1578     , m_sourceOffset(other.m_sourceOffset)
1579 #if ENABLE(JIT)
1580     , m_globalResolveInfos(other.m_globalResolveInfos)
1581 #endif
1582 #if ENABLE(VALUE_PROFILER)
1583     , m_executionEntryCount(0)
1584 #endif
1585     , m_jumpTargets(other.m_jumpTargets)
1586     , m_loopTargets(other.m_loopTargets)
1587     , m_identifiers(other.m_identifiers)
1588     , m_constantRegisters(other.m_constantRegisters)
1589     , m_functionDecls(other.m_functionDecls)
1590     , m_functionExprs(other.m_functionExprs)
1591     , m_symbolTable(symTab)
1592     , m_speculativeSuccessCounter(0)
1593     , m_speculativeFailCounter(0)
1594     , m_forcedOSRExitCounter(0)
1595     , m_optimizationDelayCounter(0)
1596     , m_reoptimizationRetryCounter(0)
1597 #if ENABLE(JIT)
1598     , m_canCompileWithDFGState(DFG::CapabilityLevelNotSet)
1599 #endif
1600 {
1601     setNumParameters(other.numParameters());
1602     optimizeAfterWarmUp();
1603     jitAfterWarmUp();
1604     
1605     if (other.m_rareData) {
1606         createRareDataIfNecessary();
1607         
1608         m_rareData->m_exceptionHandlers = other.m_rareData->m_exceptionHandlers;
1609         m_rareData->m_regexps = other.m_rareData->m_regexps;
1610         m_rareData->m_constantBuffers = other.m_rareData->m_constantBuffers;
1611         m_rareData->m_immediateSwitchJumpTables = other.m_rareData->m_immediateSwitchJumpTables;
1612         m_rareData->m_characterSwitchJumpTables = other.m_rareData->m_characterSwitchJumpTables;
1613         m_rareData->m_stringSwitchJumpTables = other.m_rareData->m_stringSwitchJumpTables;
1614         m_rareData->m_expressionInfo = other.m_rareData->m_expressionInfo;
1615         m_rareData->m_lineInfo = other.m_rareData->m_lineInfo;
1616     }
1617 }
1618
1619 CodeBlock::CodeBlock(ScriptExecutable* ownerExecutable, CodeType codeType, JSGlobalObject *globalObject, PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset, SymbolTable* symTab, bool isConstructor, PassOwnPtr<CodeBlock> alternative)
1620     : m_globalObject(globalObject->globalData(), ownerExecutable, globalObject)
1621     , m_heap(&m_globalObject->globalData().heap)
1622     , m_numCalleeRegisters(0)
1623     , m_numVars(0)
1624     , m_isConstructor(isConstructor)
1625     , m_numParameters(0)
1626     , m_ownerExecutable(globalObject->globalData(), ownerExecutable, ownerExecutable)
1627     , m_globalData(0)
1628     , m_argumentsRegister(-1)
1629     , m_needsFullScopeChain(ownerExecutable->needsActivation())
1630     , m_usesEval(ownerExecutable->usesEval())
1631     , m_isNumericCompareFunction(false)
1632     , m_isStrictMode(ownerExecutable->isStrictMode())
1633     , m_codeType(codeType)
1634     , m_source(sourceProvider)
1635     , m_sourceOffset(sourceOffset)
1636 #if ENABLE(VALUE_PROFILER)
1637     , m_executionEntryCount(0)
1638 #endif
1639     , m_symbolTable(symTab)
1640     , m_alternative(alternative)
1641     , m_speculativeSuccessCounter(0)
1642     , m_speculativeFailCounter(0)
1643     , m_optimizationDelayCounter(0)
1644     , m_reoptimizationRetryCounter(0)
1645 {
1646     ASSERT(m_source);
1647     
1648     optimizeAfterWarmUp();
1649     jitAfterWarmUp();
1650
1651 #if DUMP_CODE_BLOCK_STATISTICS
1652     liveCodeBlockSet.add(this);
1653 #endif
1654 }
1655
1656 CodeBlock::~CodeBlock()
1657 {
1658 #if ENABLE(DFG_JIT)
1659     // Remove myself from the set of DFG code blocks. Note that I may not be in this set
1660     // (because I'm not a DFG code block), in which case this is a no-op anyway.
1661     m_globalData->heap.m_dfgCodeBlocks.m_set.remove(this);
1662 #endif
1663     
1664 #if ENABLE(VERBOSE_VALUE_PROFILE)
1665     dumpValueProfiles();
1666 #endif
1667
1668 #if ENABLE(LLINT)    
1669     while (m_incomingLLIntCalls.begin() != m_incomingLLIntCalls.end())
1670         m_incomingLLIntCalls.begin()->remove();
1671 #endif // ENABLE(LLINT)
1672 #if ENABLE(JIT)
1673     // We may be destroyed before any CodeBlocks that refer to us are destroyed.
1674     // Consider that two CodeBlocks become unreachable at the same time. There
1675     // is no guarantee about the order in which the CodeBlocks are destroyed.
1676     // So, if we don't remove incoming calls, and get destroyed before the
1677     // CodeBlock(s) that have calls into us, then the CallLinkInfo vector's
1678     // destructor will try to remove nodes from our (no longer valid) linked list.
1679     while (m_incomingCalls.begin() != m_incomingCalls.end())
1680         m_incomingCalls.begin()->remove();
1681     
1682     // Note that our outgoing calls will be removed from other CodeBlocks'
1683     // m_incomingCalls linked lists through the execution of the ~CallLinkInfo
1684     // destructors.
1685
1686     for (size_t size = m_structureStubInfos.size(), i = 0; i < size; ++i)
1687         m_structureStubInfos[i].deref();
1688 #endif // ENABLE(JIT)
1689
1690 #if DUMP_CODE_BLOCK_STATISTICS
1691     liveCodeBlockSet.remove(this);
1692 #endif
1693 }
1694
1695 void CodeBlock::setNumParameters(int newValue)
1696 {
1697     m_numParameters = newValue;
1698
1699 #if ENABLE(VALUE_PROFILER)
1700     m_argumentValueProfiles.resize(newValue);
1701 #endif
1702 }
1703
1704 void CodeBlock::addParameter()
1705 {
1706     m_numParameters++;
1707
1708 #if ENABLE(VALUE_PROFILER)
1709     m_argumentValueProfiles.append(ValueProfile());
1710 #endif
1711 }
1712
1713 void CodeBlock::visitStructures(SlotVisitor& visitor, Instruction* vPC)
1714 {
1715     Interpreter* interpreter = m_globalData->interpreter;
1716
1717     if (vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id) && vPC[4].u.structure) {
1718         visitor.append(&vPC[4].u.structure);
1719         return;
1720     }
1721
1722     if (vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_self) || vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_getter_self) || vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_custom_self)) {
1723         visitor.append(&vPC[4].u.structure);
1724         return;
1725     }
1726     if (vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_proto) || vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_getter_proto) || vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_custom_proto)) {
1727         visitor.append(&vPC[4].u.structure);
1728         visitor.append(&vPC[5].u.structure);
1729         return;
1730     }
1731     if (vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_chain) || vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_getter_chain) || vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_custom_chain)) {
1732         visitor.append(&vPC[4].u.structure);
1733         if (vPC[5].u.structureChain)
1734             visitor.append(&vPC[5].u.structureChain);
1735         return;
1736     }
1737     if (vPC[0].u.opcode == interpreter->getOpcode(op_put_by_id_transition)) {
1738         visitor.append(&vPC[4].u.structure);
1739         visitor.append(&vPC[5].u.structure);
1740         if (vPC[6].u.structureChain)
1741             visitor.append(&vPC[6].u.structureChain);
1742         return;
1743     }
1744     if (vPC[0].u.opcode == interpreter->getOpcode(op_put_by_id) && vPC[4].u.structure) {
1745         visitor.append(&vPC[4].u.structure);
1746         return;
1747     }
1748     if (vPC[0].u.opcode == interpreter->getOpcode(op_put_by_id_replace)) {
1749         visitor.append(&vPC[4].u.structure);
1750         return;
1751     }
1752     if (vPC[0].u.opcode == interpreter->getOpcode(op_resolve_global) || vPC[0].u.opcode == interpreter->getOpcode(op_resolve_global_dynamic)) {
1753         if (vPC[3].u.structure)
1754             visitor.append(&vPC[3].u.structure);
1755         return;
1756     }
1757
1758     // These instructions don't ref their Structures.
1759     ASSERT(vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id) || vPC[0].u.opcode == interpreter->getOpcode(op_put_by_id) || vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_generic) || vPC[0].u.opcode == interpreter->getOpcode(op_put_by_id_generic) || vPC[0].u.opcode == interpreter->getOpcode(op_get_array_length) || vPC[0].u.opcode == interpreter->getOpcode(op_get_string_length));
1760 }
1761
1762 void EvalCodeCache::visitAggregate(SlotVisitor& visitor)
1763 {
1764     EvalCacheMap::iterator end = m_cacheMap.end();
1765     for (EvalCacheMap::iterator ptr = m_cacheMap.begin(); ptr != end; ++ptr)
1766         visitor.append(&ptr->second);
1767 }
1768
1769 void CodeBlock::visitAggregate(SlotVisitor& visitor)
1770 {
1771 #if ENABLE(PARALLEL_GC) && ENABLE(DFG_JIT)
1772     if (!!m_dfgData) {
1773         // I may be asked to scan myself more than once, and it may even happen concurrently.
1774         // To this end, use a CAS loop to check if I've been called already. Only one thread
1775         // may proceed past this point - whichever one wins the CAS race.
1776         unsigned oldValue;
1777         do {
1778             oldValue = m_dfgData->visitAggregateHasBeenCalled;
1779             if (oldValue) {
1780                 // Looks like someone else won! Return immediately to ensure that we don't
1781                 // trace the same CodeBlock concurrently. Doing so is hazardous since we will
1782                 // be mutating the state of ValueProfiles, which contain JSValues, which can
1783                 // have word-tearing on 32-bit, leading to awesome timing-dependent crashes
1784                 // that are nearly impossible to track down.
1785                 
1786                 // Also note that it must be safe to return early as soon as we see the
1787                 // value true (well, (unsigned)1), since once a GC thread is in this method
1788                 // and has won the CAS race (i.e. was responsible for setting the value true)
1789                 // it will definitely complete the rest of this method before declaring
1790                 // termination.
1791                 return;
1792             }
1793         } while (!WTF::weakCompareAndSwap(&m_dfgData->visitAggregateHasBeenCalled, 0, 1));
1794     }
1795 #endif // ENABLE(PARALLEL_GC) && ENABLE(DFG_JIT)
1796     
1797     if (!!m_alternative)
1798         m_alternative->visitAggregate(visitor);
1799
1800     // There are three things that may use unconditional finalizers: lazy bytecode freeing,
1801     // inline cache clearing, and jettisoning. The probability of us wanting to do at
1802     // least one of those things is probably quite close to 1. So we add one no matter what
1803     // and when it runs, it figures out whether it has any work to do.
1804     visitor.addUnconditionalFinalizer(this);
1805     
1806     if (shouldImmediatelyAssumeLivenessDuringScan()) {
1807         // This code block is live, so scan all references strongly and return.
1808         stronglyVisitStrongReferences(visitor);
1809         stronglyVisitWeakReferences(visitor);
1810         return;
1811     }
1812     
1813 #if ENABLE(DFG_JIT)
1814     // We get here if we're live in the sense that our owner executable is live,
1815     // but we're not yet live for sure in another sense: we may yet decide that this
1816     // code block should be jettisoned based on its outgoing weak references being
1817     // stale. Set a flag to indicate that we're still assuming that we're dead, and
1818     // perform one round of determining if we're live. The GC may determine, based on
1819     // either us marking additional objects, or by other objects being marked for
1820     // other reasons, that this iteration should run again; it will notify us of this
1821     // decision by calling harvestWeakReferences().
1822     
1823     m_dfgData->livenessHasBeenProved = false;
1824     m_dfgData->allTransitionsHaveBeenMarked = false;
1825     
1826     performTracingFixpointIteration(visitor);
1827
1828     // GC doesn't have enough information yet for us to decide whether to keep our DFG
1829     // data, so we need to register a handler to run again at the end of GC, when more
1830     // information is available.
1831     if (!(m_dfgData->livenessHasBeenProved && m_dfgData->allTransitionsHaveBeenMarked))
1832         visitor.addWeakReferenceHarvester(this);
1833     
1834 #else // ENABLE(DFG_JIT)
1835     ASSERT_NOT_REACHED();
1836 #endif // ENABLE(DFG_JIT)
1837 }
1838
1839 void CodeBlock::performTracingFixpointIteration(SlotVisitor& visitor)
1840 {
1841     UNUSED_PARAM(visitor);
1842     
1843 #if ENABLE(DFG_JIT)
1844     // Evaluate our weak reference transitions, if there are still some to evaluate.
1845     if (!m_dfgData->allTransitionsHaveBeenMarked) {
1846         bool allAreMarkedSoFar = true;
1847         for (unsigned i = 0; i < m_dfgData->transitions.size(); ++i) {
1848             if ((!m_dfgData->transitions[i].m_codeOrigin
1849                  || Heap::isMarked(m_dfgData->transitions[i].m_codeOrigin.get()))
1850                 && Heap::isMarked(m_dfgData->transitions[i].m_from.get())) {
1851                 // If the following three things are live, then the target of the
1852                 // transition is also live:
1853                 // - This code block. We know it's live already because otherwise
1854                 //   we wouldn't be scanning ourselves.
1855                 // - The code origin of the transition. Transitions may arise from
1856                 //   code that was inlined. They are not relevant if the user's
1857                 //   object that is required for the inlinee to run is no longer
1858                 //   live.
1859                 // - The source of the transition. The transition checks if some
1860                 //   heap location holds the source, and if so, stores the target.
1861                 //   Hence the source must be live for the transition to be live.
1862                 visitor.append(&m_dfgData->transitions[i].m_to);
1863             } else
1864                 allAreMarkedSoFar = false;
1865         }
1866         
1867         if (allAreMarkedSoFar)
1868             m_dfgData->allTransitionsHaveBeenMarked = true;
1869     }
1870     
1871     // Check if we have any remaining work to do.
1872     if (m_dfgData->livenessHasBeenProved)
1873         return;
1874     
1875     // Now check all of our weak references. If all of them are live, then we
1876     // have proved liveness and so we scan our strong references. If at end of
1877     // GC we still have not proved liveness, then this code block is toast.
1878     bool allAreLiveSoFar = true;
1879     for (unsigned i = 0; i < m_dfgData->weakReferences.size(); ++i) {
1880         if (!Heap::isMarked(m_dfgData->weakReferences[i].get())) {
1881             allAreLiveSoFar = false;
1882             break;
1883         }
1884     }
1885     
1886     // If some weak references are dead, then this fixpoint iteration was
1887     // unsuccessful.
1888     if (!allAreLiveSoFar)
1889         return;
1890     
1891     // All weak references are live. Record this information so we don't
1892     // come back here again, and scan the strong references.
1893     m_dfgData->livenessHasBeenProved = true;
1894     stronglyVisitStrongReferences(visitor);
1895 #endif // ENABLE(DFG_JIT)
1896 }
1897
1898 void CodeBlock::visitWeakReferences(SlotVisitor& visitor)
1899 {
1900     performTracingFixpointIteration(visitor);
1901 }
1902
1903 void CodeBlock::finalizeUnconditionally()
1904 {
1905 #if ENABLE(JIT)
1906 #if ENABLE(JIT_VERBOSE_OSR)
1907     static const bool verboseUnlinking = true;
1908 #else
1909     static const bool verboseUnlinking = false;
1910 #endif
1911 #endif // ENABLE(JIT)
1912     
1913 #if ENABLE(LLINT)
1914     Interpreter* interpreter = m_globalData->interpreter;
1915     // interpreter->classicEnabled() returns true if the old C++ interpreter is enabled. If that's enabled
1916     // then we're not using LLInt.
1917     if (!interpreter->classicEnabled() && !!numberOfInstructions()) {
1918         for (size_t size = m_propertyAccessInstructions.size(), i = 0; i < size; ++i) {
1919             Instruction* curInstruction = &instructions()[m_propertyAccessInstructions[i]];
1920             switch (interpreter->getOpcodeID(curInstruction[0].u.opcode)) {
1921             case op_get_by_id:
1922             case op_put_by_id:
1923                 if (!curInstruction[4].u.structure || Heap::isMarked(curInstruction[4].u.structure.get()))
1924                     break;
1925                 if (verboseUnlinking)
1926                     dataLog("Clearing LLInt property access with structure %p.\n", curInstruction[4].u.structure.get());
1927                 curInstruction[4].u.structure.clear();
1928                 curInstruction[5].u.operand = 0;
1929                 break;
1930             case op_put_by_id_transition_direct:
1931             case op_put_by_id_transition_normal:
1932                 if (Heap::isMarked(curInstruction[4].u.structure.get())
1933                     && Heap::isMarked(curInstruction[6].u.structure.get())
1934                     && Heap::isMarked(curInstruction[7].u.structureChain.get()))
1935                     break;
1936                 if (verboseUnlinking) {
1937                     dataLog("Clearing LLInt put transition with structures %p -> %p, chain %p.\n",
1938                             curInstruction[4].u.structure.get(),
1939                             curInstruction[6].u.structure.get(),
1940                             curInstruction[7].u.structureChain.get());
1941                 }
1942                 curInstruction[4].u.structure.clear();
1943                 curInstruction[6].u.structure.clear();
1944                 curInstruction[7].u.structureChain.clear();
1945                 curInstruction[0].u.opcode = interpreter->getOpcode(op_put_by_id);
1946                 break;
1947             default:
1948                 ASSERT_NOT_REACHED();
1949             }
1950         }
1951         for (size_t size = m_globalResolveInstructions.size(), i = 0; i < size; ++i) {
1952             Instruction* curInstruction = &instructions()[m_globalResolveInstructions[i]];
1953             ASSERT(interpreter->getOpcodeID(curInstruction[0].u.opcode) == op_resolve_global
1954                    || interpreter->getOpcodeID(curInstruction[0].u.opcode) == op_resolve_global_dynamic);
1955             if (!curInstruction[3].u.structure || Heap::isMarked(curInstruction[3].u.structure.get()))
1956                 continue;
1957             if (verboseUnlinking)
1958                 dataLog("Clearing LLInt global resolve cache with structure %p.\n", curInstruction[3].u.structure.get());
1959             curInstruction[3].u.structure.clear();
1960             curInstruction[4].u.operand = 0;
1961         }
1962         for (unsigned i = 0; i < m_llintCallLinkInfos.size(); ++i) {
1963             if (m_llintCallLinkInfos[i].isLinked() && !Heap::isMarked(m_llintCallLinkInfos[i].callee.get())) {
1964                 if (verboseUnlinking)
1965                     dataLog("Clearing LLInt call from %p.\n", this);
1966                 m_llintCallLinkInfos[i].unlink();
1967             }
1968             if (!!m_llintCallLinkInfos[i].lastSeenCallee && !Heap::isMarked(m_llintCallLinkInfos[i].lastSeenCallee.get()))
1969                 m_llintCallLinkInfos[i].lastSeenCallee.clear();
1970         }
1971     }
1972 #endif // ENABLE(LLINT)
1973
1974 #if ENABLE(DFG_JIT)
1975     // Check if we're not live. If we are, then jettison.
1976     if (!(shouldImmediatelyAssumeLivenessDuringScan() || m_dfgData->livenessHasBeenProved)) {
1977         if (verboseUnlinking)
1978             dataLog("Code block %p has dead weak references, jettisoning during GC.\n", this);
1979
1980         // Make sure that the baseline JIT knows that it should re-warm-up before
1981         // optimizing.
1982         alternative()->optimizeAfterWarmUp();
1983         
1984         jettison();
1985         return;
1986     }
1987 #endif // ENABLE(DFG_JIT)
1988     
1989 #if ENABLE(JIT)
1990     // Handle inline caches.
1991     if (!!getJITCode()) {
1992         RepatchBuffer repatchBuffer(this);
1993         for (unsigned i = 0; i < numberOfCallLinkInfos(); ++i) {
1994             if (callLinkInfo(i).isLinked() && !Heap::isMarked(callLinkInfo(i).callee.get())) {
1995                 if (verboseUnlinking)
1996                     dataLog("Clearing call from %p to %p.\n", this, callLinkInfo(i).callee.get());
1997                 callLinkInfo(i).unlink(*m_globalData, repatchBuffer);
1998             }
1999             if (!!callLinkInfo(i).lastSeenCallee
2000                 && !Heap::isMarked(callLinkInfo(i).lastSeenCallee.get()))
2001                 callLinkInfo(i).lastSeenCallee.clear();
2002         }
2003         for (size_t size = m_globalResolveInfos.size(), i = 0; i < size; ++i) {
2004             if (m_globalResolveInfos[i].structure && !Heap::isMarked(m_globalResolveInfos[i].structure.get())) {
2005                 if (verboseUnlinking)
2006                     dataLog("Clearing resolve info in %p.\n", this);
2007                 m_globalResolveInfos[i].structure.clear();
2008             }
2009         }
2010
2011         for (size_t size = m_structureStubInfos.size(), i = 0; i < size; ++i) {
2012             StructureStubInfo& stubInfo = m_structureStubInfos[i];
2013             
2014             AccessType accessType = static_cast<AccessType>(stubInfo.accessType);
2015             
2016             if (stubInfo.visitWeakReferences())
2017                 continue;
2018             
2019             if (verboseUnlinking)
2020                 dataLog("Clearing structure cache (kind %d) in %p.\n", stubInfo.accessType, this);
2021             
2022             if (isGetByIdAccess(accessType)) {
2023                 if (getJITCode().jitType() == JITCode::DFGJIT)
2024                     DFG::dfgResetGetByID(repatchBuffer, stubInfo);
2025                 else
2026                     JIT::resetPatchGetById(repatchBuffer, &stubInfo);
2027             } else {
2028                 ASSERT(isPutByIdAccess(accessType));
2029                 if (getJITCode().jitType() == JITCode::DFGJIT)
2030                     DFG::dfgResetPutByID(repatchBuffer, stubInfo);
2031                 else 
2032                     JIT::resetPatchPutById(repatchBuffer, &stubInfo);
2033             }
2034             
2035             stubInfo.reset();
2036         }
2037
2038         for (size_t size = m_methodCallLinkInfos.size(), i = 0; i < size; ++i) {
2039             if (!m_methodCallLinkInfos[i].cachedStructure)
2040                 continue;
2041             
2042             ASSERT(m_methodCallLinkInfos[i].seenOnce());
2043             ASSERT(!!m_methodCallLinkInfos[i].cachedPrototypeStructure);
2044
2045             if (!Heap::isMarked(m_methodCallLinkInfos[i].cachedStructure.get())
2046                 || !Heap::isMarked(m_methodCallLinkInfos[i].cachedPrototypeStructure.get())
2047                 || !Heap::isMarked(m_methodCallLinkInfos[i].cachedFunction.get())
2048                 || !Heap::isMarked(m_methodCallLinkInfos[i].cachedPrototype.get())) {
2049                 if (verboseUnlinking)
2050                     dataLog("Clearing method call in %p.\n", this);
2051                 m_methodCallLinkInfos[i].reset(repatchBuffer, getJITType());
2052
2053                 StructureStubInfo& stubInfo = getStubInfo(m_methodCallLinkInfos[i].bytecodeIndex);
2054
2055                 AccessType accessType = static_cast<AccessType>(stubInfo.accessType);
2056
2057                 if (accessType != access_unset) {
2058                     ASSERT(isGetByIdAccess(accessType));
2059                     if (getJITCode().jitType() == JITCode::DFGJIT)
2060                         DFG::dfgResetGetByID(repatchBuffer, stubInfo);
2061                     else
2062                         JIT::resetPatchGetById(repatchBuffer, &stubInfo);
2063                     stubInfo.reset();
2064                 }
2065             }
2066         }
2067     }
2068 #endif
2069 }
2070
2071 void CodeBlock::stronglyVisitStrongReferences(SlotVisitor& visitor)
2072 {
2073     visitor.append(&m_globalObject);
2074     visitor.append(&m_ownerExecutable);
2075     if (m_rareData) {
2076         m_rareData->m_evalCodeCache.visitAggregate(visitor);
2077         size_t regExpCount = m_rareData->m_regexps.size();
2078         WriteBarrier<RegExp>* regexps = m_rareData->m_regexps.data();
2079         for (size_t i = 0; i < regExpCount; i++)
2080             visitor.append(regexps + i);
2081     }
2082     visitor.appendValues(m_constantRegisters.data(), m_constantRegisters.size());
2083     for (size_t i = 0; i < m_functionExprs.size(); ++i)
2084         visitor.append(&m_functionExprs[i]);
2085     for (size_t i = 0; i < m_functionDecls.size(); ++i)
2086         visitor.append(&m_functionDecls[i]);
2087 #if ENABLE(CLASSIC_INTERPRETER)
2088     if (m_globalData->interpreter->classicEnabled() && !!numberOfInstructions()) {
2089         for (size_t size = m_propertyAccessInstructions.size(), i = 0; i < size; ++i)
2090             visitStructures(visitor, &instructions()[m_propertyAccessInstructions[i]]);
2091         for (size_t size = m_globalResolveInstructions.size(), i = 0; i < size; ++i)
2092             visitStructures(visitor, &instructions()[m_globalResolveInstructions[i]]);
2093     }
2094 #endif
2095
2096 #if ENABLE(DFG_JIT)
2097     if (hasCodeOrigins()) {
2098         // Make sure that executables that we have inlined don't die.
2099         // FIXME: If they would have otherwise died, we should probably trigger recompilation.
2100         for (size_t i = 0; i < inlineCallFrames().size(); ++i) {
2101             InlineCallFrame& inlineCallFrame = inlineCallFrames()[i];
2102             visitor.append(&inlineCallFrame.executable);
2103             visitor.append(&inlineCallFrame.callee);
2104         }
2105     }
2106     
2107     m_lazyOperandValueProfiles.computeUpdatedPredictions(Collection);
2108 #endif
2109
2110 #if ENABLE(VALUE_PROFILER)
2111     for (unsigned profileIndex = 0; profileIndex < numberOfArgumentValueProfiles(); ++profileIndex)
2112         valueProfileForArgument(profileIndex)->computeUpdatedPrediction(Collection);
2113     for (unsigned profileIndex = 0; profileIndex < numberOfValueProfiles(); ++profileIndex)
2114         valueProfile(profileIndex)->computeUpdatedPrediction(Collection);
2115 #endif
2116 }
2117
2118 void CodeBlock::stronglyVisitWeakReferences(SlotVisitor& visitor)
2119 {
2120     UNUSED_PARAM(visitor);
2121
2122 #if ENABLE(DFG_JIT)
2123     if (!m_dfgData)
2124         return;
2125
2126     for (unsigned i = 0; i < m_dfgData->transitions.size(); ++i) {
2127         if (!!m_dfgData->transitions[i].m_codeOrigin)
2128             visitor.append(&m_dfgData->transitions[i].m_codeOrigin); // Almost certainly not necessary, since the code origin should also be a weak reference. Better to be safe, though.
2129         visitor.append(&m_dfgData->transitions[i].m_from);
2130         visitor.append(&m_dfgData->transitions[i].m_to);
2131     }
2132     
2133     for (unsigned i = 0; i < m_dfgData->weakReferences.size(); ++i)
2134         visitor.append(&m_dfgData->weakReferences[i]);
2135 #endif    
2136 }
2137
2138 HandlerInfo* CodeBlock::handlerForBytecodeOffset(unsigned bytecodeOffset)
2139 {
2140     ASSERT(bytecodeOffset < instructions().size());
2141
2142     if (!m_rareData)
2143         return 0;
2144     
2145     Vector<HandlerInfo>& exceptionHandlers = m_rareData->m_exceptionHandlers;
2146     for (size_t i = 0; i < exceptionHandlers.size(); ++i) {
2147         // Handlers are ordered innermost first, so the first handler we encounter
2148         // that contains the source address is the correct handler to use.
2149         if (exceptionHandlers[i].start <= bytecodeOffset && exceptionHandlers[i].end >= bytecodeOffset)
2150             return &exceptionHandlers[i];
2151     }
2152
2153     return 0;
2154 }
2155
2156 int CodeBlock::lineNumberForBytecodeOffset(unsigned bytecodeOffset)
2157 {
2158     ASSERT(bytecodeOffset < instructions().size());
2159
2160     if (!m_rareData)
2161         return m_ownerExecutable->source().firstLine();
2162
2163     Vector<LineInfo>& lineInfo = m_rareData->m_lineInfo;
2164
2165     int low = 0;
2166     int high = lineInfo.size();
2167     while (low < high) {
2168         int mid = low + (high - low) / 2;
2169         if (lineInfo[mid].instructionOffset <= bytecodeOffset)
2170             low = mid + 1;
2171         else
2172             high = mid;
2173     }
2174
2175     if (!low)
2176         return m_ownerExecutable->source().firstLine();
2177     return lineInfo[low - 1].lineNumber;
2178 }
2179
2180 void CodeBlock::expressionRangeForBytecodeOffset(unsigned bytecodeOffset, int& divot, int& startOffset, int& endOffset)
2181 {
2182     ASSERT(bytecodeOffset < instructions().size());
2183
2184     if (!m_rareData) {
2185         startOffset = 0;
2186         endOffset = 0;
2187         divot = 0;
2188         return;
2189     }
2190
2191     Vector<ExpressionRangeInfo>& expressionInfo = m_rareData->m_expressionInfo;
2192
2193     int low = 0;
2194     int high = expressionInfo.size();
2195     while (low < high) {
2196         int mid = low + (high - low) / 2;
2197         if (expressionInfo[mid].instructionOffset <= bytecodeOffset)
2198             low = mid + 1;
2199         else
2200             high = mid;
2201     }
2202
2203     ASSERT(low);
2204     if (!low) {
2205         startOffset = 0;
2206         endOffset = 0;
2207         divot = 0;
2208         return;
2209     }
2210
2211     startOffset = expressionInfo[low - 1].startOffset;
2212     endOffset = expressionInfo[low - 1].endOffset;
2213     divot = expressionInfo[low - 1].divotPoint + m_sourceOffset;
2214     return;
2215 }
2216
2217 #if ENABLE(CLASSIC_INTERPRETER)
2218 bool CodeBlock::hasGlobalResolveInstructionAtBytecodeOffset(unsigned bytecodeOffset)
2219 {
2220     if (m_globalResolveInstructions.isEmpty())
2221         return false;
2222
2223     int low = 0;
2224     int high = m_globalResolveInstructions.size();
2225     while (low < high) {
2226         int mid = low + (high - low) / 2;
2227         if (m_globalResolveInstructions[mid] <= bytecodeOffset)
2228             low = mid + 1;
2229         else
2230             high = mid;
2231     }
2232
2233     if (!low || m_globalResolveInstructions[low - 1] != bytecodeOffset)
2234         return false;
2235     return true;
2236 }
2237 #endif
2238 #if ENABLE(JIT)
2239 bool CodeBlock::hasGlobalResolveInfoAtBytecodeOffset(unsigned bytecodeOffset)
2240 {
2241     if (m_globalResolveInfos.isEmpty())
2242         return false;
2243
2244     int low = 0;
2245     int high = m_globalResolveInfos.size();
2246     while (low < high) {
2247         int mid = low + (high - low) / 2;
2248         if (m_globalResolveInfos[mid].bytecodeOffset <= bytecodeOffset)
2249             low = mid + 1;
2250         else
2251             high = mid;
2252     }
2253
2254     if (!low || m_globalResolveInfos[low - 1].bytecodeOffset != bytecodeOffset)
2255         return false;
2256     return true;
2257 }
2258 #endif
2259
2260 void CodeBlock::shrinkToFit(ShrinkMode shrinkMode)
2261 {
2262     m_propertyAccessInstructions.shrinkToFit();
2263     m_globalResolveInstructions.shrinkToFit();
2264 #if ENABLE(LLINT)
2265     m_llintCallLinkInfos.shrinkToFit();
2266 #endif
2267 #if ENABLE(JIT)
2268     m_structureStubInfos.shrinkToFit();
2269     m_globalResolveInfos.shrinkToFit();
2270     m_callLinkInfos.shrinkToFit();
2271     m_methodCallLinkInfos.shrinkToFit();
2272 #endif
2273 #if ENABLE(VALUE_PROFILER)
2274     if (shrinkMode == EarlyShrink)
2275         m_argumentValueProfiles.shrinkToFit();
2276     m_valueProfiles.shrinkToFit();
2277     m_rareCaseProfiles.shrinkToFit();
2278     m_specialFastCaseProfiles.shrinkToFit();
2279 #endif
2280     
2281     if (shrinkMode == EarlyShrink) {
2282         m_identifiers.shrinkToFit();
2283         m_functionDecls.shrinkToFit();
2284         m_functionExprs.shrinkToFit();
2285         m_constantRegisters.shrinkToFit();
2286     } // else don't shrink these, because we would have already pointed pointers into these tables.
2287
2288     if (m_rareData) {
2289         m_rareData->m_exceptionHandlers.shrinkToFit();
2290         m_rareData->m_regexps.shrinkToFit();
2291         m_rareData->m_immediateSwitchJumpTables.shrinkToFit();
2292         m_rareData->m_characterSwitchJumpTables.shrinkToFit();
2293         m_rareData->m_stringSwitchJumpTables.shrinkToFit();
2294         m_rareData->m_expressionInfo.shrinkToFit();
2295         m_rareData->m_lineInfo.shrinkToFit();
2296 #if ENABLE(JIT)
2297         m_rareData->m_callReturnIndexVector.shrinkToFit();
2298 #endif
2299 #if ENABLE(DFG_JIT)
2300         m_rareData->m_inlineCallFrames.shrinkToFit();
2301         m_rareData->m_codeOrigins.shrinkToFit();
2302 #endif
2303     }
2304     
2305 #if ENABLE(DFG_JIT)
2306     if (m_dfgData) {
2307         m_dfgData->osrEntry.shrinkToFit();
2308         m_dfgData->osrExit.shrinkToFit();
2309         m_dfgData->speculationRecovery.shrinkToFit();
2310         m_dfgData->weakReferences.shrinkToFit();
2311         m_dfgData->transitions.shrinkToFit();
2312     }
2313 #endif
2314 }
2315
2316 void CodeBlock::createActivation(CallFrame* callFrame)
2317 {
2318     ASSERT(codeType() == FunctionCode);
2319     ASSERT(needsFullScopeChain());
2320     ASSERT(!callFrame->uncheckedR(activationRegister()).jsValue());
2321     JSActivation* activation = JSActivation::create(callFrame->globalData(), callFrame, static_cast<FunctionExecutable*>(ownerExecutable()));
2322     callFrame->uncheckedR(activationRegister()) = JSValue(activation);
2323     callFrame->setScopeChain(callFrame->scopeChain()->push(activation));
2324 }
2325
2326 unsigned CodeBlock::addOrFindConstant(JSValue v)
2327 {
2328     unsigned numberOfConstants = numberOfConstantRegisters();
2329     for (unsigned i = 0; i < numberOfConstants; ++i) {
2330         if (getConstant(FirstConstantRegisterIndex + i) == v)
2331             return i;
2332     }
2333     return addConstant(v);
2334 }
2335
2336 #if ENABLE(JIT)
2337 void CodeBlock::unlinkCalls()
2338 {
2339     if (!!m_alternative)
2340         m_alternative->unlinkCalls();
2341 #if ENABLE(LLINT)
2342     for (size_t i = 0; i < m_llintCallLinkInfos.size(); ++i) {
2343         if (m_llintCallLinkInfos[i].isLinked())
2344             m_llintCallLinkInfos[i].unlink();
2345     }
2346 #endif
2347     if (!(m_callLinkInfos.size() || m_methodCallLinkInfos.size()))
2348         return;
2349     if (!m_globalData->canUseJIT())
2350         return;
2351     RepatchBuffer repatchBuffer(this);
2352     for (size_t i = 0; i < m_callLinkInfos.size(); i++) {
2353         if (!m_callLinkInfos[i].isLinked())
2354             continue;
2355         m_callLinkInfos[i].unlink(*m_globalData, repatchBuffer);
2356     }
2357 }
2358
2359 void CodeBlock::unlinkIncomingCalls()
2360 {
2361 #if ENABLE(LLINT)
2362     while (m_incomingLLIntCalls.begin() != m_incomingLLIntCalls.end())
2363         m_incomingLLIntCalls.begin()->unlink();
2364 #endif
2365     if (m_incomingCalls.isEmpty())
2366         return;
2367     RepatchBuffer repatchBuffer(this);
2368     while (m_incomingCalls.begin() != m_incomingCalls.end())
2369         m_incomingCalls.begin()->unlink(*m_globalData, repatchBuffer);
2370 }
2371
2372 unsigned CodeBlock::bytecodeOffset(ExecState* exec, ReturnAddressPtr returnAddress)
2373 {
2374 #if ENABLE(LLINT)
2375     if (returnAddress.value() >= bitwise_cast<void*>(&llint_begin)
2376         && returnAddress.value() <= bitwise_cast<void*>(&llint_end)) {
2377         ASSERT(exec->codeBlock());
2378         ASSERT(exec->codeBlock() == this);
2379         ASSERT(JITCode::isBaselineCode(getJITType()));
2380         Instruction* instruction = exec->currentVPC();
2381         ASSERT(instruction);
2382         
2383         // The LLInt stores the PC after the call instruction rather than the PC of
2384         // the call instruction. This requires some correcting. We rely on the fact
2385         // that the preceding instruction must be one of the call instructions, so
2386         // either it's a call_varargs or it's a call, construct, or eval.
2387         ASSERT(OPCODE_LENGTH(op_call_varargs) <= OPCODE_LENGTH(op_call));
2388         ASSERT(OPCODE_LENGTH(op_call) == OPCODE_LENGTH(op_construct));
2389         ASSERT(OPCODE_LENGTH(op_call) == OPCODE_LENGTH(op_call_eval));
2390         if (instruction[-OPCODE_LENGTH(op_call_varargs)].u.pointer == bitwise_cast<void*>(llint_op_call_varargs)) {
2391             // We know that the preceding instruction must be op_call_varargs because there is no way that
2392             // the pointer to the call_varargs could be an operand to the call.
2393             instruction -= OPCODE_LENGTH(op_call_varargs);
2394             ASSERT(instruction[-OPCODE_LENGTH(op_call)].u.pointer != bitwise_cast<void*>(llint_op_call)
2395                    && instruction[-OPCODE_LENGTH(op_call)].u.pointer != bitwise_cast<void*>(llint_op_construct)
2396                    && instruction[-OPCODE_LENGTH(op_call)].u.pointer != bitwise_cast<void*>(llint_op_call_eval));
2397         } else {
2398             // Must be that the last instruction was some op_call.
2399             ASSERT(instruction[-OPCODE_LENGTH(op_call)].u.pointer == bitwise_cast<void*>(llint_op_call)
2400                    || instruction[-OPCODE_LENGTH(op_call)].u.pointer == bitwise_cast<void*>(llint_op_construct)
2401                    || instruction[-OPCODE_LENGTH(op_call)].u.pointer == bitwise_cast<void*>(llint_op_call_eval));
2402             instruction -= OPCODE_LENGTH(op_call);
2403         }
2404         
2405         return bytecodeOffset(instruction);
2406     }
2407 #else
2408     UNUSED_PARAM(exec);
2409 #endif
2410     if (!m_rareData)
2411         return 1;
2412     Vector<CallReturnOffsetToBytecodeOffset>& callIndices = m_rareData->m_callReturnIndexVector;
2413     if (!callIndices.size())
2414         return 1;
2415     return binarySearch<CallReturnOffsetToBytecodeOffset, unsigned, getCallReturnOffset>(callIndices.begin(), callIndices.size(), getJITCode().offsetOf(returnAddress.value()))->bytecodeOffset;
2416 }
2417 #endif
2418
2419 void CodeBlock::clearEvalCache()
2420 {
2421     if (!!m_alternative)
2422         m_alternative->clearEvalCache();
2423     if (!m_rareData)
2424         return;
2425     m_rareData->m_evalCodeCache.clear();
2426 }
2427
2428 template<typename T>
2429 inline void replaceExistingEntries(Vector<T>& target, Vector<T>& source)
2430 {
2431     ASSERT(target.size() <= source.size());
2432     for (size_t i = 0; i < target.size(); ++i)
2433         target[i] = source[i];
2434 }
2435
2436 void CodeBlock::copyPostParseDataFrom(CodeBlock* alternative)
2437 {
2438     if (!alternative)
2439         return;
2440     
2441     replaceExistingEntries(m_constantRegisters, alternative->m_constantRegisters);
2442     replaceExistingEntries(m_functionDecls, alternative->m_functionDecls);
2443     replaceExistingEntries(m_functionExprs, alternative->m_functionExprs);
2444     if (!!m_rareData && !!alternative->m_rareData)
2445         replaceExistingEntries(m_rareData->m_constantBuffers, alternative->m_rareData->m_constantBuffers);
2446 }
2447
2448 void CodeBlock::copyPostParseDataFromAlternative()
2449 {
2450     copyPostParseDataFrom(m_alternative.get());
2451 }
2452
2453 #if ENABLE(JIT)
2454 CodeBlock* ProgramCodeBlock::replacement()
2455 {
2456     return &static_cast<ProgramExecutable*>(ownerExecutable())->generatedBytecode();
2457 }
2458
2459 CodeBlock* EvalCodeBlock::replacement()
2460 {
2461     return &static_cast<EvalExecutable*>(ownerExecutable())->generatedBytecode();
2462 }
2463
2464 CodeBlock* FunctionCodeBlock::replacement()
2465 {
2466     return &static_cast<FunctionExecutable*>(ownerExecutable())->generatedBytecodeFor(m_isConstructor ? CodeForConstruct : CodeForCall);
2467 }
2468
2469 JSObject* ProgramCodeBlock::compileOptimized(ExecState* exec, ScopeChainNode* scopeChainNode)
2470 {
2471     if (replacement()->getJITType() == JITCode::nextTierJIT(getJITType()))
2472         return 0;
2473     JSObject* error = static_cast<ProgramExecutable*>(ownerExecutable())->compileOptimized(exec, scopeChainNode);
2474     return error;
2475 }
2476
2477 JSObject* EvalCodeBlock::compileOptimized(ExecState* exec, ScopeChainNode* scopeChainNode)
2478 {
2479     if (replacement()->getJITType() == JITCode::nextTierJIT(getJITType()))
2480         return 0;
2481     JSObject* error = static_cast<EvalExecutable*>(ownerExecutable())->compileOptimized(exec, scopeChainNode);
2482     return error;
2483 }
2484
2485 JSObject* FunctionCodeBlock::compileOptimized(ExecState* exec, ScopeChainNode* scopeChainNode)
2486 {
2487     if (replacement()->getJITType() == JITCode::nextTierJIT(getJITType()))
2488         return 0;
2489     JSObject* error = static_cast<FunctionExecutable*>(ownerExecutable())->compileOptimizedFor(exec, scopeChainNode, m_isConstructor ? CodeForConstruct : CodeForCall);
2490     return error;
2491 }
2492
2493 DFG::CapabilityLevel ProgramCodeBlock::canCompileWithDFGInternal()
2494 {
2495     return DFG::canCompileProgram(this);
2496 }
2497
2498 DFG::CapabilityLevel EvalCodeBlock::canCompileWithDFGInternal()
2499 {
2500     return DFG::canCompileEval(this);
2501 }
2502
2503 DFG::CapabilityLevel FunctionCodeBlock::canCompileWithDFGInternal()
2504 {
2505     if (m_isConstructor)
2506         return DFG::canCompileFunctionForConstruct(this);
2507     return DFG::canCompileFunctionForCall(this);
2508 }
2509
2510 void ProgramCodeBlock::jettison()
2511 {
2512     ASSERT(JITCode::isOptimizingJIT(getJITType()));
2513     ASSERT(this == replacement());
2514     static_cast<ProgramExecutable*>(ownerExecutable())->jettisonOptimizedCode(*globalData());
2515 }
2516
2517 void EvalCodeBlock::jettison()
2518 {
2519     ASSERT(JITCode::isOptimizingJIT(getJITType()));
2520     ASSERT(this == replacement());
2521     static_cast<EvalExecutable*>(ownerExecutable())->jettisonOptimizedCode(*globalData());
2522 }
2523
2524 void FunctionCodeBlock::jettison()
2525 {
2526     ASSERT(JITCode::isOptimizingJIT(getJITType()));
2527     ASSERT(this == replacement());
2528     static_cast<FunctionExecutable*>(ownerExecutable())->jettisonOptimizedCodeFor(*globalData(), m_isConstructor ? CodeForConstruct : CodeForCall);
2529 }
2530
2531 bool ProgramCodeBlock::jitCompileImpl(ExecState* exec)
2532 {
2533     ASSERT(getJITType() == JITCode::InterpreterThunk);
2534     ASSERT(this == replacement());
2535     return static_cast<ProgramExecutable*>(ownerExecutable())->jitCompile(exec);
2536 }
2537
2538 bool EvalCodeBlock::jitCompileImpl(ExecState* exec)
2539 {
2540     ASSERT(getJITType() == JITCode::InterpreterThunk);
2541     ASSERT(this == replacement());
2542     return static_cast<EvalExecutable*>(ownerExecutable())->jitCompile(exec);
2543 }
2544
2545 bool FunctionCodeBlock::jitCompileImpl(ExecState* exec)
2546 {
2547     ASSERT(getJITType() == JITCode::InterpreterThunk);
2548     ASSERT(this == replacement());
2549     return static_cast<FunctionExecutable*>(ownerExecutable())->jitCompileFor(exec, m_isConstructor ? CodeForConstruct : CodeForCall);
2550 }
2551 #endif
2552
2553 #if ENABLE(VALUE_PROFILER)
2554 bool CodeBlock::shouldOptimizeNow()
2555 {
2556 #if ENABLE(JIT_VERBOSE_OSR)
2557     dataLog("Considering optimizing %p...\n", this);
2558 #endif
2559
2560 #if ENABLE(VERBOSE_VALUE_PROFILE)
2561     dumpValueProfiles();
2562 #endif
2563
2564     if (m_optimizationDelayCounter >= Options::maximumOptimizationDelay)
2565         return true;
2566     
2567     unsigned numberOfLiveNonArgumentValueProfiles = 0;
2568     unsigned numberOfSamplesInProfiles = 0; // If this divided by ValueProfile::numberOfBuckets equals numberOfValueProfiles() then value profiles are full.
2569     for (unsigned i = 0; i < totalNumberOfValueProfiles(); ++i) {
2570         ValueProfile* profile = getFromAllValueProfiles(i);
2571         unsigned numSamples = profile->totalNumberOfSamples();
2572         if (numSamples > ValueProfile::numberOfBuckets)
2573             numSamples = ValueProfile::numberOfBuckets; // We don't want profiles that are extremely hot to be given more weight.
2574         numberOfSamplesInProfiles += numSamples;
2575         if (profile->m_bytecodeOffset < 0) {
2576             profile->computeUpdatedPrediction();
2577             continue;
2578         }
2579         if (profile->numberOfSamples() || profile->m_prediction != SpecNone)
2580             numberOfLiveNonArgumentValueProfiles++;
2581         profile->computeUpdatedPrediction();
2582     }
2583
2584 #if ENABLE(JIT_VERBOSE_OSR)
2585     dataLog("Profile hotness: %lf, %lf\n", (double)numberOfLiveNonArgumentValueProfiles / numberOfValueProfiles(), (double)numberOfSamplesInProfiles / ValueProfile::numberOfBuckets / numberOfValueProfiles());
2586 #endif
2587
2588     if ((!numberOfValueProfiles() || (double)numberOfLiveNonArgumentValueProfiles / numberOfValueProfiles() >= Options::desiredProfileLivenessRate)
2589         && (!totalNumberOfValueProfiles() || (double)numberOfSamplesInProfiles / ValueProfile::numberOfBuckets / totalNumberOfValueProfiles() >= Options::desiredProfileFullnessRate)
2590         && static_cast<unsigned>(m_optimizationDelayCounter) + 1 >= Options::minimumOptimizationDelay)
2591         return true;
2592     
2593     ASSERT(m_optimizationDelayCounter < std::numeric_limits<uint8_t>::max());
2594     m_optimizationDelayCounter++;
2595     optimizeAfterWarmUp();
2596     return false;
2597 }
2598 #endif
2599
2600 #if ENABLE(DFG_JIT)
2601 void CodeBlock::tallyFrequentExitSites()
2602 {
2603     ASSERT(getJITType() == JITCode::DFGJIT);
2604     ASSERT(alternative()->getJITType() == JITCode::BaselineJIT);
2605     ASSERT(!!m_dfgData);
2606     
2607     CodeBlock* profiledBlock = alternative();
2608     
2609     for (unsigned i = 0; i < m_dfgData->osrExit.size(); ++i) {
2610         DFG::OSRExit& exit = m_dfgData->osrExit[i];
2611         
2612         if (!exit.considerAddingAsFrequentExitSite(this, profiledBlock))
2613             continue;
2614         
2615 #if DFG_ENABLE(DEBUG_VERBOSE)
2616         dataLog("OSR exit #%u (bc#%u, @%u, %s) for code block %p occurred frequently; counting as frequent exit site.\n", i, exit.m_codeOrigin.bytecodeIndex, exit.m_nodeIndex, DFG::exitKindToString(exit.m_kind), this);
2617 #endif
2618     }
2619 }
2620 #endif // ENABLE(DFG_JIT)
2621
2622 #if ENABLE(VERBOSE_VALUE_PROFILE)
2623 void CodeBlock::dumpValueProfiles()
2624 {
2625     dataLog("ValueProfile for %p:\n", this);
2626     for (unsigned i = 0; i < totalNumberOfValueProfiles(); ++i) {
2627         ValueProfile* profile = getFromAllValueProfiles(i);
2628         if (profile->m_bytecodeOffset < 0) {
2629             ASSERT(profile->m_bytecodeOffset == -1);
2630             dataLog("   arg = %u: ", i);
2631         } else
2632             dataLog("   bc = %d: ", profile->m_bytecodeOffset);
2633         if (!profile->numberOfSamples() && profile->m_prediction == SpecNone) {
2634             dataLog("<empty>\n");
2635             continue;
2636         }
2637         profile->dump(WTF::dataFile());
2638         dataLog("\n");
2639     }
2640     dataLog("RareCaseProfile for %p:\n", this);
2641     for (unsigned i = 0; i < numberOfRareCaseProfiles(); ++i) {
2642         RareCaseProfile* profile = rareCaseProfile(i);
2643         dataLog("   bc = %d: %u\n", profile->m_bytecodeOffset, profile->m_counter);
2644     }
2645     dataLog("SpecialFastCaseProfile for %p:\n", this);
2646     for (unsigned i = 0; i < numberOfSpecialFastCaseProfiles(); ++i) {
2647         RareCaseProfile* profile = specialFastCaseProfile(i);
2648         dataLog("   bc = %d: %u\n", profile->m_bytecodeOffset, profile->m_counter);
2649     }
2650 }
2651 #endif
2652
2653 size_t CodeBlock::predictedMachineCodeSize()
2654 {
2655     // This will be called from CodeBlock::CodeBlock before either m_globalData or the
2656     // instructions have been initialized. It's OK to return 0 because what will really
2657     // matter is the recomputation of this value when the slow path is triggered.
2658     if (!m_globalData)
2659         return 0;
2660     
2661     if (!m_globalData->machineCodeBytesPerBytecodeWordForBaselineJIT)
2662         return 0; // It's as good of a prediction as we'll get.
2663     
2664     // Be conservative: return a size that will be an overestimation 84% of the time.
2665     double multiplier = m_globalData->machineCodeBytesPerBytecodeWordForBaselineJIT.mean() +
2666         m_globalData->machineCodeBytesPerBytecodeWordForBaselineJIT.standardDeviation();
2667     
2668     // Be paranoid: silently reject bogus multipiers. Silently doing the "wrong" thing
2669     // here is OK, since this whole method is just a heuristic.
2670     if (multiplier < 0 || multiplier > 1000)
2671         return 0;
2672     
2673     double doubleResult = multiplier * m_instructions.size();
2674     
2675     // Be even more paranoid: silently reject values that won't fit into a size_t. If
2676     // the function is so huge that we can't even fit it into virtual memory then we
2677     // should probably have some other guards in place to prevent us from even getting
2678     // to this point.
2679     if (doubleResult > std::numeric_limits<size_t>::max())
2680         return 0;
2681     
2682     return static_cast<size_t>(doubleResult);
2683 }
2684
2685 bool CodeBlock::usesOpcode(OpcodeID opcodeID)
2686 {
2687     Interpreter* interpreter = globalData()->interpreter;
2688     Instruction* instructionsBegin = instructions().begin();
2689     unsigned instructionCount = instructions().size();
2690     
2691     for (unsigned bytecodeOffset = 0; bytecodeOffset < instructionCount; ) {
2692         switch (interpreter->getOpcodeID(instructionsBegin[bytecodeOffset].u.opcode)) {
2693 #define DEFINE_OP(curOpcode, length)        \
2694         case curOpcode:                     \
2695             if (curOpcode == opcodeID)      \
2696                 return true;                \
2697             bytecodeOffset += length;       \
2698             break;
2699             FOR_EACH_OPCODE_ID(DEFINE_OP)
2700 #undef DEFINE_OP
2701         default:
2702             ASSERT_NOT_REACHED();
2703             break;
2704         }
2705     }
2706     
2707     return false;
2708 }
2709
2710 } // namespace JSC