DFG should inline prototype chain accesses, and do the right things if the
[WebKit-https.git] / Source / JavaScriptCore / bytecode / CodeBlock.h
1 /*
2  * Copyright (C) 2008, 2009, 2010, 2011, 2012 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 #ifndef CodeBlock_h
31 #define CodeBlock_h
32
33 #include "BytecodeConventions.h"
34 #include "CallLinkInfo.h"
35 #include "CallReturnOffsetToBytecodeOffset.h"
36 #include "CodeOrigin.h"
37 #include "CodeType.h"
38 #include "CompactJITCodeMap.h"
39 #include "DFGCodeBlocks.h"
40 #include "DFGCommon.h"
41 #include "DFGExitProfile.h"
42 #include "DFGOSREntry.h"
43 #include "DFGOSRExit.h"
44 #include "EvalCodeCache.h"
45 #include "ExecutionCounter.h"
46 #include "ExpressionRangeInfo.h"
47 #include "GlobalResolveInfo.h"
48 #include "HandlerInfo.h"
49 #include "MethodCallLinkInfo.h"
50 #include "Options.h"
51 #include "Instruction.h"
52 #include "JITCode.h"
53 #include "JITWriteBarrier.h"
54 #include "JSGlobalObject.h"
55 #include "JumpTable.h"
56 #include "LLIntCallLinkInfo.h"
57 #include "LazyOperandValueProfile.h"
58 #include "LineInfo.h"
59 #include "Nodes.h"
60 #include "RegExpObject.h"
61 #include "StructureStubInfo.h"
62 #include "UString.h"
63 #include "UnconditionalFinalizer.h"
64 #include "ValueProfile.h"
65 #include <wtf/RefCountedArray.h>
66 #include <wtf/FastAllocBase.h>
67 #include <wtf/PassOwnPtr.h>
68 #include <wtf/RefPtr.h>
69 #include <wtf/SegmentedVector.h>
70 #include <wtf/Vector.h>
71 #include "StructureStubInfo.h"
72
73 namespace JSC {
74
75     class DFGCodeBlocks;
76     class ExecState;
77     class LLIntOffsetsExtractor;
78
79     inline int unmodifiedArgumentsRegister(int argumentsRegister) { return argumentsRegister - 1; }
80
81     static ALWAYS_INLINE int missingThisObjectMarker() { return std::numeric_limits<int>::max(); }
82
83     class CodeBlock : public UnconditionalFinalizer, public WeakReferenceHarvester {
84         WTF_MAKE_FAST_ALLOCATED;
85         friend class JIT;
86         friend class LLIntOffsetsExtractor;
87     public:
88         enum CopyParsedBlockTag { CopyParsedBlock };
89     protected:
90         CodeBlock(CopyParsedBlockTag, CodeBlock& other, SymbolTable*);
91         
92         CodeBlock(ScriptExecutable* ownerExecutable, CodeType, JSGlobalObject*, PassRefPtr<SourceProvider>, unsigned sourceOffset, SymbolTable*, bool isConstructor, PassOwnPtr<CodeBlock> alternative);
93
94         WriteBarrier<JSGlobalObject> m_globalObject;
95         Heap* m_heap;
96
97     public:
98         JS_EXPORT_PRIVATE virtual ~CodeBlock();
99         
100         int numParameters() const { return m_numParameters; }
101         void setNumParameters(int newValue);
102         void addParameter();
103         
104         int* addressOfNumParameters() { return &m_numParameters; }
105         static ptrdiff_t offsetOfNumParameters() { return OBJECT_OFFSETOF(CodeBlock, m_numParameters); }
106
107         CodeBlock* alternative() { return m_alternative.get(); }
108         PassOwnPtr<CodeBlock> releaseAlternative() { return m_alternative.release(); }
109         void setAlternative(PassOwnPtr<CodeBlock> alternative) { m_alternative = alternative; }
110         
111         CodeSpecializationKind specializationKind()
112         {
113             if (m_isConstructor)
114                 return CodeForConstruct;
115             return CodeForCall;
116         }
117         
118 #if ENABLE(JIT)
119         CodeBlock* baselineVersion()
120         {
121             CodeBlock* result = replacement();
122             if (!result)
123                 return 0; // This can happen if we're in the process of creating the baseline version.
124             while (result->alternative())
125                 result = result->alternative();
126             ASSERT(result);
127             ASSERT(JITCode::isBaselineCode(result->getJITType()));
128             return result;
129         }
130 #endif
131         
132         void visitAggregate(SlotVisitor&);
133
134         static void dumpStatistics();
135
136         void dump(ExecState*);
137         void printStructures(const Instruction*);
138         void printStructure(const char* name, const Instruction*, int operand);
139
140         bool isStrictMode() const { return m_isStrictMode; }
141
142         inline bool isKnownNotImmediate(int index)
143         {
144             if (index == m_thisRegister && !m_isStrictMode)
145                 return true;
146
147             if (isConstantRegisterIndex(index))
148                 return getConstant(index).isCell();
149
150             return false;
151         }
152
153         ALWAYS_INLINE bool isTemporaryRegisterIndex(int index)
154         {
155             return index >= m_numVars;
156         }
157
158         HandlerInfo* handlerForBytecodeOffset(unsigned bytecodeOffset);
159         int lineNumberForBytecodeOffset(unsigned bytecodeOffset);
160         void expressionRangeForBytecodeOffset(unsigned bytecodeOffset, int& divot, int& startOffset, int& endOffset);
161
162 #if ENABLE(JIT)
163
164         StructureStubInfo& getStubInfo(ReturnAddressPtr returnAddress)
165         {
166             return *(binarySearch<StructureStubInfo, void*, getStructureStubInfoReturnLocation>(m_structureStubInfos.begin(), m_structureStubInfos.size(), returnAddress.value()));
167         }
168
169         StructureStubInfo& getStubInfo(unsigned bytecodeIndex)
170         {
171             return *(binarySearch<StructureStubInfo, unsigned, getStructureStubInfoBytecodeIndex>(m_structureStubInfos.begin(), m_structureStubInfos.size(), bytecodeIndex));
172         }
173
174         CallLinkInfo& getCallLinkInfo(ReturnAddressPtr returnAddress)
175         {
176             return *(binarySearch<CallLinkInfo, void*, getCallLinkInfoReturnLocation>(m_callLinkInfos.begin(), m_callLinkInfos.size(), returnAddress.value()));
177         }
178         
179         CallLinkInfo& getCallLinkInfo(unsigned bytecodeIndex)
180         {
181             return *(binarySearch<CallLinkInfo, unsigned, getCallLinkInfoBytecodeIndex>(m_callLinkInfos.begin(), m_callLinkInfos.size(), bytecodeIndex));
182         }
183
184         MethodCallLinkInfo& getMethodCallLinkInfo(ReturnAddressPtr returnAddress)
185         {
186             return *(binarySearch<MethodCallLinkInfo, void*, getMethodCallLinkInfoReturnLocation>(m_methodCallLinkInfos.begin(), m_methodCallLinkInfos.size(), returnAddress.value()));
187         }
188
189         MethodCallLinkInfo& getMethodCallLinkInfo(unsigned bytecodeIndex)
190         {
191             return *(binarySearch<MethodCallLinkInfo, unsigned, getMethodCallLinkInfoBytecodeIndex>(m_methodCallLinkInfos.begin(), m_methodCallLinkInfos.size(), bytecodeIndex));
192         }
193
194         unsigned bytecodeOffset(ExecState*, ReturnAddressPtr);
195
196         unsigned bytecodeOffsetForCallAtIndex(unsigned index)
197         {
198             if (!m_rareData)
199                 return 1;
200             Vector<CallReturnOffsetToBytecodeOffset>& callIndices = m_rareData->m_callReturnIndexVector;
201             if (!callIndices.size())
202                 return 1;
203             ASSERT(index < m_rareData->m_callReturnIndexVector.size());
204             return m_rareData->m_callReturnIndexVector[index].bytecodeOffset;
205         }
206
207         void unlinkCalls();
208         
209         bool hasIncomingCalls() { return m_incomingCalls.begin() != m_incomingCalls.end(); }
210         
211         void linkIncomingCall(CallLinkInfo* incoming)
212         {
213             m_incomingCalls.push(incoming);
214         }
215 #if ENABLE(LLINT)
216         void linkIncomingCall(LLIntCallLinkInfo* incoming)
217         {
218             m_incomingLLIntCalls.push(incoming);
219         }
220 #endif // ENABLE(LLINT)
221         
222         void unlinkIncomingCalls();
223 #endif // ENABLE(JIT)
224
225 #if ENABLE(DFG_JIT) || ENABLE(LLINT)
226         void setJITCodeMap(PassOwnPtr<CompactJITCodeMap> jitCodeMap)
227         {
228             m_jitCodeMap = jitCodeMap;
229         }
230         CompactJITCodeMap* jitCodeMap()
231         {
232             return m_jitCodeMap.get();
233         }
234 #endif
235         
236 #if ENABLE(DFG_JIT)
237         void createDFGDataIfNecessary()
238         {
239             if (!!m_dfgData)
240                 return;
241             
242             m_dfgData = adoptPtr(new DFGData);
243         }
244         
245         DFG::OSREntryData* appendDFGOSREntryData(unsigned bytecodeIndex, unsigned machineCodeOffset)
246         {
247             createDFGDataIfNecessary();
248             DFG::OSREntryData entry;
249             entry.m_bytecodeIndex = bytecodeIndex;
250             entry.m_machineCodeOffset = machineCodeOffset;
251             m_dfgData->osrEntry.append(entry);
252             return &m_dfgData->osrEntry.last();
253         }
254         unsigned numberOfDFGOSREntries() const
255         {
256             if (!m_dfgData)
257                 return 0;
258             return m_dfgData->osrEntry.size();
259         }
260         DFG::OSREntryData* dfgOSREntryData(unsigned i) { return &m_dfgData->osrEntry[i]; }
261         DFG::OSREntryData* dfgOSREntryDataForBytecodeIndex(unsigned bytecodeIndex)
262         {
263             if (!m_dfgData)
264                 return 0;
265             if (m_dfgData->osrEntry.isEmpty())
266                 return 0;
267             DFG::OSREntryData* result = binarySearch<
268                 DFG::OSREntryData, unsigned, DFG::getOSREntryDataBytecodeIndex>(
269                     m_dfgData->osrEntry.begin(), m_dfgData->osrEntry.size(),
270                     bytecodeIndex, WTF::KeyMustNotBePresentInArray);
271             if (result->m_bytecodeIndex != bytecodeIndex)
272                 return 0;
273             return result;
274         }
275         
276         void appendOSRExit(const DFG::OSRExit& osrExit)
277         {
278             createDFGDataIfNecessary();
279             m_dfgData->osrExit.append(osrExit);
280         }
281         
282         DFG::OSRExit& lastOSRExit()
283         {
284             return m_dfgData->osrExit.last();
285         }
286         
287         void appendSpeculationRecovery(const DFG::SpeculationRecovery& recovery)
288         {
289             createDFGDataIfNecessary();
290             m_dfgData->speculationRecovery.append(recovery);
291         }
292         
293         unsigned numberOfOSRExits()
294         {
295             if (!m_dfgData)
296                 return 0;
297             return m_dfgData->osrExit.size();
298         }
299         
300         unsigned numberOfSpeculationRecoveries()
301         {
302             if (!m_dfgData)
303                 return 0;
304             return m_dfgData->speculationRecovery.size();
305         }
306         
307         DFG::OSRExit& osrExit(unsigned index)
308         {
309             return m_dfgData->osrExit[index];
310         }
311         
312         DFG::SpeculationRecovery& speculationRecovery(unsigned index)
313         {
314             return m_dfgData->speculationRecovery[index];
315         }
316         
317         void appendWeakReference(JSCell* target)
318         {
319             createDFGDataIfNecessary();
320             m_dfgData->weakReferences.append(WriteBarrier<JSCell>(*globalData(), ownerExecutable(), target));
321         }
322         
323         void appendWeakReferenceTransition(JSCell* codeOrigin, JSCell* from, JSCell* to)
324         {
325             createDFGDataIfNecessary();
326             m_dfgData->transitions.append(
327                 WeakReferenceTransition(*globalData(), ownerExecutable(), codeOrigin, from, to));
328         }
329 #endif
330
331         unsigned bytecodeOffset(Instruction* returnAddress)
332         {
333             ASSERT(returnAddress >= instructions().begin() && returnAddress < instructions().end());
334             return static_cast<Instruction*>(returnAddress) - instructions().begin();
335         }
336
337         void setIsNumericCompareFunction(bool isNumericCompareFunction) { m_isNumericCompareFunction = isNumericCompareFunction; }
338         bool isNumericCompareFunction() { return m_isNumericCompareFunction; }
339
340         unsigned numberOfInstructions() const { return m_instructions.size(); }
341         RefCountedArray<Instruction>& instructions() { return m_instructions; }
342         const RefCountedArray<Instruction>& instructions() const { return m_instructions; }
343         
344         size_t predictedMachineCodeSize();
345         
346         bool usesOpcode(OpcodeID);
347
348         unsigned instructionCount() { return m_instructions.size(); }
349
350 #if ENABLE(JIT)
351         void setJITCode(const JITCode& code, MacroAssemblerCodePtr codeWithArityCheck)
352         {
353             m_jitCode = code;
354             m_jitCodeWithArityCheck = codeWithArityCheck;
355 #if ENABLE(DFG_JIT)
356             if (m_jitCode.jitType() == JITCode::DFGJIT) {
357                 createDFGDataIfNecessary();
358                 m_globalData->heap.m_dfgCodeBlocks.m_set.add(this);
359             }
360 #endif
361         }
362         JITCode& getJITCode() { return m_jitCode; }
363         MacroAssemblerCodePtr getJITCodeWithArityCheck() { return m_jitCodeWithArityCheck; }
364         JITCode::JITType getJITType() { return m_jitCode.jitType(); }
365         ExecutableMemoryHandle* executableMemory() { return getJITCode().getExecutableMemory(); }
366         virtual JSObject* compileOptimized(ExecState*, ScopeChainNode*) = 0;
367         virtual void jettison() = 0;
368         enum JITCompilationResult { AlreadyCompiled, CouldNotCompile, CompiledSuccessfully };
369         JITCompilationResult jitCompile(ExecState* exec)
370         {
371             if (getJITType() != JITCode::InterpreterThunk) {
372                 ASSERT(getJITType() == JITCode::BaselineJIT);
373                 return AlreadyCompiled;
374             }
375 #if ENABLE(JIT)
376             if (jitCompileImpl(exec))
377                 return CompiledSuccessfully;
378             return CouldNotCompile;
379 #else
380             UNUSED_PARAM(exec);
381             return CouldNotCompile;
382 #endif
383         }
384         virtual CodeBlock* replacement() = 0;
385
386         virtual DFG::CapabilityLevel canCompileWithDFGInternal() = 0;
387         DFG::CapabilityLevel canCompileWithDFG()
388         {
389             DFG::CapabilityLevel result = canCompileWithDFGInternal();
390             m_canCompileWithDFGState = result;
391             return result;
392         }
393         DFG::CapabilityLevel canCompileWithDFGState() { return m_canCompileWithDFGState; }
394
395         bool hasOptimizedReplacement()
396         {
397             ASSERT(JITCode::isBaselineCode(getJITType()));
398             bool result = replacement()->getJITType() > getJITType();
399 #if !ASSERT_DISABLED
400             if (result)
401                 ASSERT(replacement()->getJITType() == JITCode::DFGJIT);
402             else {
403                 ASSERT(JITCode::isBaselineCode(replacement()->getJITType()));
404                 ASSERT(replacement() == this);
405             }
406 #endif
407             return result;
408         }
409 #else
410         JITCode::JITType getJITType() { return JITCode::BaselineJIT; }
411 #endif
412
413         ScriptExecutable* ownerExecutable() const { return m_ownerExecutable.get(); }
414
415         void setGlobalData(JSGlobalData* globalData) { m_globalData = globalData; }
416         JSGlobalData* globalData() { return m_globalData; }
417
418         void setThisRegister(int thisRegister) { m_thisRegister = thisRegister; }
419         int thisRegister() const { return m_thisRegister; }
420
421         void setNeedsFullScopeChain(bool needsFullScopeChain) { m_needsFullScopeChain = needsFullScopeChain; }
422         bool needsFullScopeChain() const { return m_needsFullScopeChain; }
423         void setUsesEval(bool usesEval) { m_usesEval = usesEval; }
424         bool usesEval() const { return m_usesEval; }
425         
426         void setArgumentsRegister(int argumentsRegister)
427         {
428             ASSERT(argumentsRegister != -1);
429             m_argumentsRegister = argumentsRegister;
430             ASSERT(usesArguments());
431         }
432         int argumentsRegister()
433         {
434             ASSERT(usesArguments());
435             return m_argumentsRegister;
436         }
437         int uncheckedArgumentsRegister()
438         {
439             if (!usesArguments())
440                 return InvalidVirtualRegister;
441             return argumentsRegister();
442         }
443         void setActivationRegister(int activationRegister)
444         {
445             m_activationRegister = activationRegister;
446         }
447         int activationRegister()
448         {
449             ASSERT(needsFullScopeChain());
450             return m_activationRegister;
451         }
452         int uncheckedActivationRegister()
453         {
454             if (!needsFullScopeChain())
455                 return InvalidVirtualRegister;
456             return activationRegister();
457         }
458         bool usesArguments() const { return m_argumentsRegister != -1; }
459         
460         bool needsActivation() const
461         {
462             return needsFullScopeChain() && codeType() != GlobalCode;
463         }
464         
465         bool argumentsAreCaptured() const
466         {
467             return needsActivation() || usesArguments();
468         }
469         
470         bool argumentIsCaptured(int) const
471         {
472             return argumentsAreCaptured();
473         }
474         
475         bool localIsCaptured(InlineCallFrame* inlineCallFrame, int operand) const
476         {
477             if (!inlineCallFrame)
478                 return operand < m_numCapturedVars;
479             
480             return inlineCallFrame->capturedVars.get(operand);
481         }
482         
483         bool isCaptured(InlineCallFrame* inlineCallFrame, int operand) const
484         {
485             if (operandIsArgument(operand))
486                 return argumentIsCaptured(operandToArgument(operand));
487             return localIsCaptured(inlineCallFrame, operand);
488         }
489
490         CodeType codeType() const { return m_codeType; }
491
492         SourceProvider* source() const { return m_source.get(); }
493         unsigned sourceOffset() const { return m_sourceOffset; }
494
495         size_t numberOfJumpTargets() const { return m_jumpTargets.size(); }
496         void addJumpTarget(unsigned jumpTarget) { m_jumpTargets.append(jumpTarget); }
497         unsigned jumpTarget(int index) const { return m_jumpTargets[index]; }
498         unsigned lastJumpTarget() const { return m_jumpTargets.last(); }
499
500         void createActivation(CallFrame*);
501
502         void clearEvalCache();
503
504         void addPropertyAccessInstruction(unsigned propertyAccessInstruction)
505         {
506             m_propertyAccessInstructions.append(propertyAccessInstruction);
507         }
508         void addGlobalResolveInstruction(unsigned globalResolveInstruction)
509         {
510             m_globalResolveInstructions.append(globalResolveInstruction);
511         }
512         bool hasGlobalResolveInstructionAtBytecodeOffset(unsigned bytecodeOffset);
513 #if ENABLE(LLINT)
514         LLIntCallLinkInfo* addLLIntCallLinkInfo()
515         {
516             m_llintCallLinkInfos.append(LLIntCallLinkInfo());
517             return &m_llintCallLinkInfos.last();
518         }
519 #endif
520 #if ENABLE(JIT)
521         void setNumberOfStructureStubInfos(size_t size) { m_structureStubInfos.grow(size); }
522         size_t numberOfStructureStubInfos() const { return m_structureStubInfos.size(); }
523         StructureStubInfo& structureStubInfo(int index) { return m_structureStubInfos[index]; }
524
525         void addGlobalResolveInfo(unsigned globalResolveInstruction)
526         {
527             m_globalResolveInfos.append(GlobalResolveInfo(globalResolveInstruction));
528         }
529         GlobalResolveInfo& globalResolveInfo(int index) { return m_globalResolveInfos[index]; }
530         bool hasGlobalResolveInfoAtBytecodeOffset(unsigned bytecodeOffset);
531
532         void setNumberOfCallLinkInfos(size_t size) { m_callLinkInfos.grow(size); }
533         size_t numberOfCallLinkInfos() const { return m_callLinkInfos.size(); }
534         CallLinkInfo& callLinkInfo(int index) { return m_callLinkInfos[index]; }
535
536         void addMethodCallLinkInfos(unsigned n) { ASSERT(m_globalData->canUseJIT()); m_methodCallLinkInfos.grow(n); }
537         MethodCallLinkInfo& methodCallLinkInfo(int index) { return m_methodCallLinkInfos[index]; }
538         size_t numberOfMethodCallLinkInfos() { return m_methodCallLinkInfos.size(); }
539 #endif
540         
541 #if ENABLE(VALUE_PROFILER)
542         unsigned numberOfArgumentValueProfiles()
543         {
544             ASSERT(m_numParameters >= 0);
545             ASSERT(m_argumentValueProfiles.size() == static_cast<unsigned>(m_numParameters));
546             return m_argumentValueProfiles.size();
547         }
548         ValueProfile* valueProfileForArgument(unsigned argumentIndex)
549         {
550             ValueProfile* result = &m_argumentValueProfiles[argumentIndex];
551             ASSERT(result->m_bytecodeOffset == -1);
552             return result;
553         }
554         
555         ValueProfile* addValueProfile(int bytecodeOffset)
556         {
557             ASSERT(bytecodeOffset != -1);
558             ASSERT(m_valueProfiles.isEmpty() || m_valueProfiles.last().m_bytecodeOffset < bytecodeOffset);
559             m_valueProfiles.append(ValueProfile(bytecodeOffset));
560             return &m_valueProfiles.last();
561         }
562         unsigned numberOfValueProfiles() { return m_valueProfiles.size(); }
563         ValueProfile* valueProfile(int index)
564         {
565             ValueProfile* result = &m_valueProfiles[index];
566             ASSERT(result->m_bytecodeOffset != -1);
567             return result;
568         }
569         ValueProfile* valueProfileForBytecodeOffset(int bytecodeOffset)
570         {
571             ValueProfile* result = WTF::genericBinarySearch<ValueProfile, int, getValueProfileBytecodeOffset>(m_valueProfiles, m_valueProfiles.size(), bytecodeOffset);
572             ASSERT(result->m_bytecodeOffset != -1);
573             ASSERT(instructions()[bytecodeOffset + opcodeLength(
574                        m_globalData->interpreter->getOpcodeID(
575                            instructions()[
576                                bytecodeOffset].u.opcode)) - 1].u.profile == result);
577             return result;
578         }
579         SpeculatedType valueProfilePredictionForBytecodeOffset(int bytecodeOffset)
580         {
581             return valueProfileForBytecodeOffset(bytecodeOffset)->computeUpdatedPrediction();
582         }
583         
584         unsigned totalNumberOfValueProfiles()
585         {
586             return numberOfArgumentValueProfiles() + numberOfValueProfiles();
587         }
588         ValueProfile* getFromAllValueProfiles(unsigned index)
589         {
590             if (index < numberOfArgumentValueProfiles())
591                 return valueProfileForArgument(index);
592             return valueProfile(index - numberOfArgumentValueProfiles());
593         }
594         
595         RareCaseProfile* addRareCaseProfile(int bytecodeOffset)
596         {
597             m_rareCaseProfiles.append(RareCaseProfile(bytecodeOffset));
598             return &m_rareCaseProfiles.last();
599         }
600         unsigned numberOfRareCaseProfiles() { return m_rareCaseProfiles.size(); }
601         RareCaseProfile* rareCaseProfile(int index) { return &m_rareCaseProfiles[index]; }
602         RareCaseProfile* rareCaseProfileForBytecodeOffset(int bytecodeOffset)
603         {
604             return WTF::genericBinarySearch<RareCaseProfile, int, getRareCaseProfileBytecodeOffset>(m_rareCaseProfiles, m_rareCaseProfiles.size(), bytecodeOffset);
605         }
606         
607         bool likelyToTakeSlowCase(int bytecodeOffset)
608         {
609             if (!numberOfRareCaseProfiles())
610                 return false;
611             unsigned value = rareCaseProfileForBytecodeOffset(bytecodeOffset)->m_counter;
612             return value >= Options::likelyToTakeSlowCaseMinimumCount && static_cast<double>(value) / m_executionEntryCount >= Options::likelyToTakeSlowCaseThreshold;
613         }
614         
615         bool couldTakeSlowCase(int bytecodeOffset)
616         {
617             if (!numberOfRareCaseProfiles())
618                 return false;
619             unsigned value = rareCaseProfileForBytecodeOffset(bytecodeOffset)->m_counter;
620             return value >= Options::couldTakeSlowCaseMinimumCount && static_cast<double>(value) / m_executionEntryCount >= Options::couldTakeSlowCaseThreshold;
621         }
622         
623         RareCaseProfile* addSpecialFastCaseProfile(int bytecodeOffset)
624         {
625             m_specialFastCaseProfiles.append(RareCaseProfile(bytecodeOffset));
626             return &m_specialFastCaseProfiles.last();
627         }
628         unsigned numberOfSpecialFastCaseProfiles() { return m_specialFastCaseProfiles.size(); }
629         RareCaseProfile* specialFastCaseProfile(int index) { return &m_specialFastCaseProfiles[index]; }
630         RareCaseProfile* specialFastCaseProfileForBytecodeOffset(int bytecodeOffset)
631         {
632             return WTF::genericBinarySearch<RareCaseProfile, int, getRareCaseProfileBytecodeOffset>(m_specialFastCaseProfiles, m_specialFastCaseProfiles.size(), bytecodeOffset);
633         }
634         
635         bool likelyToTakeSpecialFastCase(int bytecodeOffset)
636         {
637             if (!numberOfRareCaseProfiles())
638                 return false;
639             unsigned specialFastCaseCount = specialFastCaseProfileForBytecodeOffset(bytecodeOffset)->m_counter;
640             return specialFastCaseCount >= Options::likelyToTakeSlowCaseMinimumCount && static_cast<double>(specialFastCaseCount) / m_executionEntryCount >= Options::likelyToTakeSlowCaseThreshold;
641         }
642         
643         bool likelyToTakeDeepestSlowCase(int bytecodeOffset)
644         {
645             if (!numberOfRareCaseProfiles())
646                 return false;
647             unsigned slowCaseCount = rareCaseProfileForBytecodeOffset(bytecodeOffset)->m_counter;
648             unsigned specialFastCaseCount = specialFastCaseProfileForBytecodeOffset(bytecodeOffset)->m_counter;
649             unsigned value = slowCaseCount - specialFastCaseCount;
650             return value >= Options::likelyToTakeSlowCaseMinimumCount && static_cast<double>(value) / m_executionEntryCount >= Options::likelyToTakeSlowCaseThreshold;
651         }
652         
653         bool likelyToTakeAnySlowCase(int bytecodeOffset)
654         {
655             if (!numberOfRareCaseProfiles())
656                 return false;
657             unsigned slowCaseCount = rareCaseProfileForBytecodeOffset(bytecodeOffset)->m_counter;
658             unsigned specialFastCaseCount = specialFastCaseProfileForBytecodeOffset(bytecodeOffset)->m_counter;
659             unsigned value = slowCaseCount + specialFastCaseCount;
660             return value >= Options::likelyToTakeSlowCaseMinimumCount && static_cast<double>(value) / m_executionEntryCount >= Options::likelyToTakeSlowCaseThreshold;
661         }
662         
663         unsigned executionEntryCount() const { return m_executionEntryCount; }
664 #endif
665
666         unsigned globalResolveInfoCount() const
667         {
668 #if ENABLE(JIT)    
669             if (m_globalData->canUseJIT())
670                 return m_globalResolveInfos.size();
671 #endif
672             return 0;
673         }
674
675         // Exception handling support
676
677         size_t numberOfExceptionHandlers() const { return m_rareData ? m_rareData->m_exceptionHandlers.size() : 0; }
678         void addExceptionHandler(const HandlerInfo& hanler) { createRareDataIfNecessary(); return m_rareData->m_exceptionHandlers.append(hanler); }
679         HandlerInfo& exceptionHandler(int index) { ASSERT(m_rareData); return m_rareData->m_exceptionHandlers[index]; }
680
681         void addExpressionInfo(const ExpressionRangeInfo& expressionInfo)
682         {
683             createRareDataIfNecessary();
684             m_rareData->m_expressionInfo.append(expressionInfo);
685         }
686
687         void addLineInfo(unsigned bytecodeOffset, int lineNo)
688         {
689             createRareDataIfNecessary();
690             Vector<LineInfo>& lineInfo = m_rareData->m_lineInfo;
691             if (!lineInfo.size() || lineInfo.last().lineNumber != lineNo) {
692                 LineInfo info = { bytecodeOffset, lineNo };
693                 lineInfo.append(info);
694             }
695         }
696
697         bool hasExpressionInfo() { return m_rareData && m_rareData->m_expressionInfo.size(); }
698         bool hasLineInfo() { return m_rareData && m_rareData->m_lineInfo.size(); }
699         //  We only generate exception handling info if the user is debugging
700         // (and may want line number info), or if the function contains exception handler.
701         bool needsCallReturnIndices()
702         {
703             return m_rareData &&
704                 (m_rareData->m_expressionInfo.size() || m_rareData->m_lineInfo.size() || m_rareData->m_exceptionHandlers.size());
705         }
706
707 #if ENABLE(JIT)
708         Vector<CallReturnOffsetToBytecodeOffset>& callReturnIndexVector()
709         {
710             createRareDataIfNecessary();
711             return m_rareData->m_callReturnIndexVector;
712         }
713 #endif
714
715 #if ENABLE(DFG_JIT)
716         SegmentedVector<InlineCallFrame, 4>& inlineCallFrames()
717         {
718             createRareDataIfNecessary();
719             return m_rareData->m_inlineCallFrames;
720         }
721         
722         Vector<CodeOriginAtCallReturnOffset>& codeOrigins()
723         {
724             createRareDataIfNecessary();
725             return m_rareData->m_codeOrigins;
726         }
727         
728         // Having code origins implies that there has been some inlining.
729         bool hasCodeOrigins()
730         {
731             return m_rareData && !!m_rareData->m_codeOrigins.size();
732         }
733         
734         bool codeOriginForReturn(ReturnAddressPtr returnAddress, CodeOrigin& codeOrigin)
735         {
736             if (!hasCodeOrigins())
737                 return false;
738             unsigned offset = getJITCode().offsetOf(returnAddress.value());
739             CodeOriginAtCallReturnOffset* entry = binarySearch<CodeOriginAtCallReturnOffset, unsigned, getCallReturnOffsetForCodeOrigin>(codeOrigins().begin(), codeOrigins().size(), offset, WTF::KeyMustNotBePresentInArray);
740             if (entry->callReturnOffset != offset)
741                 return false;
742             codeOrigin = entry->codeOrigin;
743             return true;
744         }
745         
746         CodeOrigin codeOrigin(unsigned index)
747         {
748             ASSERT(m_rareData);
749             return m_rareData->m_codeOrigins[index].codeOrigin;
750         }
751         
752         bool addFrequentExitSite(const DFG::FrequentExitSite& site)
753         {
754             ASSERT(JITCode::isBaselineCode(getJITType()));
755             return m_exitProfile.add(site);
756         }
757
758         DFG::ExitProfile& exitProfile() { return m_exitProfile; }
759         
760         CompressedLazyOperandValueProfileHolder& lazyOperandValueProfiles()
761         {
762             return m_lazyOperandValueProfiles;
763         }
764 #endif
765
766         // Constant Pool
767
768         size_t numberOfIdentifiers() const { return m_identifiers.size(); }
769         void addIdentifier(const Identifier& i) { return m_identifiers.append(i); }
770         Identifier& identifier(int index) { return m_identifiers[index]; }
771
772         size_t numberOfConstantRegisters() const { return m_constantRegisters.size(); }
773         unsigned addConstant(JSValue v)
774         {
775             unsigned result = m_constantRegisters.size();
776             m_constantRegisters.append(WriteBarrier<Unknown>());
777             m_constantRegisters.last().set(m_globalObject->globalData(), m_ownerExecutable.get(), v);
778             return result;
779         }
780         unsigned addOrFindConstant(JSValue);
781         WriteBarrier<Unknown>& constantRegister(int index) { return m_constantRegisters[index - FirstConstantRegisterIndex]; }
782         ALWAYS_INLINE bool isConstantRegisterIndex(int index) const { return index >= FirstConstantRegisterIndex; }
783         ALWAYS_INLINE JSValue getConstant(int index) const { return m_constantRegisters[index - FirstConstantRegisterIndex].get(); }
784
785         unsigned addFunctionDecl(FunctionExecutable* n)
786         {
787             unsigned size = m_functionDecls.size();
788             m_functionDecls.append(WriteBarrier<FunctionExecutable>());
789             m_functionDecls.last().set(m_globalObject->globalData(), m_ownerExecutable.get(), n);
790             return size;
791         }
792         FunctionExecutable* functionDecl(int index) { return m_functionDecls[index].get(); }
793         int numberOfFunctionDecls() { return m_functionDecls.size(); }
794         unsigned addFunctionExpr(FunctionExecutable* n)
795         {
796             unsigned size = m_functionExprs.size();
797             m_functionExprs.append(WriteBarrier<FunctionExecutable>());
798             m_functionExprs.last().set(m_globalObject->globalData(), m_ownerExecutable.get(), n);
799             return size;
800         }
801         FunctionExecutable* functionExpr(int index) { return m_functionExprs[index].get(); }
802
803         unsigned addRegExp(RegExp* r)
804         {
805             createRareDataIfNecessary();
806             unsigned size = m_rareData->m_regexps.size();
807             m_rareData->m_regexps.append(WriteBarrier<RegExp>(*m_globalData, ownerExecutable(), r));
808             return size;
809         }
810         unsigned numberOfRegExps() const
811         {
812             if (!m_rareData)
813                 return 0;
814             return m_rareData->m_regexps.size();
815         }
816         RegExp* regexp(int index) const { ASSERT(m_rareData); return m_rareData->m_regexps[index].get(); }
817
818         unsigned addConstantBuffer(unsigned length)
819         {
820             createRareDataIfNecessary();
821             unsigned size = m_rareData->m_constantBuffers.size();
822             m_rareData->m_constantBuffers.append(Vector<JSValue>(length));
823             return size;
824         }
825
826         JSValue* constantBuffer(unsigned index)
827         {
828             ASSERT(m_rareData);
829             return m_rareData->m_constantBuffers[index].data();
830         }
831
832         JSGlobalObject* globalObject() { return m_globalObject.get(); }
833         
834         JSGlobalObject* globalObjectFor(CodeOrigin codeOrigin)
835         {
836             if (!codeOrigin.inlineCallFrame)
837                 return globalObject();
838             // FIXME: if we ever inline based on executable not function, this code will need to change.
839             return codeOrigin.inlineCallFrame->callee->scope()->globalObject.get();
840         }
841
842         // Jump Tables
843
844         size_t numberOfImmediateSwitchJumpTables() const { return m_rareData ? m_rareData->m_immediateSwitchJumpTables.size() : 0; }
845         SimpleJumpTable& addImmediateSwitchJumpTable() { createRareDataIfNecessary(); m_rareData->m_immediateSwitchJumpTables.append(SimpleJumpTable()); return m_rareData->m_immediateSwitchJumpTables.last(); }
846         SimpleJumpTable& immediateSwitchJumpTable(int tableIndex) { ASSERT(m_rareData); return m_rareData->m_immediateSwitchJumpTables[tableIndex]; }
847
848         size_t numberOfCharacterSwitchJumpTables() const { return m_rareData ? m_rareData->m_characterSwitchJumpTables.size() : 0; }
849         SimpleJumpTable& addCharacterSwitchJumpTable() { createRareDataIfNecessary(); m_rareData->m_characterSwitchJumpTables.append(SimpleJumpTable()); return m_rareData->m_characterSwitchJumpTables.last(); }
850         SimpleJumpTable& characterSwitchJumpTable(int tableIndex) { ASSERT(m_rareData); return m_rareData->m_characterSwitchJumpTables[tableIndex]; }
851
852         size_t numberOfStringSwitchJumpTables() const { return m_rareData ? m_rareData->m_stringSwitchJumpTables.size() : 0; }
853         StringJumpTable& addStringSwitchJumpTable() { createRareDataIfNecessary(); m_rareData->m_stringSwitchJumpTables.append(StringJumpTable()); return m_rareData->m_stringSwitchJumpTables.last(); }
854         StringJumpTable& stringSwitchJumpTable(int tableIndex) { ASSERT(m_rareData); return m_rareData->m_stringSwitchJumpTables[tableIndex]; }
855
856
857         SymbolTable* symbolTable() { return m_symbolTable; }
858         SharedSymbolTable* sharedSymbolTable() { ASSERT(m_codeType == FunctionCode); return static_cast<SharedSymbolTable*>(m_symbolTable); }
859
860         EvalCodeCache& evalCodeCache() { createRareDataIfNecessary(); return m_rareData->m_evalCodeCache; }
861
862         enum ShrinkMode {
863             // Shrink prior to generating machine code that may point directly into vectors.
864             EarlyShrink,
865             
866             // Shrink after generating machine code, and after possibly creating new vectors
867             // and appending to others. At this time it is not safe to shrink certain vectors
868             // because we would have generated machine code that references them directly.
869             LateShrink
870         };
871         void shrinkToFit(ShrinkMode);
872         
873         void copyPostParseDataFrom(CodeBlock* alternative);
874         void copyPostParseDataFromAlternative();
875         
876         // Functions for controlling when JITting kicks in, in a mixed mode
877         // execution world.
878         
879         bool checkIfJITThresholdReached()
880         {
881             return m_llintExecuteCounter.checkIfThresholdCrossedAndSet(this);
882         }
883         
884         void dontJITAnytimeSoon()
885         {
886             m_llintExecuteCounter.deferIndefinitely();
887         }
888         
889         void jitAfterWarmUp()
890         {
891             m_llintExecuteCounter.setNewThreshold(Options::thresholdForJITAfterWarmUp, this);
892         }
893         
894         void jitSoon()
895         {
896             m_llintExecuteCounter.setNewThreshold(Options::thresholdForJITSoon, this);
897         }
898         
899         int32_t llintExecuteCounter() const
900         {
901             return m_llintExecuteCounter.m_counter;
902         }
903         
904         // Functions for controlling when tiered compilation kicks in. This
905         // controls both when the optimizing compiler is invoked and when OSR
906         // entry happens. Two triggers exist: the loop trigger and the return
907         // trigger. In either case, when an addition to m_jitExecuteCounter
908         // causes it to become non-negative, the optimizing compiler is
909         // invoked. This includes a fast check to see if this CodeBlock has
910         // already been optimized (i.e. replacement() returns a CodeBlock
911         // that was optimized with a higher tier JIT than this one). In the
912         // case of the loop trigger, if the optimized compilation succeeds
913         // (or has already succeeded in the past) then OSR is attempted to
914         // redirect program flow into the optimized code.
915         
916         // These functions are called from within the optimization triggers,
917         // and are used as a single point at which we define the heuristics
918         // for how much warm-up is mandated before the next optimization
919         // trigger files. All CodeBlocks start out with optimizeAfterWarmUp(),
920         // as this is called from the CodeBlock constructor.
921         
922         // When we observe a lot of speculation failures, we trigger a
923         // reoptimization. But each time, we increase the optimization trigger
924         // to avoid thrashing.
925         unsigned reoptimizationRetryCounter() const
926         {
927             ASSERT(m_reoptimizationRetryCounter <= Options::reoptimizationRetryCounterMax);
928             return m_reoptimizationRetryCounter;
929         }
930         
931         void countReoptimization()
932         {
933             m_reoptimizationRetryCounter++;
934             if (m_reoptimizationRetryCounter > Options::reoptimizationRetryCounterMax)
935                 m_reoptimizationRetryCounter = Options::reoptimizationRetryCounterMax;
936         }
937         
938         int32_t counterValueForOptimizeAfterWarmUp()
939         {
940             return Options::thresholdForOptimizeAfterWarmUp << reoptimizationRetryCounter();
941         }
942         
943         int32_t counterValueForOptimizeAfterLongWarmUp()
944         {
945             return Options::thresholdForOptimizeAfterLongWarmUp << reoptimizationRetryCounter();
946         }
947         
948         int32_t* addressOfJITExecuteCounter()
949         {
950             return &m_jitExecuteCounter.m_counter;
951         }
952         
953         static ptrdiff_t offsetOfJITExecuteCounter() { return OBJECT_OFFSETOF(CodeBlock, m_jitExecuteCounter) + OBJECT_OFFSETOF(ExecutionCounter, m_counter); }
954         static ptrdiff_t offsetOfJITExecutionActiveThreshold() { return OBJECT_OFFSETOF(CodeBlock, m_jitExecuteCounter) + OBJECT_OFFSETOF(ExecutionCounter, m_activeThreshold); }
955         static ptrdiff_t offsetOfJITExecutionTotalCount() { return OBJECT_OFFSETOF(CodeBlock, m_jitExecuteCounter) + OBJECT_OFFSETOF(ExecutionCounter, m_totalCount); }
956
957         int32_t jitExecuteCounter() const { return m_jitExecuteCounter.m_counter; }
958         
959         unsigned optimizationDelayCounter() const { return m_optimizationDelayCounter; }
960         
961         // Check if the optimization threshold has been reached, and if not,
962         // adjust the heuristics accordingly. Returns true if the threshold has
963         // been reached.
964         bool checkIfOptimizationThresholdReached()
965         {
966             return m_jitExecuteCounter.checkIfThresholdCrossedAndSet(this);
967         }
968         
969         // Call this to force the next optimization trigger to fire. This is
970         // rarely wise, since optimization triggers are typically more
971         // expensive than executing baseline code.
972         void optimizeNextInvocation()
973         {
974             m_jitExecuteCounter.setNewThreshold(0, this);
975         }
976         
977         // Call this to prevent optimization from happening again. Note that
978         // optimization will still happen after roughly 2^29 invocations,
979         // so this is really meant to delay that as much as possible. This
980         // is called if optimization failed, and we expect it to fail in
981         // the future as well.
982         void dontOptimizeAnytimeSoon()
983         {
984             m_jitExecuteCounter.deferIndefinitely();
985         }
986         
987         // Call this to reinitialize the counter to its starting state,
988         // forcing a warm-up to happen before the next optimization trigger
989         // fires. This is called in the CodeBlock constructor. It also
990         // makes sense to call this if an OSR exit occurred. Note that
991         // OSR exit code is code generated, so the value of the execute
992         // counter that this corresponds to is also available directly.
993         void optimizeAfterWarmUp()
994         {
995             m_jitExecuteCounter.setNewThreshold(counterValueForOptimizeAfterWarmUp(), this);
996         }
997         
998         // Call this to force an optimization trigger to fire only after
999         // a lot of warm-up.
1000         void optimizeAfterLongWarmUp()
1001         {
1002             m_jitExecuteCounter.setNewThreshold(counterValueForOptimizeAfterLongWarmUp(), this);
1003         }
1004         
1005         // Call this to cause an optimization trigger to fire soon, but
1006         // not necessarily the next one. This makes sense if optimization
1007         // succeeds. Successfuly optimization means that all calls are
1008         // relinked to the optimized code, so this only affects call
1009         // frames that are still executing this CodeBlock. The value here
1010         // is tuned to strike a balance between the cost of OSR entry
1011         // (which is too high to warrant making every loop back edge to
1012         // trigger OSR immediately) and the cost of executing baseline
1013         // code (which is high enough that we don't necessarily want to
1014         // have a full warm-up). The intuition for calling this instead of
1015         // optimizeNextInvocation() is for the case of recursive functions
1016         // with loops. Consider that there may be N call frames of some
1017         // recursive function, for a reasonably large value of N. The top
1018         // one triggers optimization, and then returns, and then all of
1019         // the others return. We don't want optimization to be triggered on
1020         // each return, as that would be superfluous. It only makes sense
1021         // to trigger optimization if one of those functions becomes hot
1022         // in the baseline code.
1023         void optimizeSoon()
1024         {
1025             m_jitExecuteCounter.setNewThreshold(Options::thresholdForOptimizeSoon << reoptimizationRetryCounter(), this);
1026         }
1027         
1028         // The speculative JIT tracks its success rate, so that we can
1029         // decide when to reoptimize. It's interesting to note that these
1030         // counters may overflow without any protection. The success
1031         // counter will overflow before the fail one does, becuase the
1032         // fail one is used as a trigger to reoptimize. So the worst case
1033         // is that the success counter overflows and we reoptimize without
1034         // needing to. But this is harmless. If a method really did
1035         // execute 2^32 times then compiling it again probably won't hurt
1036         // anyone.
1037         
1038         void countSpeculationSuccess()
1039         {
1040             m_speculativeSuccessCounter++;
1041         }
1042         
1043         void countSpeculationFailure()
1044         {
1045             m_speculativeFailCounter++;
1046         }
1047         
1048         uint32_t speculativeSuccessCounter() const { return m_speculativeSuccessCounter; }
1049         uint32_t speculativeFailCounter() const { return m_speculativeFailCounter; }
1050         uint32_t forcedOSRExitCounter() const { return m_forcedOSRExitCounter; }
1051         
1052         uint32_t* addressOfSpeculativeSuccessCounter() { return &m_speculativeSuccessCounter; }
1053         uint32_t* addressOfSpeculativeFailCounter() { return &m_speculativeFailCounter; }
1054         uint32_t* addressOfForcedOSRExitCounter() { return &m_forcedOSRExitCounter; }
1055         
1056         static ptrdiff_t offsetOfSpeculativeSuccessCounter() { return OBJECT_OFFSETOF(CodeBlock, m_speculativeSuccessCounter); }
1057         static ptrdiff_t offsetOfSpeculativeFailCounter() { return OBJECT_OFFSETOF(CodeBlock, m_speculativeFailCounter); }
1058         static ptrdiff_t offsetOfForcedOSRExitCounter() { return OBJECT_OFFSETOF(CodeBlock, m_forcedOSRExitCounter); }
1059
1060 #if ENABLE(JIT)
1061         // The number of failures that triggers the use of the ratio.
1062         unsigned largeFailCountThreshold() { return Options::largeFailCountThresholdBase << baselineVersion()->reoptimizationRetryCounter(); }
1063         unsigned largeFailCountThresholdForLoop() { return Options::largeFailCountThresholdBaseForLoop << baselineVersion()->reoptimizationRetryCounter(); }
1064
1065         bool shouldReoptimizeNow()
1066         {
1067             return (Options::desiredSpeculativeSuccessFailRatio *
1068                         speculativeFailCounter() >= speculativeSuccessCounter()
1069                     && speculativeFailCounter() >= largeFailCountThreshold())
1070                 || forcedOSRExitCounter() >=
1071                        Options::forcedOSRExitCountForReoptimization;
1072         }
1073
1074         bool shouldReoptimizeFromLoopNow()
1075         {
1076             return (Options::desiredSpeculativeSuccessFailRatio *
1077                         speculativeFailCounter() >= speculativeSuccessCounter()
1078                     && speculativeFailCounter() >= largeFailCountThresholdForLoop())
1079                 || forcedOSRExitCounter() >=
1080                        Options::forcedOSRExitCountForReoptimization;
1081         }
1082 #endif
1083
1084 #if ENABLE(VALUE_PROFILER)
1085         bool shouldOptimizeNow();
1086 #else
1087         bool shouldOptimizeNow() { return false; }
1088 #endif
1089         
1090 #if ENABLE(JIT)
1091         void reoptimize()
1092         {
1093             ASSERT(replacement() != this);
1094             ASSERT(replacement()->alternative() == this);
1095             replacement()->tallyFrequentExitSites();
1096             replacement()->jettison();
1097             countReoptimization();
1098             optimizeAfterWarmUp();
1099         }
1100 #endif
1101
1102 #if ENABLE(VERBOSE_VALUE_PROFILE)
1103         void dumpValueProfiles();
1104 #endif
1105         
1106         // FIXME: Make these remaining members private.
1107
1108         int m_numCalleeRegisters;
1109         int m_numVars;
1110         int m_numCapturedVars;
1111         bool m_isConstructor;
1112
1113     protected:
1114 #if ENABLE(JIT)
1115         virtual bool jitCompileImpl(ExecState*) = 0;
1116 #endif
1117         virtual void visitWeakReferences(SlotVisitor&);
1118         virtual void finalizeUnconditionally();
1119         
1120     private:
1121         friend class DFGCodeBlocks;
1122         
1123 #if ENABLE(DFG_JIT)
1124         void tallyFrequentExitSites();
1125 #else
1126         void tallyFrequentExitSites() { }
1127 #endif
1128         
1129         void dump(ExecState*, const Vector<Instruction>::const_iterator& begin, Vector<Instruction>::const_iterator&);
1130
1131         CString registerName(ExecState*, int r) const;
1132         void printUnaryOp(ExecState*, int location, Vector<Instruction>::const_iterator&, const char* op);
1133         void printBinaryOp(ExecState*, int location, Vector<Instruction>::const_iterator&, const char* op);
1134         void printConditionalJump(ExecState*, const Vector<Instruction>::const_iterator&, Vector<Instruction>::const_iterator&, int location, const char* op);
1135         void printGetByIdOp(ExecState*, int location, Vector<Instruction>::const_iterator&);
1136         void printGetByIdCacheStatus(ExecState*, int location);
1137         enum CacheDumpMode { DumpCaches, DontDumpCaches };
1138         void printCallOp(ExecState*, int location, Vector<Instruction>::const_iterator&, const char* op, CacheDumpMode);
1139         void printPutByIdOp(ExecState*, int location, Vector<Instruction>::const_iterator&, const char* op);
1140         void visitStructures(SlotVisitor&, Instruction* vPC);
1141         
1142 #if ENABLE(DFG_JIT)
1143         bool shouldImmediatelyAssumeLivenessDuringScan()
1144         {
1145             // Null m_dfgData means that this is a baseline JIT CodeBlock. Baseline JIT
1146             // CodeBlocks don't need to be jettisoned when their weak references go
1147             // stale. So if a basline JIT CodeBlock gets scanned, we can assume that
1148             // this means that it's live.
1149             if (!m_dfgData)
1150                 return true;
1151             
1152             // For simplicity, we don't attempt to jettison code blocks during GC if
1153             // they are executing. Instead we strongly mark their weak references to
1154             // allow them to continue to execute soundly.
1155             if (m_dfgData->mayBeExecuting)
1156                 return true;
1157
1158             return false;
1159         }
1160 #else
1161         bool shouldImmediatelyAssumeLivenessDuringScan() { return true; }
1162 #endif
1163         
1164         void performTracingFixpointIteration(SlotVisitor&);
1165         
1166         void stronglyVisitStrongReferences(SlotVisitor&);
1167         void stronglyVisitWeakReferences(SlotVisitor&);
1168
1169         void createRareDataIfNecessary()
1170         {
1171             if (!m_rareData)
1172                 m_rareData = adoptPtr(new RareData);
1173         }
1174         
1175         int m_numParameters;
1176
1177         WriteBarrier<ScriptExecutable> m_ownerExecutable;
1178         JSGlobalData* m_globalData;
1179
1180         RefCountedArray<Instruction> m_instructions;
1181
1182         int m_thisRegister;
1183         int m_argumentsRegister;
1184         int m_activationRegister;
1185
1186         bool m_needsFullScopeChain;
1187         bool m_usesEval;
1188         bool m_isNumericCompareFunction;
1189         bool m_isStrictMode;
1190
1191         CodeType m_codeType;
1192
1193         RefPtr<SourceProvider> m_source;
1194         unsigned m_sourceOffset;
1195
1196         Vector<unsigned> m_propertyAccessInstructions;
1197         Vector<unsigned> m_globalResolveInstructions;
1198 #if ENABLE(LLINT)
1199         SegmentedVector<LLIntCallLinkInfo, 8> m_llintCallLinkInfos;
1200         SentinelLinkedList<LLIntCallLinkInfo, BasicRawSentinelNode<LLIntCallLinkInfo> > m_incomingLLIntCalls;
1201 #endif
1202 #if ENABLE(JIT)
1203         Vector<StructureStubInfo> m_structureStubInfos;
1204         Vector<GlobalResolveInfo> m_globalResolveInfos;
1205         Vector<CallLinkInfo> m_callLinkInfos;
1206         Vector<MethodCallLinkInfo> m_methodCallLinkInfos;
1207         JITCode m_jitCode;
1208         MacroAssemblerCodePtr m_jitCodeWithArityCheck;
1209         SentinelLinkedList<CallLinkInfo, BasicRawSentinelNode<CallLinkInfo> > m_incomingCalls;
1210 #endif
1211 #if ENABLE(DFG_JIT) || ENABLE(LLINT)
1212         OwnPtr<CompactJITCodeMap> m_jitCodeMap;
1213 #endif
1214 #if ENABLE(DFG_JIT)
1215         struct WeakReferenceTransition {
1216             WeakReferenceTransition() { }
1217             
1218             WeakReferenceTransition(JSGlobalData& globalData, JSCell* owner, JSCell* codeOrigin, JSCell* from, JSCell* to)
1219                 : m_from(globalData, owner, from)
1220                 , m_to(globalData, owner, to)
1221             {
1222                 if (!!codeOrigin)
1223                     m_codeOrigin.set(globalData, owner, codeOrigin);
1224             }
1225
1226             WriteBarrier<JSCell> m_codeOrigin;
1227             WriteBarrier<JSCell> m_from;
1228             WriteBarrier<JSCell> m_to;
1229         };
1230         
1231         struct DFGData {
1232             DFGData()
1233                 : mayBeExecuting(false)
1234                 , isJettisoned(false)
1235             {
1236             }
1237             
1238             Vector<DFG::OSREntryData> osrEntry;
1239             SegmentedVector<DFG::OSRExit, 8> osrExit;
1240             Vector<DFG::SpeculationRecovery> speculationRecovery;
1241             Vector<WeakReferenceTransition> transitions;
1242             Vector<WriteBarrier<JSCell> > weakReferences;
1243             bool mayBeExecuting;
1244             bool isJettisoned;
1245             bool livenessHasBeenProved; // Initialized and used on every GC.
1246             bool allTransitionsHaveBeenMarked; // Initialized and used on every GC.
1247             unsigned visitAggregateHasBeenCalled; // Unsigned to make it work seamlessly with the broadest set of CAS implementations.
1248         };
1249         
1250         OwnPtr<DFGData> m_dfgData;
1251         
1252         // This is relevant to non-DFG code blocks that serve as the profiled code block
1253         // for DFG code blocks.
1254         DFG::ExitProfile m_exitProfile;
1255         CompressedLazyOperandValueProfileHolder m_lazyOperandValueProfiles;
1256 #endif
1257 #if ENABLE(VALUE_PROFILER)
1258         Vector<ValueProfile> m_argumentValueProfiles;
1259         SegmentedVector<ValueProfile, 8> m_valueProfiles;
1260         SegmentedVector<RareCaseProfile, 8> m_rareCaseProfiles;
1261         SegmentedVector<RareCaseProfile, 8> m_specialFastCaseProfiles;
1262         unsigned m_executionEntryCount;
1263 #endif
1264
1265         Vector<unsigned> m_jumpTargets;
1266         Vector<unsigned> m_loopTargets;
1267
1268         // Constant Pool
1269         Vector<Identifier> m_identifiers;
1270         COMPILE_ASSERT(sizeof(Register) == sizeof(WriteBarrier<Unknown>), Register_must_be_same_size_as_WriteBarrier_Unknown);
1271         Vector<WriteBarrier<Unknown> > m_constantRegisters;
1272         Vector<WriteBarrier<FunctionExecutable> > m_functionDecls;
1273         Vector<WriteBarrier<FunctionExecutable> > m_functionExprs;
1274
1275         SymbolTable* m_symbolTable;
1276
1277         OwnPtr<CodeBlock> m_alternative;
1278         
1279         ExecutionCounter m_llintExecuteCounter;
1280         
1281         ExecutionCounter m_jitExecuteCounter;
1282         int32_t m_totalJITExecutions;
1283         uint32_t m_speculativeSuccessCounter;
1284         uint32_t m_speculativeFailCounter;
1285         uint32_t m_forcedOSRExitCounter;
1286         uint16_t m_optimizationDelayCounter;
1287         uint16_t m_reoptimizationRetryCounter;
1288         
1289         struct RareData {
1290            WTF_MAKE_FAST_ALLOCATED;
1291         public:
1292             Vector<HandlerInfo> m_exceptionHandlers;
1293
1294             // Rare Constants
1295             Vector<WriteBarrier<RegExp> > m_regexps;
1296
1297             // Buffers used for large array literals
1298             Vector<Vector<JSValue> > m_constantBuffers;
1299             
1300             // Jump Tables
1301             Vector<SimpleJumpTable> m_immediateSwitchJumpTables;
1302             Vector<SimpleJumpTable> m_characterSwitchJumpTables;
1303             Vector<StringJumpTable> m_stringSwitchJumpTables;
1304
1305             EvalCodeCache m_evalCodeCache;
1306
1307             // Expression info - present if debugging.
1308             Vector<ExpressionRangeInfo> m_expressionInfo;
1309             // Line info - present if profiling or debugging.
1310             Vector<LineInfo> m_lineInfo;
1311 #if ENABLE(JIT)
1312             Vector<CallReturnOffsetToBytecodeOffset> m_callReturnIndexVector;
1313 #endif
1314 #if ENABLE(DFG_JIT)
1315             SegmentedVector<InlineCallFrame, 4> m_inlineCallFrames;
1316             Vector<CodeOriginAtCallReturnOffset> m_codeOrigins;
1317 #endif
1318         };
1319 #if COMPILER(MSVC)
1320         friend void WTF::deleteOwnedPtr<RareData>(RareData*);
1321 #endif
1322         OwnPtr<RareData> m_rareData;
1323 #if ENABLE(JIT)
1324         DFG::CapabilityLevel m_canCompileWithDFGState;
1325 #endif
1326     };
1327
1328     // Program code is not marked by any function, so we make the global object
1329     // responsible for marking it.
1330
1331     class GlobalCodeBlock : public CodeBlock {
1332     protected:
1333         GlobalCodeBlock(CopyParsedBlockTag, GlobalCodeBlock& other)
1334             : CodeBlock(CopyParsedBlock, other, &m_unsharedSymbolTable)
1335             , m_unsharedSymbolTable(other.m_unsharedSymbolTable)
1336         {
1337         }
1338         
1339         GlobalCodeBlock(ScriptExecutable* ownerExecutable, CodeType codeType, JSGlobalObject* globalObject, PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset, PassOwnPtr<CodeBlock> alternative)
1340             : CodeBlock(ownerExecutable, codeType, globalObject, sourceProvider, sourceOffset, &m_unsharedSymbolTable, false, alternative)
1341         {
1342         }
1343
1344     private:
1345         SymbolTable m_unsharedSymbolTable;
1346     };
1347
1348     class ProgramCodeBlock : public GlobalCodeBlock {
1349     public:
1350         ProgramCodeBlock(CopyParsedBlockTag, ProgramCodeBlock& other)
1351             : GlobalCodeBlock(CopyParsedBlock, other)
1352         {
1353         }
1354
1355         ProgramCodeBlock(ProgramExecutable* ownerExecutable, CodeType codeType, JSGlobalObject* globalObject, PassRefPtr<SourceProvider> sourceProvider, PassOwnPtr<CodeBlock> alternative)
1356             : GlobalCodeBlock(ownerExecutable, codeType, globalObject, sourceProvider, 0, alternative)
1357         {
1358         }
1359         
1360 #if ENABLE(JIT)
1361     protected:
1362         virtual JSObject* compileOptimized(ExecState*, ScopeChainNode*);
1363         virtual void jettison();
1364         virtual bool jitCompileImpl(ExecState*);
1365         virtual CodeBlock* replacement();
1366         virtual DFG::CapabilityLevel canCompileWithDFGInternal();
1367 #endif
1368     };
1369
1370     class EvalCodeBlock : public GlobalCodeBlock {
1371     public:
1372         EvalCodeBlock(CopyParsedBlockTag, EvalCodeBlock& other)
1373             : GlobalCodeBlock(CopyParsedBlock, other)
1374             , m_baseScopeDepth(other.m_baseScopeDepth)
1375             , m_variables(other.m_variables)
1376         {
1377         }
1378         
1379         EvalCodeBlock(EvalExecutable* ownerExecutable, JSGlobalObject* globalObject, PassRefPtr<SourceProvider> sourceProvider, int baseScopeDepth, PassOwnPtr<CodeBlock> alternative)
1380             : GlobalCodeBlock(ownerExecutable, EvalCode, globalObject, sourceProvider, 0, alternative)
1381             , m_baseScopeDepth(baseScopeDepth)
1382         {
1383         }
1384
1385         int baseScopeDepth() const { return m_baseScopeDepth; }
1386
1387         const Identifier& variable(unsigned index) { return m_variables[index]; }
1388         unsigned numVariables() { return m_variables.size(); }
1389         void adoptVariables(Vector<Identifier>& variables)
1390         {
1391             ASSERT(m_variables.isEmpty());
1392             m_variables.swap(variables);
1393         }
1394         
1395 #if ENABLE(JIT)
1396     protected:
1397         virtual JSObject* compileOptimized(ExecState*, ScopeChainNode*);
1398         virtual void jettison();
1399         virtual bool jitCompileImpl(ExecState*);
1400         virtual CodeBlock* replacement();
1401         virtual DFG::CapabilityLevel canCompileWithDFGInternal();
1402 #endif
1403
1404     private:
1405         int m_baseScopeDepth;
1406         Vector<Identifier> m_variables;
1407     };
1408
1409     class FunctionCodeBlock : public CodeBlock {
1410     public:
1411         FunctionCodeBlock(CopyParsedBlockTag, FunctionCodeBlock& other)
1412             : CodeBlock(CopyParsedBlock, other, other.sharedSymbolTable())
1413         {
1414             // The fact that we have to do this is yucky, but is necessary because of the
1415             // class hierarchy issues described in the comment block for the main
1416             // constructor, below.
1417             sharedSymbolTable()->ref();
1418         }
1419
1420         // Rather than using the usual RefCounted::create idiom for SharedSymbolTable we just use new
1421         // as we need to initialise the CodeBlock before we could initialise any RefPtr to hold the shared
1422         // symbol table, so we just pass as a raw pointer with a ref count of 1.  We then manually deref
1423         // in the destructor.
1424         FunctionCodeBlock(FunctionExecutable* ownerExecutable, CodeType codeType, JSGlobalObject* globalObject, PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset, bool isConstructor, PassOwnPtr<CodeBlock> alternative = nullptr)
1425             : CodeBlock(ownerExecutable, codeType, globalObject, sourceProvider, sourceOffset, SharedSymbolTable::create().leakRef(), isConstructor, alternative)
1426         {
1427         }
1428         ~FunctionCodeBlock()
1429         {
1430             sharedSymbolTable()->deref();
1431         }
1432         
1433 #if ENABLE(JIT)
1434     protected:
1435         virtual JSObject* compileOptimized(ExecState*, ScopeChainNode*);
1436         virtual void jettison();
1437         virtual bool jitCompileImpl(ExecState*);
1438         virtual CodeBlock* replacement();
1439         virtual DFG::CapabilityLevel canCompileWithDFGInternal();
1440 #endif
1441     };
1442
1443     inline CodeBlock* baselineCodeBlockForInlineCallFrame(InlineCallFrame* inlineCallFrame)
1444     {
1445         ASSERT(inlineCallFrame);
1446         ExecutableBase* executable = inlineCallFrame->executable.get();
1447         ASSERT(executable->structure()->classInfo() == &FunctionExecutable::s_info);
1448         return static_cast<FunctionExecutable*>(executable)->baselineCodeBlockFor(inlineCallFrame->isCall ? CodeForCall : CodeForConstruct);
1449     }
1450     
1451     inline CodeBlock* baselineCodeBlockForOriginAndBaselineCodeBlock(const CodeOrigin& codeOrigin, CodeBlock* baselineCodeBlock)
1452     {
1453         if (codeOrigin.inlineCallFrame)
1454             return baselineCodeBlockForInlineCallFrame(codeOrigin.inlineCallFrame);
1455         return baselineCodeBlock;
1456     }
1457     
1458
1459     inline Register& ExecState::r(int index)
1460     {
1461         CodeBlock* codeBlock = this->codeBlock();
1462         if (codeBlock->isConstantRegisterIndex(index))
1463             return *reinterpret_cast<Register*>(&codeBlock->constantRegister(index));
1464         return this[index];
1465     }
1466
1467     inline Register& ExecState::uncheckedR(int index)
1468     {
1469         ASSERT(index < FirstConstantRegisterIndex);
1470         return this[index];
1471     }
1472
1473 #if ENABLE(DFG_JIT)
1474     inline bool ExecState::isInlineCallFrame()
1475     {
1476         if (LIKELY(!codeBlock() || codeBlock()->getJITType() != JITCode::DFGJIT))
1477             return false;
1478         return isInlineCallFrameSlow();
1479     }
1480 #endif
1481
1482 #if ENABLE(DFG_JIT)
1483     inline void DFGCodeBlocks::mark(void* candidateCodeBlock)
1484     {
1485         // We have to check for 0 and -1 because those are used by the HashMap as markers.
1486         uintptr_t value = reinterpret_cast<uintptr_t>(candidateCodeBlock);
1487         
1488         // This checks for both of those nasty cases in one go.
1489         // 0 + 1 = 1
1490         // -1 + 1 = 0
1491         if (value + 1 <= 1)
1492             return;
1493         
1494         HashSet<CodeBlock*>::iterator iter = m_set.find(static_cast<CodeBlock*>(candidateCodeBlock));
1495         if (iter == m_set.end())
1496             return;
1497         
1498         (*iter)->m_dfgData->mayBeExecuting = true;
1499     }
1500 #endif
1501     
1502     inline JSValue Structure::prototypeForLookup(CodeBlock* codeBlock) const
1503     {
1504         return prototypeForLookup(codeBlock->globalObject());
1505     }
1506
1507 } // namespace JSC
1508
1509 #endif // CodeBlock_h