2 * Copyright (C) 2008-2016 Apple Inc. All rights reserved.
3 * Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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.
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"
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"
54 #include "JITWriteBarrier.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"
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"
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>
82 class JSModuleEnvironment;
83 class LLIntOffsetsExtractor;
84 class PCToCodeOriginMap;
85 class RegisterAtOffsetList;
86 class StructureStubInfo;
89 enum class AccessType : int8_t;
91 typedef HashMap<CodeOrigin, StructureStubInfo*, CodeOriginApproximateHash> StubInfoMap;
93 enum ReoptimizationMode { DontCountReoptimization, CountReoptimization };
95 class CodeBlock : public JSCell {
97 friend class BytecodeLivenessAnalysis;
99 friend class LLIntOffsetsExtractor;
101 class UnconditionalFinalizer : public JSC::UnconditionalFinalizer {
102 void finalizeUnconditionally() override;
105 class WeakReferenceHarvester : public JSC::WeakReferenceHarvester {
106 void visitWeakReferences(SlotVisitor&) override;
110 enum CopyParsedBlockTag { CopyParsedBlock };
112 static const unsigned StructureFlags = Base::StructureFlags | StructureIsImmortal;
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*);
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*);
129 WriteBarrier<JSGlobalObject> m_globalObject;
132 JS_EXPORT_PRIVATE ~CodeBlock();
134 UnlinkedCodeBlock* unlinkedCodeBlock() const { return m_unlinkedCode.get(); }
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;
146 int numParameters() const { return m_numParameters; }
147 void setNumParameters(int newValue);
149 int numCalleeLocals() const { return m_numCalleeLocals; }
151 int* addressOfNumParameters() { return &m_numParameters; }
152 static ptrdiff_t offsetOfNumParameters() { return OBJECT_OFFSETOF(CodeBlock, m_numParameters); }
154 CodeBlock* alternative() const { return static_cast<CodeBlock*>(m_alternative.get()); }
155 void setAlternative(VM&, CodeBlock*);
157 template <typename Functor> void forEachRelatedCodeBlock(Functor&& functor)
159 Functor f(std::forward<Functor>(functor));
160 Vector<CodeBlock*, 4> codeBlocks;
161 codeBlocks.append(this);
163 while (!codeBlocks.isEmpty()) {
164 CodeBlock* currentCodeBlock = codeBlocks.takeLast();
167 if (CodeBlock* alternative = currentCodeBlock->alternative())
168 codeBlocks.append(alternative);
169 if (CodeBlock* osrEntryBlock = currentCodeBlock->specialOSREntryBlockOrNull())
170 codeBlocks.append(osrEntryBlock);
174 CodeSpecializationKind specializationKind() const
176 return specializationFromIsConstruct(m_isConstructor);
179 CodeBlock* alternativeForJettison();
180 JS_EXPORT_PRIVATE CodeBlock* baselineAlternative();
182 // FIXME: Get rid of this.
183 // https://bugs.webkit.org/show_bug.cgi?id=123677
184 CodeBlock* baselineVersion();
186 static size_t estimatedSize(JSCell*);
187 static void visitChildren(JSCell*, SlotVisitor&);
188 void visitChildren(SlotVisitor&);
189 void visitWeakly(SlotVisitor&);
190 void clearVisitWeaklyHasBeenCalled();
193 void dumpSource(PrintStream&);
196 void dumpBytecode(PrintStream&);
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);
204 bool isStrictMode() const { return m_isStrictMode; }
205 ECMAMode ecmaMode() const { return isStrictMode() ? StrictMode : NotStrictMode; }
207 inline bool isKnownNotImmediate(int index)
209 if (index == m_thisRegister.offset() && !m_isStrictMode)
212 if (isConstantRegisterIndex(index))
213 return getConstant(index).isCell();
218 ALWAYS_INLINE bool isTemporaryRegisterIndex(int index)
220 return index >= m_numVars;
223 enum class RequiredHandler {
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);
235 Optional<unsigned> bytecodeOffsetFromCallSiteIndex(CallSiteIndex);
237 void getStubInfoMap(const ConcurrentJITLocker&, StubInfoMap& result);
238 void getStubInfoMap(StubInfoMap& result);
240 void getCallLinkInfoMap(const ConcurrentJITLocker&, CallLinkInfoMap& result);
241 void getCallLinkInfoMap(CallLinkInfoMap& result);
243 void getByValInfoMap(const ConcurrentJITLocker&, ByValInfoMap& result);
244 void getByValInfoMap(ByValInfoMap& result);
247 StructureStubInfo* addStubInfo(AccessType);
248 Bag<StructureStubInfo>::iterator stubInfoBegin() { return m_stubInfos.begin(); }
249 Bag<StructureStubInfo>::iterator stubInfoEnd() { return m_stubInfos.end(); }
251 // O(n) operation. Use getStubInfoMap() unless you really only intend to get one
253 StructureStubInfo* findStubInfo(CodeOrigin);
255 ByValInfo* addByValInfo();
257 CallLinkInfo* addCallLinkInfo();
258 Bag<CallLinkInfo>::iterator callLinkInfosBegin() { return m_callLinkInfos.begin(); }
259 Bag<CallLinkInfo>::iterator callLinkInfosEnd() { return m_callLinkInfos.end(); }
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)
267 void unlinkIncomingCalls();
270 void linkIncomingCall(ExecState* callerFrame, CallLinkInfo*);
271 void linkIncomingPolymorphicCall(ExecState* callerFrame, PolymorphicCallNode*);
272 #endif // ENABLE(JIT)
274 void linkIncomingCall(ExecState* callerFrame, LLIntCallLinkInfo*);
276 void setJITCodeMap(std::unique_ptr<CompactJITCodeMap> jitCodeMap)
278 m_jitCodeMap = WTFMove(jitCodeMap);
280 CompactJITCodeMap* jitCodeMap()
282 return m_jitCodeMap.get();
285 unsigned bytecodeOffset(Instruction* returnAddress)
287 RELEASE_ASSERT(returnAddress >= instructions().begin() && returnAddress < instructions().end());
288 return static_cast<Instruction*>(returnAddress) - instructions().begin();
291 unsigned numberOfInstructions() const { return m_instructions.size(); }
292 RefCountedArray<Instruction>& instructions() { return m_instructions; }
293 const RefCountedArray<Instruction>& instructions() const { return m_instructions; }
295 size_t predictedMachineCodeSize();
297 bool usesOpcode(OpcodeID);
299 unsigned instructionCount() const { return m_instructions.size(); }
301 // Exactly equivalent to codeBlock->ownerExecutable()->newReplacementCodeBlockFor(codeBlock->specializationKind())
302 CodeBlock* newReplacement();
304 void setJITCode(PassRefPtr<JITCode> code)
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.
312 PassRefPtr<JITCode> jitCode() { return m_jitCode; }
313 static ptrdiff_t jitCodeOffset() { return OBJECT_OFFSETOF(CodeBlock, m_jitCode); }
314 JITCode::JITType jitType() const
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.
323 bool hasBaselineJITProfiling() const
325 return jitType() == JITCode::BaselineJIT;
329 CodeBlock* replacement();
331 DFG::CapabilityLevel computeCapabilityLevel();
332 DFG::CapabilityLevel capabilityLevel();
333 DFG::CapabilityLevel capabilityLevelState() { return static_cast<DFG::CapabilityLevel>(m_capabilityLevelState); }
335 bool hasOptimizedReplacement(JITCode::JITType typeToReplace);
336 bool hasOptimizedReplacement(); // the typeToReplace is my JITType
339 void jettison(Profiler::JettisonReason, ReoptimizationMode = DontCountReoptimization, const FireDetail* = nullptr);
341 ExecutableBase* ownerExecutable() const { return m_ownerExecutable.get(); }
342 ScriptExecutable* ownerScriptExecutable() const { return jsCast<ScriptExecutable*>(m_ownerExecutable.get()); }
344 VM* vm() const { return m_vm; }
346 void setThisRegister(VirtualRegister thisRegister) { m_thisRegister = thisRegister; }
347 VirtualRegister thisRegister() const { return m_thisRegister; }
349 bool usesEval() const { return m_unlinkedCode->usesEval(); }
351 void setScopeRegister(VirtualRegister scopeRegister)
353 ASSERT(scopeRegister.isLocal() || !scopeRegister.isValid());
354 m_scopeRegister = scopeRegister;
357 VirtualRegister scopeRegister() const
359 return m_scopeRegister;
362 CodeType codeType() const
364 return static_cast<CodeType>(m_codeType);
367 PutPropertySlot::Context putByIdContext() const
369 if (codeType() == EvalCode)
370 return PutPropertySlot::PutByIdEval;
371 return PutPropertySlot::PutById;
374 SourceProvider* source() const { return m_source.get(); }
375 unsigned sourceOffset() const { return m_sourceOffset; }
376 unsigned firstLineColumnOffset() const { return m_firstLineColumnOffset; }
378 size_t numberOfJumpTargets() const { return m_unlinkedCode->numberOfJumpTargets(); }
379 unsigned jumpTarget(int index) const { return m_unlinkedCode->jumpTarget(index); }
381 String nameForRegister(VirtualRegister);
383 unsigned numberOfArgumentValueProfiles()
385 ASSERT(m_numParameters >= 0);
386 ASSERT(m_argumentValueProfiles.size() == static_cast<unsigned>(m_numParameters));
387 return m_argumentValueProfiles.size();
389 ValueProfile* valueProfileForArgument(unsigned argumentIndex)
391 ValueProfile* result = &m_argumentValueProfiles[argumentIndex];
392 ASSERT(result->m_bytecodeOffset == -1);
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)
401 return valueProfileForBytecodeOffset(bytecodeOffset)->computeUpdatedPrediction(locker);
404 unsigned totalNumberOfValueProfiles()
406 return numberOfArgumentValueProfiles() + numberOfValueProfiles();
408 ValueProfile* getFromAllValueProfiles(unsigned index)
410 if (index < numberOfArgumentValueProfiles())
411 return valueProfileForArgument(index);
412 return valueProfile(index - numberOfArgumentValueProfiles());
415 RareCaseProfile* addRareCaseProfile(int bytecodeOffset)
417 m_rareCaseProfiles.append(RareCaseProfile(bytecodeOffset));
418 return &m_rareCaseProfiles.last();
420 unsigned numberOfRareCaseProfiles() { return m_rareCaseProfiles.size(); }
421 RareCaseProfile* rareCaseProfileForBytecodeOffset(int bytecodeOffset);
422 unsigned rareCaseProfileCountForBytecodeOffset(int bytecodeOffset);
424 bool likelyToTakeSlowCase(int bytecodeOffset)
426 if (!hasBaselineJITProfiling())
428 unsigned value = rareCaseProfileCountForBytecodeOffset(bytecodeOffset);
429 return value >= Options::likelyToTakeSlowCaseMinimumCount();
432 bool couldTakeSlowCase(int bytecodeOffset)
434 if (!hasBaselineJITProfiling())
436 unsigned value = rareCaseProfileCountForBytecodeOffset(bytecodeOffset);
437 return value >= Options::couldTakeSlowCaseMinimumCount();
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);
446 unsigned specialFastCaseProfileCountForBytecodeOffset(int bytecodeOffset)
448 ResultProfile* profile = resultProfileForBytecodeOffset(bytecodeOffset);
451 return profile->specialFastPathCount();
454 bool couldTakeSpecialFastCase(int bytecodeOffset)
456 if (!hasBaselineJITProfiling())
458 unsigned specialFastCaseCount = specialFastCaseProfileCountForBytecodeOffset(bytecodeOffset);
459 return specialFastCaseCount >= Options::couldTakeSlowCaseMinimumCount();
462 unsigned numberOfArrayProfiles() const { return m_arrayProfiles.size(); }
463 const ArrayProfileVector& arrayProfiles() { return m_arrayProfiles; }
464 ArrayProfile* addArrayProfile(unsigned bytecodeOffset)
466 m_arrayProfiles.append(ArrayProfile(bytecodeOffset));
467 return &m_arrayProfiles.last();
469 ArrayProfile* getArrayProfile(unsigned bytecodeOffset);
470 ArrayProfile* getOrAddArrayProfile(unsigned bytecodeOffset);
472 // Exception handling support
474 size_t numberOfExceptionHandlers() const { return m_rareData ? m_rareData->m_exceptionHandlers.size() : 0; }
475 HandlerInfo& exceptionHandler(int index) { RELEASE_ASSERT(m_rareData); return m_rareData->m_exceptionHandlers[index]; }
477 bool hasExpressionInfo() { return m_unlinkedCode->hasExpressionInfo(); }
480 Vector<CodeOrigin, 0, UnsafeVectorOverflow>& codeOrigins();
482 // Having code origins implies that there has been some inlining.
483 bool hasCodeOrigins()
485 return JITCode::isOptimizingJIT(jitType());
488 bool canGetCodeOrigin(CallSiteIndex index)
490 if (!hasCodeOrigins())
492 return index.bits() < codeOrigins().size();
495 CodeOrigin codeOrigin(CallSiteIndex index)
497 return codeOrigins()[index.bits()];
500 bool addFrequentExitSite(const DFG::FrequentExitSite& site)
502 ASSERT(JITCode::isBaselineCode(jitType()));
503 ConcurrentJITLocker locker(m_lock);
504 return m_exitProfile.add(locker, this, site);
507 bool hasExitSite(const ConcurrentJITLocker& locker, const DFG::FrequentExitSite& site) const
509 return m_exitProfile.hasExitSite(locker, site);
511 bool hasExitSite(const DFG::FrequentExitSite& site) const
513 ConcurrentJITLocker locker(m_lock);
514 return hasExitSite(locker, site);
517 DFG::ExitProfile& exitProfile() { return m_exitProfile; }
519 CompressedLazyOperandValueProfileHolder& lazyOperandValueProfiles()
521 return m_lazyOperandValueProfiles;
523 #endif // ENABLE(DFG_JIT)
527 size_t numberOfIdentifiers() const { return m_unlinkedCode->numberOfIdentifiers() + numberOfDFGIdentifiers(); }
528 size_t numberOfDFGIdentifiers() const;
529 const Identifier& identifier(int index) const;
531 size_t numberOfIdentifiers() const { return m_unlinkedCode->numberOfIdentifiers(); }
532 const Identifier& identifier(int index) const { return m_unlinkedCode->identifier(index); }
535 Vector<WriteBarrier<Unknown>>& constants() { return m_constantRegisters; }
536 Vector<SourceCodeRepresentation>& constantsSourceCodeRepresentation() { return m_constantsSourceCodeRepresentation; }
537 unsigned addConstant(JSValue v)
539 unsigned result = m_constantRegisters.size();
540 m_constantRegisters.append(WriteBarrier<Unknown>());
541 m_constantRegisters.last().set(m_globalObject->vm(), this, v);
542 m_constantsSourceCodeRepresentation.append(SourceCodeRepresentation::Other);
546 unsigned addConstantLazily()
548 unsigned result = m_constantRegisters.size();
549 m_constantRegisters.append(WriteBarrier<Unknown>());
550 m_constantsSourceCodeRepresentation.append(SourceCodeRepresentation::Other);
554 WriteBarrier<Unknown>& constantRegister(int index) { return m_constantRegisters[index - FirstConstantRegisterIndex]; }
555 ALWAYS_INLINE bool isConstantRegisterIndex(int index) const { return index >= FirstConstantRegisterIndex; }
556 ALWAYS_INLINE JSValue getConstant(int index) const { return m_constantRegisters[index - FirstConstantRegisterIndex].get(); }
557 ALWAYS_INLINE SourceCodeRepresentation constantSourceCodeRepresentation(int index) const { return m_constantsSourceCodeRepresentation[index - FirstConstantRegisterIndex]; }
559 FunctionExecutable* functionDecl(int index) { return m_functionDecls[index].get(); }
560 int numberOfFunctionDecls() { return m_functionDecls.size(); }
561 FunctionExecutable* functionExpr(int index) { return m_functionExprs[index].get(); }
563 RegExp* regexp(int index) const { return m_unlinkedCode->regexp(index); }
565 unsigned numberOfConstantBuffers() const
569 return m_rareData->m_constantBuffers.size();
571 unsigned addConstantBuffer(const Vector<JSValue>& buffer)
573 createRareDataIfNecessary();
574 unsigned size = m_rareData->m_constantBuffers.size();
575 m_rareData->m_constantBuffers.append(buffer);
579 Vector<JSValue>& constantBufferAsVector(unsigned index)
582 return m_rareData->m_constantBuffers[index];
584 JSValue* constantBuffer(unsigned index)
586 return constantBufferAsVector(index).data();
589 Heap* heap() const { return &m_vm->heap; }
590 JSGlobalObject* globalObject() { return m_globalObject.get(); }
592 JSGlobalObject* globalObjectFor(CodeOrigin);
594 BytecodeLivenessAnalysis& livenessAnalysis()
597 ConcurrentJITLocker locker(m_lock);
598 if (!!m_livenessAnalysis)
599 return *m_livenessAnalysis;
601 std::unique_ptr<BytecodeLivenessAnalysis> analysis =
602 std::make_unique<BytecodeLivenessAnalysis>(this);
604 ConcurrentJITLocker locker(m_lock);
605 if (!m_livenessAnalysis)
606 m_livenessAnalysis = WTFMove(analysis);
607 return *m_livenessAnalysis;
615 size_t numberOfSwitchJumpTables() const { return m_rareData ? m_rareData->m_switchJumpTables.size() : 0; }
616 SimpleJumpTable& addSwitchJumpTable() { createRareDataIfNecessary(); m_rareData->m_switchJumpTables.append(SimpleJumpTable()); return m_rareData->m_switchJumpTables.last(); }
617 SimpleJumpTable& switchJumpTable(int tableIndex) { RELEASE_ASSERT(m_rareData); return m_rareData->m_switchJumpTables[tableIndex]; }
618 void clearSwitchJumpTables()
622 m_rareData->m_switchJumpTables.clear();
625 size_t numberOfStringSwitchJumpTables() const { return m_rareData ? m_rareData->m_stringSwitchJumpTables.size() : 0; }
626 StringJumpTable& addStringSwitchJumpTable() { createRareDataIfNecessary(); m_rareData->m_stringSwitchJumpTables.append(StringJumpTable()); return m_rareData->m_stringSwitchJumpTables.last(); }
627 StringJumpTable& stringSwitchJumpTable(int tableIndex) { RELEASE_ASSERT(m_rareData); return m_rareData->m_stringSwitchJumpTables[tableIndex]; }
629 // Live callee registers at yield points.
630 const FastBitVector& liveCalleeLocalsAtYield(unsigned index) const
632 RELEASE_ASSERT(m_rareData);
633 return m_rareData->m_liveCalleeLocalsAtYield[index];
635 FastBitVector& liveCalleeLocalsAtYield(unsigned index)
637 RELEASE_ASSERT(m_rareData);
638 return m_rareData->m_liveCalleeLocalsAtYield[index];
641 EvalCodeCache& evalCodeCache() { createRareDataIfNecessary(); return m_rareData->m_evalCodeCache; }
644 // Shrink prior to generating machine code that may point directly into vectors.
647 // Shrink after generating machine code, and after possibly creating new vectors
648 // and appending to others. At this time it is not safe to shrink certain vectors
649 // because we would have generated machine code that references them directly.
652 void shrinkToFit(ShrinkMode);
654 // Functions for controlling when JITting kicks in, in a mixed mode
657 bool checkIfJITThresholdReached()
659 return m_llintExecuteCounter.checkIfThresholdCrossedAndSet(this);
662 void dontJITAnytimeSoon()
664 m_llintExecuteCounter.deferIndefinitely();
667 void jitAfterWarmUp()
669 m_llintExecuteCounter.setNewThreshold(Options::thresholdForJITAfterWarmUp(), this);
674 m_llintExecuteCounter.setNewThreshold(Options::thresholdForJITSoon(), this);
677 const BaselineExecutionCounter& llintExecuteCounter() const
679 return m_llintExecuteCounter;
682 typedef HashMap<Structure*, Bag<LLIntPrototypeLoadAdaptiveStructureWatchpoint>> StructureWatchpointMap;
683 StructureWatchpointMap& llintGetByIdWatchpointMap() { return m_llintGetByIdWatchpointMap; }
685 // Functions for controlling when tiered compilation kicks in. This
686 // controls both when the optimizing compiler is invoked and when OSR
687 // entry happens. Two triggers exist: the loop trigger and the return
688 // trigger. In either case, when an addition to m_jitExecuteCounter
689 // causes it to become non-negative, the optimizing compiler is
690 // invoked. This includes a fast check to see if this CodeBlock has
691 // already been optimized (i.e. replacement() returns a CodeBlock
692 // that was optimized with a higher tier JIT than this one). In the
693 // case of the loop trigger, if the optimized compilation succeeds
694 // (or has already succeeded in the past) then OSR is attempted to
695 // redirect program flow into the optimized code.
697 // These functions are called from within the optimization triggers,
698 // and are used as a single point at which we define the heuristics
699 // for how much warm-up is mandated before the next optimization
700 // trigger files. All CodeBlocks start out with optimizeAfterWarmUp(),
701 // as this is called from the CodeBlock constructor.
703 // When we observe a lot of speculation failures, we trigger a
704 // reoptimization. But each time, we increase the optimization trigger
705 // to avoid thrashing.
706 JS_EXPORT_PRIVATE unsigned reoptimizationRetryCounter() const;
707 void countReoptimization();
709 static unsigned numberOfLLIntBaselineCalleeSaveRegisters() { return RegisterSet::llintBaselineCalleeSaveRegisters().numberOfSetRegisters(); }
710 static size_t llintBaselineCalleeSaveSpaceAsVirtualRegisters();
711 size_t calleeSaveSpaceAsVirtualRegisters();
713 unsigned numberOfDFGCompiles();
715 int32_t codeTypeThresholdMultiplier() const;
717 int32_t adjustedCounterValue(int32_t desiredThreshold);
719 int32_t* addressOfJITExecuteCounter()
721 return &m_jitExecuteCounter.m_counter;
724 static ptrdiff_t offsetOfJITExecuteCounter() { return OBJECT_OFFSETOF(CodeBlock, m_jitExecuteCounter) + OBJECT_OFFSETOF(BaselineExecutionCounter, m_counter); }
725 static ptrdiff_t offsetOfJITExecutionActiveThreshold() { return OBJECT_OFFSETOF(CodeBlock, m_jitExecuteCounter) + OBJECT_OFFSETOF(BaselineExecutionCounter, m_activeThreshold); }
726 static ptrdiff_t offsetOfJITExecutionTotalCount() { return OBJECT_OFFSETOF(CodeBlock, m_jitExecuteCounter) + OBJECT_OFFSETOF(BaselineExecutionCounter, m_totalCount); }
728 const BaselineExecutionCounter& jitExecuteCounter() const { return m_jitExecuteCounter; }
730 unsigned optimizationDelayCounter() const { return m_optimizationDelayCounter; }
732 // Check if the optimization threshold has been reached, and if not,
733 // adjust the heuristics accordingly. Returns true if the threshold has
735 bool checkIfOptimizationThresholdReached();
737 // Call this to force the next optimization trigger to fire. This is
738 // rarely wise, since optimization triggers are typically more
739 // expensive than executing baseline code.
740 void optimizeNextInvocation();
742 // Call this to prevent optimization from happening again. Note that
743 // optimization will still happen after roughly 2^29 invocations,
744 // so this is really meant to delay that as much as possible. This
745 // is called if optimization failed, and we expect it to fail in
746 // the future as well.
747 void dontOptimizeAnytimeSoon();
749 // Call this to reinitialize the counter to its starting state,
750 // forcing a warm-up to happen before the next optimization trigger
751 // fires. This is called in the CodeBlock constructor. It also
752 // makes sense to call this if an OSR exit occurred. Note that
753 // OSR exit code is code generated, so the value of the execute
754 // counter that this corresponds to is also available directly.
755 void optimizeAfterWarmUp();
757 // Call this to force an optimization trigger to fire only after
759 void optimizeAfterLongWarmUp();
761 // Call this to cause an optimization trigger to fire soon, but
762 // not necessarily the next one. This makes sense if optimization
763 // succeeds. Successfuly optimization means that all calls are
764 // relinked to the optimized code, so this only affects call
765 // frames that are still executing this CodeBlock. The value here
766 // is tuned to strike a balance between the cost of OSR entry
767 // (which is too high to warrant making every loop back edge to
768 // trigger OSR immediately) and the cost of executing baseline
769 // code (which is high enough that we don't necessarily want to
770 // have a full warm-up). The intuition for calling this instead of
771 // optimizeNextInvocation() is for the case of recursive functions
772 // with loops. Consider that there may be N call frames of some
773 // recursive function, for a reasonably large value of N. The top
774 // one triggers optimization, and then returns, and then all of
775 // the others return. We don't want optimization to be triggered on
776 // each return, as that would be superfluous. It only makes sense
777 // to trigger optimization if one of those functions becomes hot
778 // in the baseline code.
781 void forceOptimizationSlowPathConcurrently();
783 void setOptimizationThresholdBasedOnCompilationResult(CompilationResult);
785 uint32_t osrExitCounter() const { return m_osrExitCounter; }
787 void countOSRExit() { m_osrExitCounter++; }
789 uint32_t* addressOfOSRExitCounter() { return &m_osrExitCounter; }
791 static ptrdiff_t offsetOfOSRExitCounter() { return OBJECT_OFFSETOF(CodeBlock, m_osrExitCounter); }
793 uint32_t adjustedExitCountThreshold(uint32_t desiredThreshold);
794 uint32_t exitCountThresholdForReoptimization();
795 uint32_t exitCountThresholdForReoptimizationFromLoop();
796 bool shouldReoptimizeNow();
797 bool shouldReoptimizeFromLoopNow();
799 void setCalleeSaveRegisters(RegisterSet);
800 void setCalleeSaveRegisters(std::unique_ptr<RegisterAtOffsetList>);
802 RegisterAtOffsetList* calleeSaveRegisters() const { return m_calleeSaveRegisters.get(); }
804 static unsigned numberOfLLIntBaselineCalleeSaveRegisters() { return 0; }
805 static size_t llintBaselineCalleeSaveSpaceAsVirtualRegisters() { return 0; };
806 void optimizeAfterWarmUp() { }
807 unsigned numberOfDFGCompiles() { return 0; }
810 bool shouldOptimizeNow();
811 void updateAllValueProfilePredictions();
812 void updateAllArrayPredictions();
813 void updateAllPredictions();
815 unsigned frameRegisterCount();
816 int stackPointerOffset();
818 bool hasOpDebugForLineAndColumn(unsigned line, unsigned column);
820 bool hasDebuggerRequests() const { return m_debuggerRequests; }
821 void* debuggerRequestsAddress() { return &m_debuggerRequests; }
823 void addBreakpoint(unsigned numBreakpoints);
824 void removeBreakpoint(unsigned numBreakpoints)
826 ASSERT(m_numBreakpoints >= numBreakpoints);
827 m_numBreakpoints -= numBreakpoints;
831 SteppingModeDisabled,
834 void setSteppingMode(SteppingMode);
836 void clearDebuggerRequests()
838 m_steppingMode = SteppingModeDisabled;
839 m_numBreakpoints = 0;
842 bool wasCompiledWithDebuggingOpcodes() const { return m_unlinkedCode->wasCompiledWithDebuggingOpcodes(); }
844 // FIXME: Make these remaining members private.
846 int m_numCalleeLocals;
849 // This is intentionally public; it's the responsibility of anyone doing any
850 // of the following to hold the lock:
852 // - Modifying any inline cache in this code block.
854 // - Quering any inline cache in this code block, from a thread other than
857 // Additionally, it's only legal to modify the inline cache on the main
858 // thread. This means that the main thread can query the inline cache without
859 // locking. This is crucial since executing the inline cache is effectively
862 // Another exception to the rules is that the GC can do whatever it wants
863 // without holding any locks, because the GC is guaranteed to wait until any
864 // concurrent compilation threads finish what they're doing.
865 mutable ConcurrentJITLock m_lock;
867 Atomic<bool> m_visitWeaklyHasBeenCalled;
869 bool m_shouldAlwaysBeInlined; // Not a bitfield because the JIT wants to store to it.
872 unsigned m_capabilityLevelState : 2; // DFG::CapabilityLevel
875 bool m_allTransitionsHaveBeenMarked : 1; // Initialized and used on every GC.
877 bool m_didFailFTLCompilation : 1;
878 bool m_hasBeenCompiledWithFTL : 1;
879 bool m_isConstructor : 1;
880 bool m_isStrictMode : 1;
881 unsigned m_codeType : 2; // CodeType
883 // Internal methods for use by validation code. It would be private if it wasn't
884 // for the fact that we use it from anonymous namespaces.
885 void beginValidationDidFail();
886 NO_RETURN_DUE_TO_CRASH void endValidationDidFail();
889 WTF_MAKE_FAST_ALLOCATED;
891 Vector<HandlerInfo> m_exceptionHandlers;
893 // Buffers used for large array literals
894 Vector<Vector<JSValue>> m_constantBuffers;
897 Vector<SimpleJumpTable> m_switchJumpTables;
898 Vector<StringJumpTable> m_stringSwitchJumpTables;
900 Vector<FastBitVector> m_liveCalleeLocalsAtYield;
902 EvalCodeCache m_evalCodeCache;
905 void clearExceptionHandlers()
908 m_rareData->m_exceptionHandlers.clear();
911 void appendExceptionHandler(const HandlerInfo& handler)
913 createRareDataIfNecessary(); // We may be handling the exception of an inlined call frame.
914 m_rareData->m_exceptionHandlers.append(handler);
917 CallSiteIndex newExceptionHandlingCallSiteIndex(CallSiteIndex originalCallSite);
920 void setPCToCodeOriginMap(std::unique_ptr<PCToCodeOriginMap>&&);
921 Optional<CodeOrigin> findPC(void* pc);
925 void finalizeLLIntInlineCaches();
926 void finalizeBaselineJITInlineCaches();
929 void tallyFrequentExitSites();
931 void tallyFrequentExitSites() { }
935 friend class CodeBlockSet;
937 CodeBlock* specialOSREntryBlockOrNull();
939 void noticeIncomingCall(ExecState* callerFrame);
941 double optimizationThresholdScalingFactor();
943 void updateAllPredictionsAndCountLiveness(unsigned& numberOfLiveNonArgumentValueProfiles, unsigned& numberOfSamplesInProfiles);
945 void setConstantRegisters(const Vector<WriteBarrier<Unknown>>& constants, const Vector<SourceCodeRepresentation>& constantsSourceCodeRepresentation);
947 void replaceConstant(int index, JSValue value)
949 ASSERT(isConstantRegisterIndex(index) && static_cast<size_t>(index - FirstConstantRegisterIndex) < m_constantRegisters.size());
950 m_constantRegisters[index - FirstConstantRegisterIndex].set(m_globalObject->vm(), this, value);
954 PrintStream&, ExecState*, const Instruction* begin, const Instruction*&,
955 const StubInfoMap& = StubInfoMap(), const CallLinkInfoMap& = CallLinkInfoMap());
957 CString registerName(int r) const;
958 CString constantName(int index) const;
959 void printUnaryOp(PrintStream&, ExecState*, int location, const Instruction*&, const char* op);
960 void printBinaryOp(PrintStream&, ExecState*, int location, const Instruction*&, const char* op);
961 void printConditionalJump(PrintStream&, ExecState*, const Instruction*, const Instruction*&, int location, const char* op);
962 void printGetByIdOp(PrintStream&, ExecState*, int location, const Instruction*&);
963 void printGetByIdCacheStatus(PrintStream&, ExecState*, int location, const StubInfoMap&);
964 enum CacheDumpMode { DumpCaches, DontDumpCaches };
965 void printCallOp(PrintStream&, ExecState*, int location, const Instruction*&, const char* op, CacheDumpMode, bool& hasPrintedProfiling, const CallLinkInfoMap&);
966 void printPutByIdOp(PrintStream&, ExecState*, int location, const Instruction*&, const char* op);
967 void printPutByIdCacheStatus(PrintStream&, int location, const StubInfoMap&);
968 void printLocationAndOp(PrintStream&, ExecState*, int location, const Instruction*&, const char* op);
969 void printLocationOpAndRegisterOperand(PrintStream&, ExecState*, int location, const Instruction*& it, const char* op, int operand);
971 void beginDumpProfiling(PrintStream&, bool& hasPrintedProfiling);
972 void dumpValueProfiling(PrintStream&, const Instruction*&, bool& hasPrintedProfiling);
973 void dumpArrayProfiling(PrintStream&, const Instruction*&, bool& hasPrintedProfiling);
974 void dumpRareCaseProfile(PrintStream&, const char* name, RareCaseProfile*, bool& hasPrintedProfiling);
975 void dumpResultProfile(PrintStream&, ResultProfile*, bool& hasPrintedProfiling);
977 bool shouldVisitStrongly();
978 bool shouldJettisonDueToWeakReference();
979 bool shouldJettisonDueToOldAge();
981 void propagateTransitions(SlotVisitor&);
982 void determineLiveness(SlotVisitor&);
984 void stronglyVisitStrongReferences(SlotVisitor&);
985 void stronglyVisitWeakReferences(SlotVisitor&);
986 void visitOSRExitTargets(SlotVisitor&);
988 std::chrono::milliseconds timeSinceCreation()
990 return std::chrono::duration_cast<std::chrono::milliseconds>(
991 std::chrono::steady_clock::now() - m_creationTime);
994 void createRareDataIfNecessary()
997 m_rareData = std::make_unique<RareData>();
1000 void insertBasicBlockBoundariesForControlFlowProfiler(RefCountedArray<Instruction>&);
1002 WriteBarrier<UnlinkedCodeBlock> m_unlinkedCode;
1003 int m_numParameters;
1005 unsigned m_debuggerRequests;
1007 unsigned m_hasDebuggerStatement : 1;
1008 unsigned m_steppingMode : 1;
1009 unsigned m_numBreakpoints : 30;
1012 WriteBarrier<ExecutableBase> m_ownerExecutable;
1015 RefCountedArray<Instruction> m_instructions;
1016 VirtualRegister m_thisRegister;
1017 VirtualRegister m_scopeRegister;
1018 mutable CodeBlockHash m_hash;
1020 RefPtr<SourceProvider> m_source;
1021 unsigned m_sourceOffset;
1022 unsigned m_firstLineColumnOffset;
1024 RefCountedArray<LLIntCallLinkInfo> m_llintCallLinkInfos;
1025 SentinelLinkedList<LLIntCallLinkInfo, BasicRawSentinelNode<LLIntCallLinkInfo>> m_incomingLLIntCalls;
1026 StructureWatchpointMap m_llintGetByIdWatchpointMap;
1027 RefPtr<JITCode> m_jitCode;
1029 std::unique_ptr<RegisterAtOffsetList> m_calleeSaveRegisters;
1030 Bag<StructureStubInfo> m_stubInfos;
1031 Bag<ByValInfo> m_byValInfos;
1032 Bag<CallLinkInfo> m_callLinkInfos;
1033 SentinelLinkedList<CallLinkInfo, BasicRawSentinelNode<CallLinkInfo>> m_incomingCalls;
1034 SentinelLinkedList<PolymorphicCallNode, BasicRawSentinelNode<PolymorphicCallNode>> m_incomingPolymorphicCalls;
1035 std::unique_ptr<PCToCodeOriginMap> m_pcToCodeOriginMap;
1037 std::unique_ptr<CompactJITCodeMap> m_jitCodeMap;
1039 // This is relevant to non-DFG code blocks that serve as the profiled code block
1040 // for DFG code blocks.
1041 DFG::ExitProfile m_exitProfile;
1042 CompressedLazyOperandValueProfileHolder m_lazyOperandValueProfiles;
1044 RefCountedArray<ValueProfile> m_argumentValueProfiles;
1045 RefCountedArray<ValueProfile> m_valueProfiles;
1046 SegmentedVector<RareCaseProfile, 8> m_rareCaseProfiles;
1047 SegmentedVector<ResultProfile, 8> m_resultProfiles;
1048 typedef HashMap<unsigned, unsigned, IntHash<unsigned>, WTF::UnsignedWithZeroKeyHashTraits<unsigned>> BytecodeOffsetToResultProfileIndexMap;
1049 std::unique_ptr<BytecodeOffsetToResultProfileIndexMap> m_bytecodeOffsetToResultProfileIndexMap;
1050 RefCountedArray<ArrayAllocationProfile> m_arrayAllocationProfiles;
1051 ArrayProfileVector m_arrayProfiles;
1052 RefCountedArray<ObjectAllocationProfile> m_objectAllocationProfiles;
1055 COMPILE_ASSERT(sizeof(Register) == sizeof(WriteBarrier<Unknown>), Register_must_be_same_size_as_WriteBarrier_Unknown);
1056 // TODO: This could just be a pointer to m_unlinkedCodeBlock's data, but the DFG mutates
1057 // it, so we're stuck with it for now.
1058 Vector<WriteBarrier<Unknown>> m_constantRegisters;
1059 Vector<SourceCodeRepresentation> m_constantsSourceCodeRepresentation;
1060 RefCountedArray<WriteBarrier<FunctionExecutable>> m_functionDecls;
1061 RefCountedArray<WriteBarrier<FunctionExecutable>> m_functionExprs;
1063 WriteBarrier<CodeBlock> m_alternative;
1065 BaselineExecutionCounter m_llintExecuteCounter;
1067 BaselineExecutionCounter m_jitExecuteCounter;
1068 uint32_t m_osrExitCounter;
1069 uint16_t m_optimizationDelayCounter;
1070 uint16_t m_reoptimizationRetryCounter;
1072 std::chrono::steady_clock::time_point m_creationTime;
1074 std::unique_ptr<BytecodeLivenessAnalysis> m_livenessAnalysis;
1076 std::unique_ptr<RareData> m_rareData;
1078 UnconditionalFinalizer m_unconditionalFinalizer;
1079 WeakReferenceHarvester m_weakReferenceHarvester;
1082 // Program code is not marked by any function, so we make the global object
1083 // responsible for marking it.
1085 class GlobalCodeBlock : public CodeBlock {
1086 typedef CodeBlock Base;
1090 GlobalCodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, GlobalCodeBlock& other)
1091 : CodeBlock(vm, structure, CopyParsedBlock, other)
1095 GlobalCodeBlock(VM* vm, Structure* structure, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock, JSScope* scope, PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset, unsigned firstLineColumnOffset)
1096 : CodeBlock(vm, structure, ownerExecutable, unlinkedCodeBlock, scope, sourceProvider, sourceOffset, firstLineColumnOffset)
1101 class ProgramCodeBlock : public GlobalCodeBlock {
1103 typedef GlobalCodeBlock Base;
1106 static ProgramCodeBlock* create(VM* vm, CopyParsedBlockTag, ProgramCodeBlock& other)
1108 ProgramCodeBlock* instance = new (NotNull, allocateCell<ProgramCodeBlock>(vm->heap))
1109 ProgramCodeBlock(vm, vm->programCodeBlockStructure.get(), CopyParsedBlock, other);
1110 instance->finishCreation(*vm, CopyParsedBlock, other);
1114 static ProgramCodeBlock* create(VM* vm, ProgramExecutable* ownerExecutable, UnlinkedProgramCodeBlock* unlinkedCodeBlock,
1115 JSScope* scope, PassRefPtr<SourceProvider> sourceProvider, unsigned firstLineColumnOffset)
1117 ProgramCodeBlock* instance = new (NotNull, allocateCell<ProgramCodeBlock>(vm->heap))
1118 ProgramCodeBlock(vm, vm->programCodeBlockStructure.get(), ownerExecutable, unlinkedCodeBlock, scope, sourceProvider, firstLineColumnOffset);
1119 instance->finishCreation(*vm, ownerExecutable, unlinkedCodeBlock, scope);
1123 static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
1125 return Structure::create(vm, globalObject, prototype, TypeInfo(CellType, StructureFlags), info());
1129 ProgramCodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, ProgramCodeBlock& other)
1130 : GlobalCodeBlock(vm, structure, CopyParsedBlock, other)
1134 ProgramCodeBlock(VM* vm, Structure* structure, ProgramExecutable* ownerExecutable, UnlinkedProgramCodeBlock* unlinkedCodeBlock,
1135 JSScope* scope, PassRefPtr<SourceProvider> sourceProvider, unsigned firstLineColumnOffset)
1136 : GlobalCodeBlock(vm, structure, ownerExecutable, unlinkedCodeBlock, scope, sourceProvider, 0, firstLineColumnOffset)
1140 static void destroy(JSCell*);
1143 class ModuleProgramCodeBlock : public GlobalCodeBlock {
1145 typedef GlobalCodeBlock Base;
1148 static ModuleProgramCodeBlock* create(VM* vm, CopyParsedBlockTag, ModuleProgramCodeBlock& other)
1150 ModuleProgramCodeBlock* instance = new (NotNull, allocateCell<ModuleProgramCodeBlock>(vm->heap))
1151 ModuleProgramCodeBlock(vm, vm->moduleProgramCodeBlockStructure.get(), CopyParsedBlock, other);
1152 instance->finishCreation(*vm, CopyParsedBlock, other);
1156 static ModuleProgramCodeBlock* create(VM* vm, ModuleProgramExecutable* ownerExecutable, UnlinkedModuleProgramCodeBlock* unlinkedCodeBlock,
1157 JSScope* scope, PassRefPtr<SourceProvider> sourceProvider, unsigned firstLineColumnOffset)
1159 ModuleProgramCodeBlock* instance = new (NotNull, allocateCell<ModuleProgramCodeBlock>(vm->heap))
1160 ModuleProgramCodeBlock(vm, vm->moduleProgramCodeBlockStructure.get(), ownerExecutable, unlinkedCodeBlock, scope, sourceProvider, firstLineColumnOffset);
1161 instance->finishCreation(*vm, ownerExecutable, unlinkedCodeBlock, scope);
1165 static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
1167 return Structure::create(vm, globalObject, prototype, TypeInfo(CellType, StructureFlags), info());
1171 ModuleProgramCodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, ModuleProgramCodeBlock& other)
1172 : GlobalCodeBlock(vm, structure, CopyParsedBlock, other)
1176 ModuleProgramCodeBlock(VM* vm, Structure* structure, ModuleProgramExecutable* ownerExecutable, UnlinkedModuleProgramCodeBlock* unlinkedCodeBlock,
1177 JSScope* scope, PassRefPtr<SourceProvider> sourceProvider, unsigned firstLineColumnOffset)
1178 : GlobalCodeBlock(vm, structure, ownerExecutable, unlinkedCodeBlock, scope, sourceProvider, 0, firstLineColumnOffset)
1182 static void destroy(JSCell*);
1185 class EvalCodeBlock : public GlobalCodeBlock {
1187 typedef GlobalCodeBlock Base;
1190 static EvalCodeBlock* create(VM* vm, CopyParsedBlockTag, EvalCodeBlock& other)
1192 EvalCodeBlock* instance = new (NotNull, allocateCell<EvalCodeBlock>(vm->heap))
1193 EvalCodeBlock(vm, vm->evalCodeBlockStructure.get(), CopyParsedBlock, other);
1194 instance->finishCreation(*vm, CopyParsedBlock, other);
1198 static EvalCodeBlock* create(VM* vm, EvalExecutable* ownerExecutable, UnlinkedEvalCodeBlock* unlinkedCodeBlock,
1199 JSScope* scope, PassRefPtr<SourceProvider> sourceProvider)
1201 EvalCodeBlock* instance = new (NotNull, allocateCell<EvalCodeBlock>(vm->heap))
1202 EvalCodeBlock(vm, vm->evalCodeBlockStructure.get(), ownerExecutable, unlinkedCodeBlock, scope, sourceProvider);
1203 instance->finishCreation(*vm, ownerExecutable, unlinkedCodeBlock, scope);
1207 static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
1209 return Structure::create(vm, globalObject, prototype, TypeInfo(CellType, StructureFlags), info());
1212 const Identifier& variable(unsigned index) { return unlinkedEvalCodeBlock()->variable(index); }
1213 unsigned numVariables() { return unlinkedEvalCodeBlock()->numVariables(); }
1216 EvalCodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, EvalCodeBlock& other)
1217 : GlobalCodeBlock(vm, structure, CopyParsedBlock, other)
1221 EvalCodeBlock(VM* vm, Structure* structure, EvalExecutable* ownerExecutable, UnlinkedEvalCodeBlock* unlinkedCodeBlock,
1222 JSScope* scope, PassRefPtr<SourceProvider> sourceProvider)
1223 : GlobalCodeBlock(vm, structure, ownerExecutable, unlinkedCodeBlock, scope, sourceProvider, 0, 1)
1227 static void destroy(JSCell*);
1230 UnlinkedEvalCodeBlock* unlinkedEvalCodeBlock() const { return jsCast<UnlinkedEvalCodeBlock*>(unlinkedCodeBlock()); }
1233 class FunctionCodeBlock : public CodeBlock {
1235 typedef CodeBlock Base;
1238 static FunctionCodeBlock* create(VM* vm, CopyParsedBlockTag, FunctionCodeBlock& other)
1240 FunctionCodeBlock* instance = new (NotNull, allocateCell<FunctionCodeBlock>(vm->heap))
1241 FunctionCodeBlock(vm, vm->functionCodeBlockStructure.get(), CopyParsedBlock, other);
1242 instance->finishCreation(*vm, CopyParsedBlock, other);
1246 static FunctionCodeBlock* create(VM* vm, FunctionExecutable* ownerExecutable, UnlinkedFunctionCodeBlock* unlinkedCodeBlock, JSScope* scope,
1247 PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset, unsigned firstLineColumnOffset)
1249 FunctionCodeBlock* instance = new (NotNull, allocateCell<FunctionCodeBlock>(vm->heap))
1250 FunctionCodeBlock(vm, vm->functionCodeBlockStructure.get(), ownerExecutable, unlinkedCodeBlock, scope, sourceProvider, sourceOffset, firstLineColumnOffset);
1251 instance->finishCreation(*vm, ownerExecutable, unlinkedCodeBlock, scope);
1255 static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
1257 return Structure::create(vm, globalObject, prototype, TypeInfo(CellType, StructureFlags), info());
1261 FunctionCodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, FunctionCodeBlock& other)
1262 : CodeBlock(vm, structure, CopyParsedBlock, other)
1266 FunctionCodeBlock(VM* vm, Structure* structure, FunctionExecutable* ownerExecutable, UnlinkedFunctionCodeBlock* unlinkedCodeBlock, JSScope* scope,
1267 PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset, unsigned firstLineColumnOffset)
1268 : CodeBlock(vm, structure, ownerExecutable, unlinkedCodeBlock, scope, sourceProvider, sourceOffset, firstLineColumnOffset)
1272 static void destroy(JSCell*);
1275 #if ENABLE(WEBASSEMBLY)
1276 class WebAssemblyCodeBlock : public CodeBlock {
1278 typedef CodeBlock Base;
1281 static WebAssemblyCodeBlock* create(VM* vm, CopyParsedBlockTag, WebAssemblyCodeBlock& other)
1283 WebAssemblyCodeBlock* instance = new (NotNull, allocateCell<WebAssemblyCodeBlock>(vm->heap))
1284 WebAssemblyCodeBlock(vm, vm->webAssemblyCodeBlockStructure.get(), CopyParsedBlock, other);
1285 instance->finishCreation(*vm, CopyParsedBlock, other);
1289 static WebAssemblyCodeBlock* create(VM* vm, WebAssemblyExecutable* ownerExecutable, JSGlobalObject* globalObject)
1291 WebAssemblyCodeBlock* instance = new (NotNull, allocateCell<WebAssemblyCodeBlock>(vm->heap))
1292 WebAssemblyCodeBlock(vm, vm->webAssemblyCodeBlockStructure.get(), ownerExecutable, globalObject);
1293 instance->finishCreation(*vm, ownerExecutable, globalObject);
1297 static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
1299 return Structure::create(vm, globalObject, prototype, TypeInfo(CellType, StructureFlags), info());
1303 WebAssemblyCodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, WebAssemblyCodeBlock& other)
1304 : CodeBlock(vm, structure, CopyParsedBlock, other)
1308 WebAssemblyCodeBlock(VM* vm, Structure* structure, WebAssemblyExecutable* ownerExecutable, JSGlobalObject* globalObject)
1309 : CodeBlock(vm, structure, ownerExecutable, globalObject)
1313 static void destroy(JSCell*);
1317 inline void clearLLIntGetByIdCache(Instruction* instruction)
1319 instruction[0].u.opcode = LLInt::getOpcode(op_get_by_id);
1320 instruction[4].u.pointer = nullptr;
1321 instruction[5].u.pointer = nullptr;
1322 instruction[6].u.pointer = nullptr;
1325 inline Register& ExecState::r(int index)
1327 CodeBlock* codeBlock = this->codeBlock();
1328 if (codeBlock->isConstantRegisterIndex(index))
1329 return *reinterpret_cast<Register*>(&codeBlock->constantRegister(index));
1333 inline Register& ExecState::r(VirtualRegister reg)
1335 return r(reg.offset());
1338 inline Register& ExecState::uncheckedR(int index)
1340 RELEASE_ASSERT(index < FirstConstantRegisterIndex);
1344 inline Register& ExecState::uncheckedR(VirtualRegister reg)
1346 return uncheckedR(reg.offset());
1349 inline void CodeBlock::clearVisitWeaklyHasBeenCalled()
1351 m_visitWeaklyHasBeenCalled.store(false, std::memory_order_relaxed);
1354 inline void CodeBlockSet::mark(const LockHolder& locker, void* candidateCodeBlock)
1356 ASSERT(m_lock.isLocked());
1357 // We have to check for 0 and -1 because those are used by the HashMap as markers.
1358 uintptr_t value = reinterpret_cast<uintptr_t>(candidateCodeBlock);
1360 // This checks for both of those nasty cases in one go.
1366 CodeBlock* codeBlock = static_cast<CodeBlock*>(candidateCodeBlock);
1367 if (!m_oldCodeBlocks.contains(codeBlock) && !m_newCodeBlocks.contains(codeBlock))
1370 mark(locker, codeBlock);
1373 inline void CodeBlockSet::mark(const LockHolder&, CodeBlock* codeBlock)
1378 // Try to recover gracefully if we forget to execute a barrier for a
1379 // CodeBlock that does value profiling. This is probably overkill, but we
1380 // have always done it.
1381 Heap::heap(codeBlock)->writeBarrier(codeBlock);
1383 m_currentlyExecuting.add(codeBlock);
1386 template <typename Functor> inline void ScriptExecutable::forEachCodeBlock(Functor&& functor)
1389 case ProgramExecutableType: {
1390 if (CodeBlock* codeBlock = static_cast<CodeBlock*>(jsCast<ProgramExecutable*>(this)->m_programCodeBlock.get()))
1391 codeBlock->forEachRelatedCodeBlock(std::forward<Functor>(functor));
1395 case EvalExecutableType: {
1396 if (CodeBlock* codeBlock = static_cast<CodeBlock*>(jsCast<EvalExecutable*>(this)->m_evalCodeBlock.get()))
1397 codeBlock->forEachRelatedCodeBlock(std::forward<Functor>(functor));
1401 case FunctionExecutableType: {
1402 Functor f(std::forward<Functor>(functor));
1403 FunctionExecutable* executable = jsCast<FunctionExecutable*>(this);
1404 if (CodeBlock* codeBlock = static_cast<CodeBlock*>(executable->m_codeBlockForCall.get()))
1405 codeBlock->forEachRelatedCodeBlock(f);
1406 if (CodeBlock* codeBlock = static_cast<CodeBlock*>(executable->m_codeBlockForConstruct.get()))
1407 codeBlock->forEachRelatedCodeBlock(f);
1411 case ModuleProgramExecutableType: {
1412 if (CodeBlock* codeBlock = static_cast<CodeBlock*>(jsCast<ModuleProgramExecutable*>(this)->m_moduleProgramCodeBlock.get()))
1413 codeBlock->forEachRelatedCodeBlock(std::forward<Functor>(functor));
1418 RELEASE_ASSERT_NOT_REACHED();
1422 #define CODEBLOCK_LOG_EVENT(codeBlock, summary, details) \
1423 (codeBlock->vm()->logEvent(codeBlock, summary, [&] () { return toCString details; }))
1427 #endif // CodeBlock_h