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