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