Unreviewed, rolling out r192914.
[WebKit-https.git] / Source / JavaScriptCore / bytecode / CodeBlock.h
1 /*
2  * Copyright (C) 2008-2015 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 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 "ArrayProfile.h"
34 #include "ByValInfo.h"
35 #include "BytecodeConventions.h"
36 #include "BytecodeLivenessAnalysis.h"
37 #include "CallLinkInfo.h"
38 #include "CallReturnOffsetToBytecodeOffset.h"
39 #include "CodeBlockHash.h"
40 #include "CodeBlockSet.h"
41 #include "CodeOrigin.h"
42 #include "CodeType.h"
43 #include "CompactJITCodeMap.h"
44 #include "ConcurrentJITLock.h"
45 #include "DFGCommon.h"
46 #include "DFGExitProfile.h"
47 #include "DeferredCompilationCallback.h"
48 #include "EvalCodeCache.h"
49 #include "ExecutionCounter.h"
50 #include "ExpressionRangeInfo.h"
51 #include "HandlerInfo.h"
52 #include "Instruction.h"
53 #include "JITCode.h"
54 #include "JITWriteBarrier.h"
55 #include "JSCell.h"
56 #include "JSGlobalObject.h"
57 #include "JumpTable.h"
58 #include "LLIntCallLinkInfo.h"
59 #include "LazyOperandValueProfile.h"
60 #include "ObjectAllocationProfile.h"
61 #include "Options.h"
62 #include "ProfilerCompilation.h"
63 #include "ProfilerJettisonReason.h"
64 #include "PutPropertySlot.h"
65 #include "RegExpObject.h"
66 #include "StructureStubInfo.h"
67 #include "UnconditionalFinalizer.h"
68 #include "ValueProfile.h"
69 #include "VirtualRegister.h"
70 #include "Watchpoint.h"
71 #include <wtf/Bag.h>
72 #include <wtf/FastMalloc.h>
73 #include <wtf/RefCountedArray.h>
74 #include <wtf/RefPtr.h>
75 #include <wtf/SegmentedVector.h>
76 #include <wtf/Vector.h>
77 #include <wtf/text/WTFString.h>
78
79 namespace JSC {
80
81 class ExecState;
82 class LLIntOffsetsExtractor;
83 class RegisterAtOffsetList;
84 class TypeLocation;
85 class JSModuleEnvironment;
86
87 enum ReoptimizationMode { DontCountReoptimization, CountReoptimization };
88
89 class CodeBlock : public JSCell {
90     typedef JSCell Base;
91     friend class BytecodeLivenessAnalysis;
92     friend class JIT;
93     friend class LLIntOffsetsExtractor;
94
95     class UnconditionalFinalizer : public JSC::UnconditionalFinalizer { 
96         virtual void finalizeUnconditionally() override;
97     };
98
99     class WeakReferenceHarvester : public JSC::WeakReferenceHarvester {
100         virtual void visitWeakReferences(SlotVisitor&) override;
101     };
102
103 public:
104     enum CopyParsedBlockTag { CopyParsedBlock };
105
106     static const unsigned StructureFlags = Base::StructureFlags | StructureIsImmortal;
107
108     DECLARE_INFO;
109
110 protected:
111     CodeBlock(VM*, Structure*, CopyParsedBlockTag, CodeBlock& other);
112     CodeBlock(VM*, Structure*, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock*, JSScope*, PassRefPtr<SourceProvider>, unsigned sourceOffset, unsigned firstLineColumnOffset);
113 #if ENABLE(WEBASSEMBLY)
114     CodeBlock(VM*, Structure*, WebAssemblyExecutable* ownerExecutable, JSGlobalObject*);
115 #endif
116
117     void finishCreation(VM&, CopyParsedBlockTag, CodeBlock& other);
118     void finishCreation(VM&, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock*, JSScope*);
119 #if ENABLE(WEBASSEMBLY)
120     void finishCreation(VM&, WebAssemblyExecutable* ownerExecutable, JSGlobalObject*);
121 #endif
122
123     WriteBarrier<JSGlobalObject> m_globalObject;
124     Heap* m_heap;
125
126 public:
127     JS_EXPORT_PRIVATE ~CodeBlock();
128
129     UnlinkedCodeBlock* unlinkedCodeBlock() const { return m_unlinkedCode.get(); }
130
131     CString inferredName() const;
132     CodeBlockHash hash() const;
133     bool hasHash() const;
134     bool isSafeToComputeHash() const;
135     CString hashAsStringIfPossible() const;
136     CString sourceCodeForTools() const; // Not quite the actual source we parsed; this will do things like prefix the source for a function with a reified signature.
137     CString sourceCodeOnOneLine() const; // As sourceCodeForTools(), but replaces all whitespace runs with a single space.
138     void dumpAssumingJITType(PrintStream&, JITCode::JITType) const;
139     void dump(PrintStream&) const;
140
141     int numParameters() const { return m_numParameters; }
142     void setNumParameters(int newValue);
143
144     int* addressOfNumParameters() { return &m_numParameters; }
145     static ptrdiff_t offsetOfNumParameters() { return OBJECT_OFFSETOF(CodeBlock, m_numParameters); }
146
147     CodeBlock* alternative() const { return static_cast<CodeBlock*>(m_alternative.get()); }
148     void setAlternative(VM&, CodeBlock*);
149
150     template <typename Functor> void forEachRelatedCodeBlock(Functor&& functor)
151     {
152         Functor f(std::forward<Functor>(functor));
153         Vector<CodeBlock*, 4> codeBlocks;
154         codeBlocks.append(this);
155
156         while (!codeBlocks.isEmpty()) {
157             CodeBlock* currentCodeBlock = codeBlocks.takeLast();
158             f(currentCodeBlock);
159
160             if (CodeBlock* alternative = currentCodeBlock->alternative())
161                 codeBlocks.append(alternative);
162             if (CodeBlock* osrEntryBlock = currentCodeBlock->specialOSREntryBlockOrNull())
163                 codeBlocks.append(osrEntryBlock);
164         }
165     }
166     
167     CodeSpecializationKind specializationKind() const
168     {
169         return specializationFromIsConstruct(m_isConstructor);
170     }
171
172     CodeBlock* alternativeForJettison();    
173     JS_EXPORT_PRIVATE CodeBlock* baselineAlternative();
174     
175     // FIXME: Get rid of this.
176     // https://bugs.webkit.org/show_bug.cgi?id=123677
177     CodeBlock* baselineVersion();
178
179     static void visitChildren(JSCell*, SlotVisitor&);
180     void visitChildren(SlotVisitor&);
181     void visitWeakly(SlotVisitor&);
182     void clearVisitWeaklyHasBeenCalled();
183
184     void dumpSource();
185     void dumpSource(PrintStream&);
186
187     void dumpBytecode();
188     void dumpBytecode(PrintStream&);
189     void dumpBytecode(
190         PrintStream&, unsigned bytecodeOffset,
191         const StubInfoMap& = StubInfoMap(), const CallLinkInfoMap& = CallLinkInfoMap());
192     void printStructures(PrintStream&, const Instruction*);
193     void printStructure(PrintStream&, const char* name, const Instruction*, int operand);
194
195     bool isStrictMode() const { return m_isStrictMode; }
196     ECMAMode ecmaMode() const { return isStrictMode() ? StrictMode : NotStrictMode; }
197
198     inline bool isKnownNotImmediate(int index)
199     {
200         if (index == m_thisRegister.offset() && !m_isStrictMode)
201             return true;
202
203         if (isConstantRegisterIndex(index))
204             return getConstant(index).isCell();
205
206         return false;
207     }
208
209     ALWAYS_INLINE bool isTemporaryRegisterIndex(int index)
210     {
211         return index >= m_numVars;
212     }
213
214     enum class RequiredHandler {
215         CatchHandler,
216         AnyHandler
217     };
218     HandlerInfo* handlerForBytecodeOffset(unsigned bytecodeOffset, RequiredHandler = RequiredHandler::AnyHandler);
219     HandlerInfo* handlerForIndex(unsigned, RequiredHandler = RequiredHandler::AnyHandler);
220     void removeExceptionHandlerForCallSite(CallSiteIndex);
221     unsigned lineNumberForBytecodeOffset(unsigned bytecodeOffset);
222     unsigned columnNumberForBytecodeOffset(unsigned bytecodeOffset);
223     void expressionRangeForBytecodeOffset(unsigned bytecodeOffset, int& divot,
224                                           int& startOffset, int& endOffset, unsigned& line, unsigned& column);
225
226     void getStubInfoMap(const ConcurrentJITLocker&, StubInfoMap& result);
227     void getStubInfoMap(StubInfoMap& result);
228     
229     void getCallLinkInfoMap(const ConcurrentJITLocker&, CallLinkInfoMap& result);
230     void getCallLinkInfoMap(CallLinkInfoMap& result);
231
232     void getByValInfoMap(const ConcurrentJITLocker&, ByValInfoMap& result);
233     void getByValInfoMap(ByValInfoMap& result);
234     
235 #if ENABLE(JIT)
236     StructureStubInfo* addStubInfo(AccessType);
237     Bag<StructureStubInfo>::iterator stubInfoBegin() { return m_stubInfos.begin(); }
238     Bag<StructureStubInfo>::iterator stubInfoEnd() { return m_stubInfos.end(); }
239     
240     // O(n) operation. Use getStubInfoMap() unless you really only intend to get one
241     // stub info.
242     StructureStubInfo* findStubInfo(CodeOrigin);
243
244     ByValInfo* addByValInfo();
245
246     CallLinkInfo* addCallLinkInfo();
247     Bag<CallLinkInfo>::iterator callLinkInfosBegin() { return m_callLinkInfos.begin(); }
248     Bag<CallLinkInfo>::iterator callLinkInfosEnd() { return m_callLinkInfos.end(); }
249
250     // This is a slow function call used primarily for compiling OSR exits in the case
251     // that there had been inlining. Chances are if you want to use this, you're really
252     // looking for a CallLinkInfoMap to amortize the cost of calling this.
253     CallLinkInfo* getCallLinkInfoForBytecodeIndex(unsigned bytecodeIndex);
254 #endif // ENABLE(JIT)
255
256     void unlinkIncomingCalls();
257
258 #if ENABLE(JIT)
259     void linkIncomingCall(ExecState* callerFrame, CallLinkInfo*);
260     void linkIncomingPolymorphicCall(ExecState* callerFrame, PolymorphicCallNode*);
261 #endif // ENABLE(JIT)
262
263     void linkIncomingCall(ExecState* callerFrame, LLIntCallLinkInfo*);
264
265     void setJITCodeMap(std::unique_ptr<CompactJITCodeMap> jitCodeMap)
266     {
267         m_jitCodeMap = WTF::move(jitCodeMap);
268     }
269     CompactJITCodeMap* jitCodeMap()
270     {
271         return m_jitCodeMap.get();
272     }
273     
274     unsigned bytecodeOffset(Instruction* returnAddress)
275     {
276         RELEASE_ASSERT(returnAddress >= instructions().begin() && returnAddress < instructions().end());
277         return static_cast<Instruction*>(returnAddress) - instructions().begin();
278     }
279
280     unsigned numberOfInstructions() const { return m_instructions.size(); }
281     RefCountedArray<Instruction>& instructions() { return m_instructions; }
282     const RefCountedArray<Instruction>& instructions() const { return m_instructions; }
283
284     size_t predictedMachineCodeSize();
285
286     bool usesOpcode(OpcodeID);
287
288     unsigned instructionCount() const { return m_instructions.size(); }
289
290     // Exactly equivalent to codeBlock->ownerExecutable()->newReplacementCodeBlockFor(codeBlock->specializationKind())
291     CodeBlock* newReplacement();
292     
293     void setJITCode(PassRefPtr<JITCode> code)
294     {
295         ASSERT(m_heap->isDeferred());
296         m_heap->reportExtraMemoryAllocated(code->size());
297         ConcurrentJITLocker locker(m_lock);
298         WTF::storeStoreFence(); // This is probably not needed because the lock will also do something similar, but it's good to be paranoid.
299         m_jitCode = code;
300     }
301     PassRefPtr<JITCode> jitCode() { return m_jitCode; }
302     JITCode::JITType jitType() const
303     {
304         JITCode* jitCode = m_jitCode.get();
305         WTF::loadLoadFence();
306         JITCode::JITType result = JITCode::jitTypeFor(jitCode);
307         WTF::loadLoadFence(); // This probably isn't needed. Oh well, paranoia is good.
308         return result;
309     }
310
311     bool hasBaselineJITProfiling() const
312     {
313         return jitType() == JITCode::BaselineJIT;
314     }
315     
316 #if ENABLE(JIT)
317     CodeBlock* replacement();
318
319     DFG::CapabilityLevel computeCapabilityLevel();
320     DFG::CapabilityLevel capabilityLevel();
321     DFG::CapabilityLevel capabilityLevelState() { return m_capabilityLevelState; }
322
323     bool hasOptimizedReplacement(JITCode::JITType typeToReplace);
324     bool hasOptimizedReplacement(); // the typeToReplace is my JITType
325 #endif
326
327     void jettison(Profiler::JettisonReason, ReoptimizationMode = DontCountReoptimization, const FireDetail* = nullptr);
328     
329     ExecutableBase* ownerExecutable() const { return m_ownerExecutable.get(); }
330     ScriptExecutable* ownerScriptExecutable() const { return jsCast<ScriptExecutable*>(m_ownerExecutable.get()); }
331
332     void setVM(VM* vm) { m_vm = vm; }
333     VM* vm() { return m_vm; }
334
335     void setThisRegister(VirtualRegister thisRegister) { m_thisRegister = thisRegister; }
336     VirtualRegister thisRegister() const { return m_thisRegister; }
337
338     bool usesEval() const { return m_unlinkedCode->usesEval(); }
339
340     void setScopeRegister(VirtualRegister scopeRegister)
341     {
342         ASSERT(scopeRegister.isLocal() || !scopeRegister.isValid());
343         m_scopeRegister = scopeRegister;
344     }
345
346     VirtualRegister scopeRegister() const
347     {
348         return m_scopeRegister;
349     }
350
351     void setActivationRegister(VirtualRegister activationRegister)
352     {
353         m_lexicalEnvironmentRegister = activationRegister;
354     }
355
356     VirtualRegister activationRegister() const
357     {
358         ASSERT(m_lexicalEnvironmentRegister.isValid());
359         return m_lexicalEnvironmentRegister;
360     }
361
362     VirtualRegister uncheckedActivationRegister()
363     {
364         return m_lexicalEnvironmentRegister;
365     }
366
367     bool needsActivation() const
368     {
369         ASSERT(m_lexicalEnvironmentRegister.isValid() == m_needsActivation);
370         return m_needsActivation;
371     }
372     
373     CodeType codeType() const
374     {
375         return m_codeType;
376     }
377
378     PutPropertySlot::Context putByIdContext() const
379     {
380         if (codeType() == EvalCode)
381             return PutPropertySlot::PutByIdEval;
382         return PutPropertySlot::PutById;
383     }
384
385     SourceProvider* source() const { return m_source.get(); }
386     unsigned sourceOffset() const { return m_sourceOffset; }
387     unsigned firstLineColumnOffset() const { return m_firstLineColumnOffset; }
388
389     size_t numberOfJumpTargets() const { return m_unlinkedCode->numberOfJumpTargets(); }
390     unsigned jumpTarget(int index) const { return m_unlinkedCode->jumpTarget(index); }
391
392     String nameForRegister(VirtualRegister);
393
394     unsigned numberOfArgumentValueProfiles()
395     {
396         ASSERT(m_numParameters >= 0);
397         ASSERT(m_argumentValueProfiles.size() == static_cast<unsigned>(m_numParameters));
398         return m_argumentValueProfiles.size();
399     }
400     ValueProfile* valueProfileForArgument(unsigned argumentIndex)
401     {
402         ValueProfile* result = &m_argumentValueProfiles[argumentIndex];
403         ASSERT(result->m_bytecodeOffset == -1);
404         return result;
405     }
406
407     unsigned numberOfValueProfiles() { return m_valueProfiles.size(); }
408     ValueProfile* valueProfile(int index) { return &m_valueProfiles[index]; }
409     ValueProfile* valueProfileForBytecodeOffset(int bytecodeOffset);
410     SpeculatedType valueProfilePredictionForBytecodeOffset(const ConcurrentJITLocker& locker, int bytecodeOffset)
411     {
412         return valueProfileForBytecodeOffset(bytecodeOffset)->computeUpdatedPrediction(locker);
413     }
414
415     unsigned totalNumberOfValueProfiles()
416     {
417         return numberOfArgumentValueProfiles() + numberOfValueProfiles();
418     }
419     ValueProfile* getFromAllValueProfiles(unsigned index)
420     {
421         if (index < numberOfArgumentValueProfiles())
422             return valueProfileForArgument(index);
423         return valueProfile(index - numberOfArgumentValueProfiles());
424     }
425
426     RareCaseProfile* addRareCaseProfile(int bytecodeOffset)
427     {
428         m_rareCaseProfiles.append(RareCaseProfile(bytecodeOffset));
429         return &m_rareCaseProfiles.last();
430     }
431     unsigned numberOfRareCaseProfiles() { return m_rareCaseProfiles.size(); }
432     RareCaseProfile* rareCaseProfileForBytecodeOffset(int bytecodeOffset);
433     unsigned rareCaseProfileCountForBytecodeOffset(int bytecodeOffset);
434
435     bool likelyToTakeSlowCase(int bytecodeOffset)
436     {
437         if (!hasBaselineJITProfiling())
438             return false;
439         unsigned value = rareCaseProfileCountForBytecodeOffset(bytecodeOffset);
440         return value >= Options::likelyToTakeSlowCaseMinimumCount();
441     }
442
443     bool couldTakeSlowCase(int bytecodeOffset)
444     {
445         if (!hasBaselineJITProfiling())
446             return false;
447         unsigned value = rareCaseProfileCountForBytecodeOffset(bytecodeOffset);
448         return value >= Options::couldTakeSlowCaseMinimumCount();
449     }
450
451     RareCaseProfile* addSpecialFastCaseProfile(int bytecodeOffset)
452     {
453         m_specialFastCaseProfiles.append(RareCaseProfile(bytecodeOffset));
454         return &m_specialFastCaseProfiles.last();
455     }
456     unsigned numberOfSpecialFastCaseProfiles() { return m_specialFastCaseProfiles.size(); }
457     RareCaseProfile* specialFastCaseProfile(int index) { return &m_specialFastCaseProfiles[index]; }
458     RareCaseProfile* specialFastCaseProfileForBytecodeOffset(int bytecodeOffset)
459     {
460         return tryBinarySearch<RareCaseProfile, int>(
461             m_specialFastCaseProfiles, m_specialFastCaseProfiles.size(), bytecodeOffset,
462             getRareCaseProfileBytecodeOffset);
463     }
464     unsigned specialFastCaseProfileCountForBytecodeOffset(int bytecodeOffset)
465     {
466         RareCaseProfile* profile = specialFastCaseProfileForBytecodeOffset(bytecodeOffset);
467         if (!profile)
468             return 0;
469         return profile->m_counter;
470     }
471
472     bool couldTakeSpecialFastCase(int bytecodeOffset)
473     {
474         if (!hasBaselineJITProfiling())
475             return false;
476         unsigned specialFastCaseCount = specialFastCaseProfileCountForBytecodeOffset(bytecodeOffset);
477         return specialFastCaseCount >= Options::couldTakeSlowCaseMinimumCount();
478     }
479
480     bool likelyToTakeDeepestSlowCase(int bytecodeOffset)
481     {
482         if (!hasBaselineJITProfiling())
483             return false;
484         unsigned slowCaseCount = rareCaseProfileCountForBytecodeOffset(bytecodeOffset);
485         unsigned specialFastCaseCount = specialFastCaseProfileCountForBytecodeOffset(bytecodeOffset);
486         unsigned value = slowCaseCount - specialFastCaseCount;
487         return value >= Options::likelyToTakeSlowCaseMinimumCount();
488     }
489
490     unsigned numberOfArrayProfiles() const { return m_arrayProfiles.size(); }
491     const ArrayProfileVector& arrayProfiles() { return m_arrayProfiles; }
492     ArrayProfile* addArrayProfile(unsigned bytecodeOffset)
493     {
494         m_arrayProfiles.append(ArrayProfile(bytecodeOffset));
495         return &m_arrayProfiles.last();
496     }
497     ArrayProfile* getArrayProfile(unsigned bytecodeOffset);
498     ArrayProfile* getOrAddArrayProfile(unsigned bytecodeOffset);
499
500     // Exception handling support
501
502     size_t numberOfExceptionHandlers() const { return m_rareData ? m_rareData->m_exceptionHandlers.size() : 0; }
503     HandlerInfo& exceptionHandler(int index) { RELEASE_ASSERT(m_rareData); return m_rareData->m_exceptionHandlers[index]; }
504
505     bool hasExpressionInfo() { return m_unlinkedCode->hasExpressionInfo(); }
506
507 #if ENABLE(DFG_JIT)
508     Vector<CodeOrigin, 0, UnsafeVectorOverflow>& codeOrigins();
509     
510     // Having code origins implies that there has been some inlining.
511     bool hasCodeOrigins()
512     {
513         return JITCode::isOptimizingJIT(jitType());
514     }
515         
516     bool canGetCodeOrigin(CallSiteIndex index)
517     {
518         if (!hasCodeOrigins())
519             return false;
520         return index.bits() < codeOrigins().size();
521     }
522
523     CodeOrigin codeOrigin(CallSiteIndex index)
524     {
525         return codeOrigins()[index.bits()];
526     }
527
528     bool addFrequentExitSite(const DFG::FrequentExitSite& site)
529     {
530         ASSERT(JITCode::isBaselineCode(jitType()));
531         ConcurrentJITLocker locker(m_lock);
532         return m_exitProfile.add(locker, site);
533     }
534
535     bool hasExitSite(const ConcurrentJITLocker& locker, const DFG::FrequentExitSite& site) const
536     {
537         return m_exitProfile.hasExitSite(locker, site);
538     }
539     bool hasExitSite(const DFG::FrequentExitSite& site) const
540     {
541         ConcurrentJITLocker locker(m_lock);
542         return hasExitSite(locker, site);
543     }
544
545     DFG::ExitProfile& exitProfile() { return m_exitProfile; }
546
547     CompressedLazyOperandValueProfileHolder& lazyOperandValueProfiles()
548     {
549         return m_lazyOperandValueProfiles;
550     }
551 #endif // ENABLE(DFG_JIT)
552
553     // Constant Pool
554 #if ENABLE(DFG_JIT)
555     size_t numberOfIdentifiers() const { return m_unlinkedCode->numberOfIdentifiers() + numberOfDFGIdentifiers(); }
556     size_t numberOfDFGIdentifiers() const;
557     const Identifier& identifier(int index) const;
558 #else
559     size_t numberOfIdentifiers() const { return m_unlinkedCode->numberOfIdentifiers(); }
560     const Identifier& identifier(int index) const { return m_unlinkedCode->identifier(index); }
561 #endif
562
563     Vector<WriteBarrier<Unknown>>& constants() { return m_constantRegisters; }
564     Vector<SourceCodeRepresentation>& constantsSourceCodeRepresentation() { return m_constantsSourceCodeRepresentation; }
565     unsigned addConstant(JSValue v)
566     {
567         unsigned result = m_constantRegisters.size();
568         m_constantRegisters.append(WriteBarrier<Unknown>());
569         m_constantRegisters.last().set(m_globalObject->vm(), this, v);
570         m_constantsSourceCodeRepresentation.append(SourceCodeRepresentation::Other);
571         return result;
572     }
573
574     unsigned addConstantLazily()
575     {
576         unsigned result = m_constantRegisters.size();
577         m_constantRegisters.append(WriteBarrier<Unknown>());
578         m_constantsSourceCodeRepresentation.append(SourceCodeRepresentation::Other);
579         return result;
580     }
581
582     WriteBarrier<Unknown>& constantRegister(int index) { return m_constantRegisters[index - FirstConstantRegisterIndex]; }
583     ALWAYS_INLINE bool isConstantRegisterIndex(int index) const { return index >= FirstConstantRegisterIndex; }
584     ALWAYS_INLINE JSValue getConstant(int index) const { return m_constantRegisters[index - FirstConstantRegisterIndex].get(); }
585     ALWAYS_INLINE SourceCodeRepresentation constantSourceCodeRepresentation(int index) const { return m_constantsSourceCodeRepresentation[index - FirstConstantRegisterIndex]; }
586
587     FunctionExecutable* functionDecl(int index) { return m_functionDecls[index].get(); }
588     int numberOfFunctionDecls() { return m_functionDecls.size(); }
589     FunctionExecutable* functionExpr(int index) { return m_functionExprs[index].get(); }
590     
591     RegExp* regexp(int index) const { return m_unlinkedCode->regexp(index); }
592
593     unsigned numberOfConstantBuffers() const
594     {
595         if (!m_rareData)
596             return 0;
597         return m_rareData->m_constantBuffers.size();
598     }
599     unsigned addConstantBuffer(const Vector<JSValue>& buffer)
600     {
601         createRareDataIfNecessary();
602         unsigned size = m_rareData->m_constantBuffers.size();
603         m_rareData->m_constantBuffers.append(buffer);
604         return size;
605     }
606
607     Vector<JSValue>& constantBufferAsVector(unsigned index)
608     {
609         ASSERT(m_rareData);
610         return m_rareData->m_constantBuffers[index];
611     }
612     JSValue* constantBuffer(unsigned index)
613     {
614         return constantBufferAsVector(index).data();
615     }
616
617     Heap* heap() const { return m_heap; }
618     JSGlobalObject* globalObject() { return m_globalObject.get(); }
619
620     JSGlobalObject* globalObjectFor(CodeOrigin);
621
622     BytecodeLivenessAnalysis& livenessAnalysis()
623     {
624         {
625             ConcurrentJITLocker locker(m_lock);
626             if (!!m_livenessAnalysis)
627                 return *m_livenessAnalysis;
628         }
629         std::unique_ptr<BytecodeLivenessAnalysis> analysis =
630             std::make_unique<BytecodeLivenessAnalysis>(this);
631         {
632             ConcurrentJITLocker locker(m_lock);
633             if (!m_livenessAnalysis)
634                 m_livenessAnalysis = WTF::move(analysis);
635             return *m_livenessAnalysis;
636         }
637     }
638     
639     void validate();
640
641     // Jump Tables
642
643     size_t numberOfSwitchJumpTables() const { return m_rareData ? m_rareData->m_switchJumpTables.size() : 0; }
644     SimpleJumpTable& addSwitchJumpTable() { createRareDataIfNecessary(); m_rareData->m_switchJumpTables.append(SimpleJumpTable()); return m_rareData->m_switchJumpTables.last(); }
645     SimpleJumpTable& switchJumpTable(int tableIndex) { RELEASE_ASSERT(m_rareData); return m_rareData->m_switchJumpTables[tableIndex]; }
646     void clearSwitchJumpTables()
647     {
648         if (!m_rareData)
649             return;
650         m_rareData->m_switchJumpTables.clear();
651     }
652
653     size_t numberOfStringSwitchJumpTables() const { return m_rareData ? m_rareData->m_stringSwitchJumpTables.size() : 0; }
654     StringJumpTable& addStringSwitchJumpTable() { createRareDataIfNecessary(); m_rareData->m_stringSwitchJumpTables.append(StringJumpTable()); return m_rareData->m_stringSwitchJumpTables.last(); }
655     StringJumpTable& stringSwitchJumpTable(int tableIndex) { RELEASE_ASSERT(m_rareData); return m_rareData->m_stringSwitchJumpTables[tableIndex]; }
656
657     EvalCodeCache& evalCodeCache() { createRareDataIfNecessary(); return m_rareData->m_evalCodeCache; }
658
659     enum ShrinkMode {
660         // Shrink prior to generating machine code that may point directly into vectors.
661         EarlyShrink,
662
663         // Shrink after generating machine code, and after possibly creating new vectors
664         // and appending to others. At this time it is not safe to shrink certain vectors
665         // because we would have generated machine code that references them directly.
666         LateShrink
667     };
668     void shrinkToFit(ShrinkMode);
669
670     // Functions for controlling when JITting kicks in, in a mixed mode
671     // execution world.
672
673     bool checkIfJITThresholdReached()
674     {
675         return m_llintExecuteCounter.checkIfThresholdCrossedAndSet(this);
676     }
677
678     void dontJITAnytimeSoon()
679     {
680         m_llintExecuteCounter.deferIndefinitely();
681     }
682
683     void jitAfterWarmUp()
684     {
685         m_llintExecuteCounter.setNewThreshold(Options::thresholdForJITAfterWarmUp(), this);
686     }
687
688     void jitSoon()
689     {
690         m_llintExecuteCounter.setNewThreshold(Options::thresholdForJITSoon(), this);
691     }
692
693     const BaselineExecutionCounter& llintExecuteCounter() const
694     {
695         return m_llintExecuteCounter;
696     }
697
698     // Functions for controlling when tiered compilation kicks in. This
699     // controls both when the optimizing compiler is invoked and when OSR
700     // entry happens. Two triggers exist: the loop trigger and the return
701     // trigger. In either case, when an addition to m_jitExecuteCounter
702     // causes it to become non-negative, the optimizing compiler is
703     // invoked. This includes a fast check to see if this CodeBlock has
704     // already been optimized (i.e. replacement() returns a CodeBlock
705     // that was optimized with a higher tier JIT than this one). In the
706     // case of the loop trigger, if the optimized compilation succeeds
707     // (or has already succeeded in the past) then OSR is attempted to
708     // redirect program flow into the optimized code.
709
710     // These functions are called from within the optimization triggers,
711     // and are used as a single point at which we define the heuristics
712     // for how much warm-up is mandated before the next optimization
713     // trigger files. All CodeBlocks start out with optimizeAfterWarmUp(),
714     // as this is called from the CodeBlock constructor.
715
716     // When we observe a lot of speculation failures, we trigger a
717     // reoptimization. But each time, we increase the optimization trigger
718     // to avoid thrashing.
719     JS_EXPORT_PRIVATE unsigned reoptimizationRetryCounter() const;
720     void countReoptimization();
721 #if ENABLE(JIT)
722     static unsigned numberOfLLIntBaselineCalleeSaveRegisters() { return RegisterSet::llintBaselineCalleeSaveRegisters().numberOfSetRegisters(); }
723     static size_t llintBaselineCalleeSaveSpaceAsVirtualRegisters();
724     size_t calleeSaveSpaceAsVirtualRegisters();
725
726     unsigned numberOfDFGCompiles();
727
728     int32_t codeTypeThresholdMultiplier() const;
729
730     int32_t adjustedCounterValue(int32_t desiredThreshold);
731
732     int32_t* addressOfJITExecuteCounter()
733     {
734         return &m_jitExecuteCounter.m_counter;
735     }
736
737     static ptrdiff_t offsetOfJITExecuteCounter() { return OBJECT_OFFSETOF(CodeBlock, m_jitExecuteCounter) + OBJECT_OFFSETOF(BaselineExecutionCounter, m_counter); }
738     static ptrdiff_t offsetOfJITExecutionActiveThreshold() { return OBJECT_OFFSETOF(CodeBlock, m_jitExecuteCounter) + OBJECT_OFFSETOF(BaselineExecutionCounter, m_activeThreshold); }
739     static ptrdiff_t offsetOfJITExecutionTotalCount() { return OBJECT_OFFSETOF(CodeBlock, m_jitExecuteCounter) + OBJECT_OFFSETOF(BaselineExecutionCounter, m_totalCount); }
740
741     const BaselineExecutionCounter& jitExecuteCounter() const { return m_jitExecuteCounter; }
742
743     unsigned optimizationDelayCounter() const { return m_optimizationDelayCounter; }
744
745     // Check if the optimization threshold has been reached, and if not,
746     // adjust the heuristics accordingly. Returns true if the threshold has
747     // been reached.
748     bool checkIfOptimizationThresholdReached();
749
750     // Call this to force the next optimization trigger to fire. This is
751     // rarely wise, since optimization triggers are typically more
752     // expensive than executing baseline code.
753     void optimizeNextInvocation();
754
755     // Call this to prevent optimization from happening again. Note that
756     // optimization will still happen after roughly 2^29 invocations,
757     // so this is really meant to delay that as much as possible. This
758     // is called if optimization failed, and we expect it to fail in
759     // the future as well.
760     void dontOptimizeAnytimeSoon();
761
762     // Call this to reinitialize the counter to its starting state,
763     // forcing a warm-up to happen before the next optimization trigger
764     // fires. This is called in the CodeBlock constructor. It also
765     // makes sense to call this if an OSR exit occurred. Note that
766     // OSR exit code is code generated, so the value of the execute
767     // counter that this corresponds to is also available directly.
768     void optimizeAfterWarmUp();
769
770     // Call this to force an optimization trigger to fire only after
771     // a lot of warm-up.
772     void optimizeAfterLongWarmUp();
773
774     // Call this to cause an optimization trigger to fire soon, but
775     // not necessarily the next one. This makes sense if optimization
776     // succeeds. Successfuly optimization means that all calls are
777     // relinked to the optimized code, so this only affects call
778     // frames that are still executing this CodeBlock. The value here
779     // is tuned to strike a balance between the cost of OSR entry
780     // (which is too high to warrant making every loop back edge to
781     // trigger OSR immediately) and the cost of executing baseline
782     // code (which is high enough that we don't necessarily want to
783     // have a full warm-up). The intuition for calling this instead of
784     // optimizeNextInvocation() is for the case of recursive functions
785     // with loops. Consider that there may be N call frames of some
786     // recursive function, for a reasonably large value of N. The top
787     // one triggers optimization, and then returns, and then all of
788     // the others return. We don't want optimization to be triggered on
789     // each return, as that would be superfluous. It only makes sense
790     // to trigger optimization if one of those functions becomes hot
791     // in the baseline code.
792     void optimizeSoon();
793
794     void forceOptimizationSlowPathConcurrently();
795
796     void setOptimizationThresholdBasedOnCompilationResult(CompilationResult);
797     
798     uint32_t osrExitCounter() const { return m_osrExitCounter; }
799
800     void countOSRExit() { m_osrExitCounter++; }
801
802     uint32_t* addressOfOSRExitCounter() { return &m_osrExitCounter; }
803
804     static ptrdiff_t offsetOfOSRExitCounter() { return OBJECT_OFFSETOF(CodeBlock, m_osrExitCounter); }
805
806     uint32_t adjustedExitCountThreshold(uint32_t desiredThreshold);
807     uint32_t exitCountThresholdForReoptimization();
808     uint32_t exitCountThresholdForReoptimizationFromLoop();
809     bool shouldReoptimizeNow();
810     bool shouldReoptimizeFromLoopNow();
811
812     void setCalleeSaveRegisters(RegisterSet);
813     void setCalleeSaveRegisters(std::unique_ptr<RegisterAtOffsetList>);
814     
815     RegisterAtOffsetList* calleeSaveRegisters() const { return m_calleeSaveRegisters.get(); }
816 #else // No JIT
817     static unsigned numberOfLLIntBaselineCalleeSaveRegisters() { return 0; }
818     static size_t llintBaselineCalleeSaveSpaceAsVirtualRegisters() { return 0; };
819     void optimizeAfterWarmUp() { }
820     unsigned numberOfDFGCompiles() { return 0; }
821 #endif
822
823     bool shouldOptimizeNow();
824     void updateAllValueProfilePredictions();
825     void updateAllArrayPredictions();
826     void updateAllPredictions();
827
828     unsigned frameRegisterCount();
829     int stackPointerOffset();
830
831     bool hasOpDebugForLineAndColumn(unsigned line, unsigned column);
832
833     bool hasDebuggerRequests() const { return m_debuggerRequests; }
834     void* debuggerRequestsAddress() { return &m_debuggerRequests; }
835
836     void addBreakpoint(unsigned numBreakpoints);
837     void removeBreakpoint(unsigned numBreakpoints)
838     {
839         ASSERT(m_numBreakpoints >= numBreakpoints);
840         m_numBreakpoints -= numBreakpoints;
841     }
842
843     enum SteppingMode {
844         SteppingModeDisabled,
845         SteppingModeEnabled
846     };
847     void setSteppingMode(SteppingMode);
848
849     void clearDebuggerRequests()
850     {
851         m_steppingMode = SteppingModeDisabled;
852         m_numBreakpoints = 0;
853     }
854     
855     // FIXME: Make these remaining members private.
856
857     int m_numLocalRegistersForCalleeSaves;
858     int m_numCalleeRegisters;
859     int m_numVars;
860     bool m_isConstructor : 1;
861     
862     // This is intentionally public; it's the responsibility of anyone doing any
863     // of the following to hold the lock:
864     //
865     // - Modifying any inline cache in this code block.
866     //
867     // - Quering any inline cache in this code block, from a thread other than
868     //   the main thread.
869     //
870     // Additionally, it's only legal to modify the inline cache on the main
871     // thread. This means that the main thread can query the inline cache without
872     // locking. This is crucial since executing the inline cache is effectively
873     // "querying" it.
874     //
875     // Another exception to the rules is that the GC can do whatever it wants
876     // without holding any locks, because the GC is guaranteed to wait until any
877     // concurrent compilation threads finish what they're doing.
878     mutable ConcurrentJITLock m_lock;
879     
880     bool m_shouldAlwaysBeInlined; // Not a bitfield because the JIT wants to store to it.
881     bool m_allTransitionsHaveBeenMarked : 1; // Initialized and used on every GC.
882     
883     bool m_didFailFTLCompilation : 1;
884     bool m_hasBeenCompiledWithFTL : 1;
885
886     // Internal methods for use by validation code. It would be private if it wasn't
887     // for the fact that we use it from anonymous namespaces.
888     void beginValidationDidFail();
889     NO_RETURN_DUE_TO_CRASH void endValidationDidFail();
890
891     struct RareData {
892         WTF_MAKE_FAST_ALLOCATED;
893     public:
894         Vector<HandlerInfo> m_exceptionHandlers;
895
896         // Buffers used for large array literals
897         Vector<Vector<JSValue>> m_constantBuffers;
898
899         // Jump Tables
900         Vector<SimpleJumpTable> m_switchJumpTables;
901         Vector<StringJumpTable> m_stringSwitchJumpTables;
902
903         EvalCodeCache m_evalCodeCache;
904     };
905
906     void clearExceptionHandlers()
907     {
908         if (m_rareData)
909             m_rareData->m_exceptionHandlers.clear();
910     }
911
912     void appendExceptionHandler(const HandlerInfo& handler)
913     {
914         createRareDataIfNecessary(); // We may be handling the exception of an inlined call frame.
915         m_rareData->m_exceptionHandlers.append(handler);
916     }
917
918     CallSiteIndex newExceptionHandlingCallSiteIndex(CallSiteIndex originalCallSite);
919
920 protected:
921     void finalizeLLIntInlineCaches();
922     void finalizeBaselineJITInlineCaches();
923
924 #if ENABLE(DFG_JIT)
925     void tallyFrequentExitSites();
926 #else
927     void tallyFrequentExitSites() { }
928 #endif
929
930 private:
931     friend class CodeBlockSet;
932     
933     CodeBlock* specialOSREntryBlockOrNull();
934     
935     void noticeIncomingCall(ExecState* callerFrame);
936     
937     double optimizationThresholdScalingFactor();
938
939     void updateAllPredictionsAndCountLiveness(unsigned& numberOfLiveNonArgumentValueProfiles, unsigned& numberOfSamplesInProfiles);
940
941     void setConstantRegisters(const Vector<WriteBarrier<Unknown>>& constants, const Vector<SourceCodeRepresentation>& constantsSourceCodeRepresentation)
942     {
943         ASSERT(constants.size() == constantsSourceCodeRepresentation.size());
944         size_t count = constants.size();
945         m_constantRegisters.resizeToFit(count);
946         for (size_t i = 0; i < count; i++)
947             m_constantRegisters[i].set(*m_vm, this, constants[i].get());
948         m_constantsSourceCodeRepresentation = constantsSourceCodeRepresentation;
949     }
950
951     void replaceConstant(int index, JSValue value)
952     {
953         ASSERT(isConstantRegisterIndex(index) && static_cast<size_t>(index - FirstConstantRegisterIndex) < m_constantRegisters.size());
954         m_constantRegisters[index - FirstConstantRegisterIndex].set(m_globalObject->vm(), this, value);
955     }
956
957     void dumpBytecode(
958         PrintStream&, ExecState*, const Instruction* begin, const Instruction*&,
959         const StubInfoMap& = StubInfoMap(), const CallLinkInfoMap& = CallLinkInfoMap());
960
961     CString registerName(int r) const;
962     CString constantName(int index) const;
963     void printUnaryOp(PrintStream&, ExecState*, int location, const Instruction*&, const char* op);
964     void printBinaryOp(PrintStream&, ExecState*, int location, const Instruction*&, const char* op);
965     void printConditionalJump(PrintStream&, ExecState*, const Instruction*, const Instruction*&, int location, const char* op);
966     void printGetByIdOp(PrintStream&, ExecState*, int location, const Instruction*&);
967     void printGetByIdCacheStatus(PrintStream&, ExecState*, int location, const StubInfoMap&);
968     enum CacheDumpMode { DumpCaches, DontDumpCaches };
969     void printCallOp(PrintStream&, ExecState*, int location, const Instruction*&, const char* op, CacheDumpMode, bool& hasPrintedProfiling, const CallLinkInfoMap&);
970     void printPutByIdOp(PrintStream&, ExecState*, int location, const Instruction*&, const char* op);
971     void printPutByIdCacheStatus(PrintStream&, int location, const StubInfoMap&);
972     void printLocationAndOp(PrintStream&, ExecState*, int location, const Instruction*&, const char* op);
973     void printLocationOpAndRegisterOperand(PrintStream&, ExecState*, int location, const Instruction*& it, const char* op, int operand);
974
975     void beginDumpProfiling(PrintStream&, bool& hasPrintedProfiling);
976     void dumpValueProfiling(PrintStream&, const Instruction*&, bool& hasPrintedProfiling);
977     void dumpArrayProfiling(PrintStream&, const Instruction*&, bool& hasPrintedProfiling);
978     void dumpRareCaseProfile(PrintStream&, const char* name, RareCaseProfile*, bool& hasPrintedProfiling);
979         
980     bool shouldVisitStrongly();
981     bool shouldJettisonDueToWeakReference();
982     bool shouldJettisonDueToOldAge();
983     
984     void propagateTransitions(SlotVisitor&);
985     void determineLiveness(SlotVisitor&);
986         
987     void stronglyVisitStrongReferences(SlotVisitor&);
988     void stronglyVisitWeakReferences(SlotVisitor&);
989     void visitOSRExitTargets(SlotVisitor&);
990
991     std::chrono::milliseconds timeSinceCreation()
992     {
993         return std::chrono::duration_cast<std::chrono::milliseconds>(
994             std::chrono::steady_clock::now() - m_creationTime);
995     }
996
997     void createRareDataIfNecessary()
998     {
999         if (!m_rareData)
1000             m_rareData = std::make_unique<RareData>();
1001     }
1002
1003     void insertBasicBlockBoundariesForControlFlowProfiler(RefCountedArray<Instruction>&);
1004
1005     WriteBarrier<UnlinkedCodeBlock> m_unlinkedCode;
1006     int m_numParameters;
1007     union {
1008         unsigned m_debuggerRequests;
1009         struct {
1010             unsigned m_hasDebuggerStatement : 1;
1011             unsigned m_steppingMode : 1;
1012             unsigned m_numBreakpoints : 30;
1013         };
1014     };
1015     WriteBarrier<ExecutableBase> m_ownerExecutable;
1016     VM* m_vm;
1017
1018     RefCountedArray<Instruction> m_instructions;
1019     VirtualRegister m_thisRegister;
1020     VirtualRegister m_scopeRegister;
1021     VirtualRegister m_lexicalEnvironmentRegister;
1022
1023     bool m_isStrictMode;
1024     bool m_needsActivation;
1025
1026     Atomic<bool> m_visitWeaklyHasBeenCalled;
1027
1028     RefPtr<SourceProvider> m_source;
1029     unsigned m_sourceOffset;
1030     unsigned m_firstLineColumnOffset;
1031     CodeType m_codeType;
1032
1033     Vector<LLIntCallLinkInfo> m_llintCallLinkInfos;
1034     SentinelLinkedList<LLIntCallLinkInfo, BasicRawSentinelNode<LLIntCallLinkInfo>> m_incomingLLIntCalls;
1035     RefPtr<JITCode> m_jitCode;
1036 #if ENABLE(JIT)
1037     std::unique_ptr<RegisterAtOffsetList> m_calleeSaveRegisters;
1038     Bag<StructureStubInfo> m_stubInfos;
1039     Bag<ByValInfo> m_byValInfos;
1040     Bag<CallLinkInfo> m_callLinkInfos;
1041     SentinelLinkedList<CallLinkInfo, BasicRawSentinelNode<CallLinkInfo>> m_incomingCalls;
1042     SentinelLinkedList<PolymorphicCallNode, BasicRawSentinelNode<PolymorphicCallNode>> m_incomingPolymorphicCalls;
1043 #endif
1044     std::unique_ptr<CompactJITCodeMap> m_jitCodeMap;
1045 #if ENABLE(DFG_JIT)
1046     // This is relevant to non-DFG code blocks that serve as the profiled code block
1047     // for DFG code blocks.
1048     DFG::ExitProfile m_exitProfile;
1049     CompressedLazyOperandValueProfileHolder m_lazyOperandValueProfiles;
1050 #endif
1051     Vector<ValueProfile> m_argumentValueProfiles;
1052     Vector<ValueProfile> m_valueProfiles;
1053     SegmentedVector<RareCaseProfile, 8> m_rareCaseProfiles;
1054     SegmentedVector<RareCaseProfile, 8> m_specialFastCaseProfiles;
1055     Vector<ArrayAllocationProfile> m_arrayAllocationProfiles;
1056     ArrayProfileVector m_arrayProfiles;
1057     Vector<ObjectAllocationProfile> m_objectAllocationProfiles;
1058
1059     // Constant Pool
1060     COMPILE_ASSERT(sizeof(Register) == sizeof(WriteBarrier<Unknown>), Register_must_be_same_size_as_WriteBarrier_Unknown);
1061     // TODO: This could just be a pointer to m_unlinkedCodeBlock's data, but the DFG mutates
1062     // it, so we're stuck with it for now.
1063     Vector<WriteBarrier<Unknown>> m_constantRegisters;
1064     Vector<SourceCodeRepresentation> m_constantsSourceCodeRepresentation;
1065     Vector<WriteBarrier<FunctionExecutable>> m_functionDecls;
1066     Vector<WriteBarrier<FunctionExecutable>> m_functionExprs;
1067
1068     WriteBarrier<CodeBlock> m_alternative;
1069     
1070     BaselineExecutionCounter m_llintExecuteCounter;
1071
1072     BaselineExecutionCounter m_jitExecuteCounter;
1073     int32_t m_totalJITExecutions;
1074     uint32_t m_osrExitCounter;
1075     uint16_t m_optimizationDelayCounter;
1076     uint16_t m_reoptimizationRetryCounter;
1077
1078     std::chrono::steady_clock::time_point m_creationTime;
1079
1080     mutable CodeBlockHash m_hash;
1081
1082     std::unique_ptr<BytecodeLivenessAnalysis> m_livenessAnalysis;
1083
1084     std::unique_ptr<RareData> m_rareData;
1085 #if ENABLE(JIT)
1086     DFG::CapabilityLevel m_capabilityLevelState;
1087 #endif
1088
1089     UnconditionalFinalizer m_unconditionalFinalizer;
1090     WeakReferenceHarvester m_weakReferenceHarvester;
1091 };
1092
1093 // Program code is not marked by any function, so we make the global object
1094 // responsible for marking it.
1095
1096 class GlobalCodeBlock : public CodeBlock {
1097     typedef CodeBlock Base;
1098     DECLARE_INFO;
1099
1100 protected:
1101     GlobalCodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, GlobalCodeBlock& other)
1102         : CodeBlock(vm, structure, CopyParsedBlock, other)
1103     {
1104     }
1105
1106     GlobalCodeBlock(VM* vm, Structure* structure, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock, JSScope* scope, PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset, unsigned firstLineColumnOffset)
1107         : CodeBlock(vm, structure, ownerExecutable, unlinkedCodeBlock, scope, sourceProvider, sourceOffset, firstLineColumnOffset)
1108     {
1109     }
1110 };
1111
1112 class ProgramCodeBlock : public GlobalCodeBlock {
1113 public:
1114     typedef GlobalCodeBlock Base;
1115     DECLARE_INFO;
1116
1117     static ProgramCodeBlock* create(VM* vm, CopyParsedBlockTag, ProgramCodeBlock& other)
1118     {
1119         ProgramCodeBlock* instance = new (NotNull, allocateCell<ProgramCodeBlock>(vm->heap))
1120             ProgramCodeBlock(vm, vm->programCodeBlockStructure.get(), CopyParsedBlock, other);
1121         instance->finishCreation(*vm, CopyParsedBlock, other);
1122         return instance;
1123     }
1124
1125     static ProgramCodeBlock* create(VM* vm, ProgramExecutable* ownerExecutable, UnlinkedProgramCodeBlock* unlinkedCodeBlock,
1126         JSScope* scope, PassRefPtr<SourceProvider> sourceProvider, unsigned firstLineColumnOffset)
1127     {
1128         ProgramCodeBlock* instance = new (NotNull, allocateCell<ProgramCodeBlock>(vm->heap))
1129             ProgramCodeBlock(vm, vm->programCodeBlockStructure.get(), ownerExecutable, unlinkedCodeBlock, scope, sourceProvider, firstLineColumnOffset);
1130         instance->finishCreation(*vm, ownerExecutable, unlinkedCodeBlock, scope);
1131         return instance;
1132     }
1133
1134     static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
1135     {
1136         return Structure::create(vm, globalObject, prototype, TypeInfo(CellType, StructureFlags), info());
1137     }
1138
1139 private:
1140     ProgramCodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, ProgramCodeBlock& other)
1141         : GlobalCodeBlock(vm, structure, CopyParsedBlock, other)
1142     {
1143     }
1144
1145     ProgramCodeBlock(VM* vm, Structure* structure, ProgramExecutable* ownerExecutable, UnlinkedProgramCodeBlock* unlinkedCodeBlock,
1146         JSScope* scope, PassRefPtr<SourceProvider> sourceProvider, unsigned firstLineColumnOffset)
1147         : GlobalCodeBlock(vm, structure, ownerExecutable, unlinkedCodeBlock, scope, sourceProvider, 0, firstLineColumnOffset)
1148     {
1149     }
1150
1151     static void destroy(JSCell*);
1152 };
1153
1154 class ModuleProgramCodeBlock : public GlobalCodeBlock {
1155 public:
1156     typedef GlobalCodeBlock Base;
1157     DECLARE_INFO;
1158
1159     static ModuleProgramCodeBlock* create(VM* vm, CopyParsedBlockTag, ModuleProgramCodeBlock& other)
1160     {
1161         ModuleProgramCodeBlock* instance = new (NotNull, allocateCell<ModuleProgramCodeBlock>(vm->heap))
1162             ModuleProgramCodeBlock(vm, vm->moduleProgramCodeBlockStructure.get(), CopyParsedBlock, other);
1163         instance->finishCreation(*vm, CopyParsedBlock, other);
1164         return instance;
1165     }
1166
1167     static ModuleProgramCodeBlock* create(VM* vm, ModuleProgramExecutable* ownerExecutable, UnlinkedModuleProgramCodeBlock* unlinkedCodeBlock,
1168         JSScope* scope, PassRefPtr<SourceProvider> sourceProvider, unsigned firstLineColumnOffset)
1169     {
1170         ModuleProgramCodeBlock* instance = new (NotNull, allocateCell<ModuleProgramCodeBlock>(vm->heap))
1171             ModuleProgramCodeBlock(vm, vm->moduleProgramCodeBlockStructure.get(), ownerExecutable, unlinkedCodeBlock, scope, sourceProvider, firstLineColumnOffset);
1172         instance->finishCreation(*vm, ownerExecutable, unlinkedCodeBlock, scope);
1173         return instance;
1174     }
1175
1176     static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
1177     {
1178         return Structure::create(vm, globalObject, prototype, TypeInfo(CellType, StructureFlags), info());
1179     }
1180
1181 private:
1182     ModuleProgramCodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, ModuleProgramCodeBlock& other)
1183         : GlobalCodeBlock(vm, structure, CopyParsedBlock, other)
1184     {
1185     }
1186
1187     ModuleProgramCodeBlock(VM* vm, Structure* structure, ModuleProgramExecutable* ownerExecutable, UnlinkedModuleProgramCodeBlock* unlinkedCodeBlock,
1188         JSScope* scope, PassRefPtr<SourceProvider> sourceProvider, unsigned firstLineColumnOffset)
1189         : GlobalCodeBlock(vm, structure, ownerExecutable, unlinkedCodeBlock, scope, sourceProvider, 0, firstLineColumnOffset)
1190     {
1191     }
1192
1193     static void destroy(JSCell*);
1194 };
1195
1196 class EvalCodeBlock : public GlobalCodeBlock {
1197 public:
1198     typedef GlobalCodeBlock Base;
1199     DECLARE_INFO;
1200
1201     static EvalCodeBlock* create(VM* vm, CopyParsedBlockTag, EvalCodeBlock& other)
1202     {
1203         EvalCodeBlock* instance = new (NotNull, allocateCell<EvalCodeBlock>(vm->heap))
1204             EvalCodeBlock(vm, vm->evalCodeBlockStructure.get(), CopyParsedBlock, other);
1205         instance->finishCreation(*vm, CopyParsedBlock, other);
1206         return instance;
1207     }
1208
1209     static EvalCodeBlock* create(VM* vm, EvalExecutable* ownerExecutable, UnlinkedEvalCodeBlock* unlinkedCodeBlock,
1210         JSScope* scope, PassRefPtr<SourceProvider> sourceProvider)
1211     {
1212         EvalCodeBlock* instance = new (NotNull, allocateCell<EvalCodeBlock>(vm->heap))
1213             EvalCodeBlock(vm, vm->evalCodeBlockStructure.get(), ownerExecutable, unlinkedCodeBlock, scope, sourceProvider);
1214         instance->finishCreation(*vm, ownerExecutable, unlinkedCodeBlock, scope);
1215         return instance;
1216     }
1217
1218     static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
1219     {
1220         return Structure::create(vm, globalObject, prototype, TypeInfo(CellType, StructureFlags), info());
1221     }
1222
1223     const Identifier& variable(unsigned index) { return unlinkedEvalCodeBlock()->variable(index); }
1224     unsigned numVariables() { return unlinkedEvalCodeBlock()->numVariables(); }
1225     
1226 private:
1227     EvalCodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, EvalCodeBlock& other)
1228         : GlobalCodeBlock(vm, structure, CopyParsedBlock, other)
1229     {
1230     }
1231         
1232     EvalCodeBlock(VM* vm, Structure* structure, EvalExecutable* ownerExecutable, UnlinkedEvalCodeBlock* unlinkedCodeBlock,
1233         JSScope* scope, PassRefPtr<SourceProvider> sourceProvider)
1234         : GlobalCodeBlock(vm, structure, ownerExecutable, unlinkedCodeBlock, scope, sourceProvider, 0, 1)
1235     {
1236     }
1237     
1238     static void destroy(JSCell*);
1239
1240 private:
1241     UnlinkedEvalCodeBlock* unlinkedEvalCodeBlock() const { return jsCast<UnlinkedEvalCodeBlock*>(unlinkedCodeBlock()); }
1242 };
1243
1244 class FunctionCodeBlock : public CodeBlock {
1245 public:
1246     typedef CodeBlock Base;
1247     DECLARE_INFO;
1248
1249     static FunctionCodeBlock* create(VM* vm, CopyParsedBlockTag, FunctionCodeBlock& other)
1250     {
1251         FunctionCodeBlock* instance = new (NotNull, allocateCell<FunctionCodeBlock>(vm->heap))
1252             FunctionCodeBlock(vm, vm->functionCodeBlockStructure.get(), CopyParsedBlock, other);
1253         instance->finishCreation(*vm, CopyParsedBlock, other);
1254         return instance;
1255     }
1256
1257     static FunctionCodeBlock* create(VM* vm, FunctionExecutable* ownerExecutable, UnlinkedFunctionCodeBlock* unlinkedCodeBlock, JSScope* scope,
1258         PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset, unsigned firstLineColumnOffset)
1259     {
1260         FunctionCodeBlock* instance = new (NotNull, allocateCell<FunctionCodeBlock>(vm->heap))
1261             FunctionCodeBlock(vm, vm->functionCodeBlockStructure.get(), ownerExecutable, unlinkedCodeBlock, scope, sourceProvider, sourceOffset, firstLineColumnOffset);
1262         instance->finishCreation(*vm, ownerExecutable, unlinkedCodeBlock, scope);
1263         return instance;
1264     }
1265
1266     static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
1267     {
1268         return Structure::create(vm, globalObject, prototype, TypeInfo(CellType, StructureFlags), info());
1269     }
1270
1271 private:
1272     FunctionCodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, FunctionCodeBlock& other)
1273         : CodeBlock(vm, structure, CopyParsedBlock, other)
1274     {
1275     }
1276
1277     FunctionCodeBlock(VM* vm, Structure* structure, FunctionExecutable* ownerExecutable, UnlinkedFunctionCodeBlock* unlinkedCodeBlock, JSScope* scope,
1278         PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset, unsigned firstLineColumnOffset)
1279         : CodeBlock(vm, structure, ownerExecutable, unlinkedCodeBlock, scope, sourceProvider, sourceOffset, firstLineColumnOffset)
1280     {
1281     }
1282     
1283     static void destroy(JSCell*);
1284 };
1285
1286 #if ENABLE(WEBASSEMBLY)
1287 class WebAssemblyCodeBlock : public CodeBlock {
1288 public:
1289     typedef CodeBlock Base;
1290     DECLARE_INFO;
1291
1292     static WebAssemblyCodeBlock* create(VM* vm, CopyParsedBlockTag, WebAssemblyCodeBlock& other)
1293     {
1294         WebAssemblyCodeBlock* instance = new (NotNull, allocateCell<WebAssemblyCodeBlock>(vm->heap))
1295             WebAssemblyCodeBlock(vm, vm->webAssemblyCodeBlockStructure.get(), CopyParsedBlock, other);
1296         instance->finishCreation(*vm, CopyParsedBlock, other);
1297         return instance;
1298     }
1299
1300     static WebAssemblyCodeBlock* create(VM* vm, WebAssemblyExecutable* ownerExecutable, JSGlobalObject* globalObject)
1301     {
1302         WebAssemblyCodeBlock* instance = new (NotNull, allocateCell<WebAssemblyCodeBlock>(vm->heap))
1303             WebAssemblyCodeBlock(vm, vm->webAssemblyCodeBlockStructure.get(), ownerExecutable, globalObject);
1304         instance->finishCreation(*vm, ownerExecutable, globalObject);
1305         return instance;
1306     }
1307
1308     static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
1309     {
1310         return Structure::create(vm, globalObject, prototype, TypeInfo(CellType, StructureFlags), info());
1311     }
1312
1313 private:
1314     WebAssemblyCodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, WebAssemblyCodeBlock& other)
1315         : CodeBlock(vm, structure, CopyParsedBlock, other)
1316     {
1317     }
1318
1319     WebAssemblyCodeBlock(VM* vm, Structure* structure, WebAssemblyExecutable* ownerExecutable, JSGlobalObject* globalObject)
1320         : CodeBlock(vm, structure, ownerExecutable, globalObject)
1321     {
1322     }
1323
1324     static void destroy(JSCell*);
1325 };
1326 #endif
1327
1328 inline Register& ExecState::r(int index)
1329 {
1330     CodeBlock* codeBlock = this->codeBlock();
1331     if (codeBlock->isConstantRegisterIndex(index))
1332         return *reinterpret_cast<Register*>(&codeBlock->constantRegister(index));
1333     return this[index];
1334 }
1335
1336 inline Register& ExecState::r(VirtualRegister reg)
1337 {
1338     return r(reg.offset());
1339 }
1340
1341 inline Register& ExecState::uncheckedR(int index)
1342 {
1343     RELEASE_ASSERT(index < FirstConstantRegisterIndex);
1344     return this[index];
1345 }
1346
1347 inline Register& ExecState::uncheckedR(VirtualRegister reg)
1348 {
1349     return uncheckedR(reg.offset());
1350 }
1351
1352 inline void CodeBlock::clearVisitWeaklyHasBeenCalled()
1353 {
1354     m_visitWeaklyHasBeenCalled.store(false, std::memory_order_relaxed);
1355 }
1356
1357 inline void CodeBlockSet::mark(void* candidateCodeBlock)
1358 {
1359     // We have to check for 0 and -1 because those are used by the HashMap as markers.
1360     uintptr_t value = reinterpret_cast<uintptr_t>(candidateCodeBlock);
1361     
1362     // This checks for both of those nasty cases in one go.
1363     // 0 + 1 = 1
1364     // -1 + 1 = 0
1365     if (value + 1 <= 1)
1366         return;
1367
1368     CodeBlock* codeBlock = static_cast<CodeBlock*>(candidateCodeBlock); 
1369     if (!m_oldCodeBlocks.contains(codeBlock) && !m_newCodeBlocks.contains(codeBlock))
1370         return;
1371
1372     mark(codeBlock);
1373 }
1374
1375 inline void CodeBlockSet::mark(CodeBlock* codeBlock)
1376 {
1377     if (!codeBlock)
1378         return;
1379
1380     // Try to recover gracefully if we forget to execute a barrier for a
1381     // CodeBlock that does value profiling. This is probably overkill, but we
1382     // have always done it.
1383     Heap::heap(codeBlock)->writeBarrier(codeBlock);
1384
1385     m_currentlyExecuting.add(codeBlock);
1386 }
1387
1388 template <typename Functor> inline void ScriptExecutable::forEachCodeBlock(Functor&& functor)
1389 {
1390     switch (type()) {
1391     case ProgramExecutableType: {
1392         if (CodeBlock* codeBlock = static_cast<CodeBlock*>(jsCast<ProgramExecutable*>(this)->m_programCodeBlock.get()))
1393             codeBlock->forEachRelatedCodeBlock(std::forward<Functor>(functor));
1394         break;
1395     }
1396
1397     case EvalExecutableType: {
1398         if (CodeBlock* codeBlock = static_cast<CodeBlock*>(jsCast<EvalExecutable*>(this)->m_evalCodeBlock.get()))
1399             codeBlock->forEachRelatedCodeBlock(std::forward<Functor>(functor));
1400         break;
1401     }
1402
1403     case FunctionExecutableType: {
1404         Functor f(std::forward<Functor>(functor));
1405         FunctionExecutable* executable = jsCast<FunctionExecutable*>(this);
1406         if (CodeBlock* codeBlock = static_cast<CodeBlock*>(executable->m_codeBlockForCall.get()))
1407             codeBlock->forEachRelatedCodeBlock(f);
1408         if (CodeBlock* codeBlock = static_cast<CodeBlock*>(executable->m_codeBlockForConstruct.get()))
1409             codeBlock->forEachRelatedCodeBlock(f);
1410         break;
1411     }
1412
1413     case ModuleProgramExecutableType: {
1414         if (CodeBlock* codeBlock = static_cast<CodeBlock*>(jsCast<ModuleProgramExecutable*>(this)->m_moduleProgramCodeBlock.get()))
1415             codeBlock->forEachRelatedCodeBlock(std::forward<Functor>(functor));
1416         break;
1417     }
1418
1419     default:
1420         RELEASE_ASSERT_NOT_REACHED();
1421     }
1422 }
1423
1424 } // namespace JSC
1425
1426 #endif // CodeBlock_h