2 * Copyright (C) 2008-2017 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.
32 #include "ArrayProfile.h"
33 #include "ByValInfo.h"
34 #include "BytecodeConventions.h"
35 #include "CallLinkInfo.h"
36 #include "CallReturnOffsetToBytecodeOffset.h"
37 #include "CodeBlockHash.h"
38 #include "CodeOrigin.h"
40 #include "CompactJITCodeMap.h"
41 #include "ConcurrentJSLock.h"
42 #include "DFGCommon.h"
43 #include "DFGExitProfile.h"
44 #include "DeferredCompilationCallback.h"
45 #include "DirectEvalCodeCache.h"
46 #include "EvalExecutable.h"
47 #include "ExecutionCounter.h"
48 #include "ExpressionRangeInfo.h"
49 #include "FunctionExecutable.h"
50 #include "HandlerInfo.h"
51 #include "Instruction.h"
53 #include "JITMathICForwards.h"
55 #include "JSGlobalObject.h"
56 #include "JumpTable.h"
57 #include "LLIntCallLinkInfo.h"
58 #include "LLIntPrototypeLoadAdaptiveStructureWatchpoint.h"
59 #include "LazyOperandValueProfile.h"
60 #include "ModuleProgramExecutable.h"
61 #include "ObjectAllocationProfile.h"
63 #include "ProfilerJettisonReason.h"
64 #include "ProgramExecutable.h"
65 #include "PutPropertySlot.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>
81 class BytecodeLivenessAnalysis;
84 class JSModuleEnvironment;
85 class LLIntOffsetsExtractor;
86 class PCToCodeOriginMap;
87 class RegisterAtOffsetList;
88 class StructureStubInfo;
90 enum class AccessType : int8_t;
94 typedef HashMap<CodeOrigin, StructureStubInfo*, CodeOriginApproximateHash> StubInfoMap;
96 enum ReoptimizationMode { DontCountReoptimization, CountReoptimization };
98 class CodeBlock : public JSCell {
100 friend class BytecodeLivenessAnalysis;
102 friend class LLIntOffsetsExtractor;
104 class UnconditionalFinalizer : public JSC::UnconditionalFinalizer {
105 void finalizeUnconditionally() override;
108 class WeakReferenceHarvester : public JSC::WeakReferenceHarvester {
109 void visitWeakReferences(SlotVisitor&) override;
113 enum CopyParsedBlockTag { CopyParsedBlock };
115 static const unsigned StructureFlags = Base::StructureFlags | StructureIsImmortal;
120 CodeBlock(VM*, Structure*, CopyParsedBlockTag, CodeBlock& other);
121 CodeBlock(VM*, Structure*, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock*, JSScope*, RefPtr<SourceProvider>&&, unsigned sourceOffset, unsigned firstLineColumnOffset);
123 void finishCreation(VM&, CopyParsedBlockTag, CodeBlock& other);
124 bool finishCreation(VM&, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock*, JSScope*);
126 WriteBarrier<JSGlobalObject> m_globalObject;
129 JS_EXPORT_PRIVATE ~CodeBlock();
131 UnlinkedCodeBlock* unlinkedCodeBlock() const { return m_unlinkedCode.get(); }
133 CString inferredName() const;
134 CodeBlockHash hash() const;
135 bool hasHash() const;
136 bool isSafeToComputeHash() const;
137 CString hashAsStringIfPossible() const;
138 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.
139 CString sourceCodeOnOneLine() const; // As sourceCodeForTools(), but replaces all whitespace runs with a single space.
140 void dumpAssumingJITType(PrintStream&, JITCode::JITType) const;
141 JS_EXPORT_PRIVATE void dump(PrintStream&) const;
143 int numParameters() const { return m_numParameters; }
144 void setNumParameters(int newValue);
146 int numberOfArgumentsToSkip() const { return m_numberOfArgumentsToSkip; }
148 int numCalleeLocals() const { return m_numCalleeLocals; }
150 int* addressOfNumParameters() { return &m_numParameters; }
151 static ptrdiff_t offsetOfNumParameters() { return OBJECT_OFFSETOF(CodeBlock, m_numParameters); }
153 CodeBlock* alternative() const { return static_cast<CodeBlock*>(m_alternative.get()); }
154 void setAlternative(VM&, CodeBlock*);
156 template <typename Functor> void forEachRelatedCodeBlock(Functor&& functor)
158 Functor f(std::forward<Functor>(functor));
159 Vector<CodeBlock*, 4> codeBlocks;
160 codeBlocks.append(this);
162 while (!codeBlocks.isEmpty()) {
163 CodeBlock* currentCodeBlock = codeBlocks.takeLast();
166 if (CodeBlock* alternative = currentCodeBlock->alternative())
167 codeBlocks.append(alternative);
168 if (CodeBlock* osrEntryBlock = currentCodeBlock->specialOSREntryBlockOrNull())
169 codeBlocks.append(osrEntryBlock);
173 CodeSpecializationKind specializationKind() const
175 return specializationFromIsConstruct(m_isConstructor);
178 CodeBlock* alternativeForJettison();
179 JS_EXPORT_PRIVATE CodeBlock* baselineAlternative();
181 // FIXME: Get rid of this.
182 // https://bugs.webkit.org/show_bug.cgi?id=123677
183 CodeBlock* baselineVersion();
185 static size_t estimatedSize(JSCell*);
186 static void visitChildren(JSCell*, SlotVisitor&);
187 void visitChildren(SlotVisitor&);
188 void visitWeakly(SlotVisitor&);
189 void clearVisitWeaklyHasBeenCalled();
192 void dumpSource(PrintStream&);
195 void dumpBytecode(PrintStream&);
196 void dumpBytecode(PrintStream& out, const Instruction* begin, const Instruction*& it, const StubInfoMap& = StubInfoMap(), const CallLinkInfoMap& = CallLinkInfoMap());
197 void dumpBytecode(PrintStream& out, unsigned bytecodeOffset, const StubInfoMap& = StubInfoMap(), const CallLinkInfoMap& = CallLinkInfoMap());
199 void dumpExceptionHandlers(PrintStream&);
200 void printStructures(PrintStream&, const Instruction*);
201 void printStructure(PrintStream&, const char* name, const Instruction*, int operand);
203 void dumpMathICStats();
205 bool isStrictMode() const { return m_isStrictMode; }
206 ECMAMode ecmaMode() const { return isStrictMode() ? StrictMode : NotStrictMode; }
208 bool hasInstalledVMTrapBreakpoints() const;
209 bool installVMTrapBreakpoints();
211 inline bool isKnownNotImmediate(int index)
213 if (index == m_thisRegister.offset() && !m_isStrictMode)
216 if (isConstantRegisterIndex(index))
217 return getConstant(index).isCell();
222 ALWAYS_INLINE bool isTemporaryRegisterIndex(int index)
224 return index >= m_numVars;
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;
235 std::optional<unsigned> bytecodeOffsetFromCallSiteIndex(CallSiteIndex);
237 void getStubInfoMap(const ConcurrentJSLocker&, StubInfoMap& result);
238 void getStubInfoMap(StubInfoMap& result);
240 void getCallLinkInfoMap(const ConcurrentJSLocker&, CallLinkInfoMap& result);
241 void getCallLinkInfoMap(CallLinkInfoMap& result);
243 void getByValInfoMap(const ConcurrentJSLocker&, ByValInfoMap& result);
244 void getByValInfoMap(ByValInfoMap& result);
247 StructureStubInfo* addStubInfo(AccessType);
248 JITAddIC* addJITAddIC(ArithProfile*);
249 JITMulIC* addJITMulIC(ArithProfile*);
250 JITNegIC* addJITNegIC(ArithProfile*);
251 JITSubIC* addJITSubIC(ArithProfile*);
252 Bag<StructureStubInfo>::iterator stubInfoBegin() { return m_stubInfos.begin(); }
253 Bag<StructureStubInfo>::iterator stubInfoEnd() { return m_stubInfos.end(); }
255 // O(n) operation. Use getStubInfoMap() unless you really only intend to get one
257 StructureStubInfo* findStubInfo(CodeOrigin);
259 ByValInfo* addByValInfo();
261 CallLinkInfo* addCallLinkInfo();
262 Bag<CallLinkInfo>::iterator callLinkInfosBegin() { return m_callLinkInfos.begin(); }
263 Bag<CallLinkInfo>::iterator callLinkInfosEnd() { return m_callLinkInfos.end(); }
265 // This is a slow function call used primarily for compiling OSR exits in the case
266 // that there had been inlining. Chances are if you want to use this, you're really
267 // looking for a CallLinkInfoMap to amortize the cost of calling this.
268 CallLinkInfo* getCallLinkInfoForBytecodeIndex(unsigned bytecodeIndex);
270 // We call this when we want to reattempt compiling something with the baseline JIT. Ideally
271 // the baseline JIT would not add data to CodeBlock, but instead it would put its data into
272 // a newly created JITCode, which could be thrown away if we bail on JIT compilation. Then we
273 // would be able to get rid of this silly function.
274 // FIXME: https://bugs.webkit.org/show_bug.cgi?id=159061
276 #endif // ENABLE(JIT)
278 void unlinkIncomingCalls();
281 void linkIncomingCall(ExecState* callerFrame, CallLinkInfo*);
282 void linkIncomingPolymorphicCall(ExecState* callerFrame, PolymorphicCallNode*);
283 #endif // ENABLE(JIT)
285 void linkIncomingCall(ExecState* callerFrame, LLIntCallLinkInfo*);
287 void setJITCodeMap(std::unique_ptr<CompactJITCodeMap> jitCodeMap)
289 m_jitCodeMap = WTFMove(jitCodeMap);
291 CompactJITCodeMap* jitCodeMap()
293 return m_jitCodeMap.get();
296 static void clearLLIntGetByIdCache(Instruction*);
298 unsigned bytecodeOffset(Instruction* returnAddress)
300 RELEASE_ASSERT(returnAddress >= instructions().begin() && returnAddress < instructions().end());
301 return static_cast<Instruction*>(returnAddress) - instructions().begin();
304 typedef JSC::Instruction Instruction;
305 typedef RefCountedArray<Instruction>& UnpackedInstructions;
307 unsigned numberOfInstructions() const { return m_instructions.size(); }
308 RefCountedArray<Instruction>& instructions() { return m_instructions; }
309 const RefCountedArray<Instruction>& instructions() const { return m_instructions; }
311 size_t predictedMachineCodeSize();
313 bool usesOpcode(OpcodeID);
315 unsigned instructionCount() const { return m_instructions.size(); }
317 // Exactly equivalent to codeBlock->ownerExecutable()->newReplacementCodeBlockFor(codeBlock->specializationKind())
318 CodeBlock* newReplacement();
320 void setJITCode(Ref<JITCode>&& code)
322 ASSERT(heap()->isDeferred());
323 heap()->reportExtraMemoryAllocated(code->size());
324 ConcurrentJSLocker locker(m_lock);
325 WTF::storeStoreFence(); // This is probably not needed because the lock will also do something similar, but it's good to be paranoid.
326 m_jitCode = WTFMove(code);
328 RefPtr<JITCode> jitCode() { return m_jitCode; }
329 static ptrdiff_t jitCodeOffset() { return OBJECT_OFFSETOF(CodeBlock, m_jitCode); }
330 JITCode::JITType jitType() const
332 JITCode* jitCode = m_jitCode.get();
333 WTF::loadLoadFence();
334 JITCode::JITType result = JITCode::jitTypeFor(jitCode);
335 WTF::loadLoadFence(); // This probably isn't needed. Oh well, paranoia is good.
339 bool hasBaselineJITProfiling() const
341 return jitType() == JITCode::BaselineJIT;
345 CodeBlock* replacement();
347 DFG::CapabilityLevel computeCapabilityLevel();
348 DFG::CapabilityLevel capabilityLevel();
349 DFG::CapabilityLevel capabilityLevelState() { return static_cast<DFG::CapabilityLevel>(m_capabilityLevelState); }
351 bool hasOptimizedReplacement(JITCode::JITType typeToReplace);
352 bool hasOptimizedReplacement(); // the typeToReplace is my JITType
355 void jettison(Profiler::JettisonReason, ReoptimizationMode = DontCountReoptimization, const FireDetail* = nullptr);
357 ExecutableBase* ownerExecutable() const { return m_ownerExecutable.get(); }
358 ScriptExecutable* ownerScriptExecutable() const { return jsCast<ScriptExecutable*>(m_ownerExecutable.get()); }
360 VM* vm() const { return m_vm; }
362 void setThisRegister(VirtualRegister thisRegister) { m_thisRegister = thisRegister; }
363 VirtualRegister thisRegister() const { return m_thisRegister; }
365 bool usesEval() const { return m_unlinkedCode->usesEval(); }
367 void setScopeRegister(VirtualRegister scopeRegister)
369 ASSERT(scopeRegister.isLocal() || !scopeRegister.isValid());
370 m_scopeRegister = scopeRegister;
373 VirtualRegister scopeRegister() const
375 return m_scopeRegister;
378 CodeType codeType() const
380 return static_cast<CodeType>(m_codeType);
383 PutPropertySlot::Context putByIdContext() const
385 if (codeType() == EvalCode)
386 return PutPropertySlot::PutByIdEval;
387 return PutPropertySlot::PutById;
390 SourceProvider* source() const { return m_source.get(); }
391 unsigned sourceOffset() const { return m_sourceOffset; }
392 unsigned firstLineColumnOffset() const { return m_firstLineColumnOffset; }
394 size_t numberOfJumpTargets() const { return m_unlinkedCode->numberOfJumpTargets(); }
395 unsigned jumpTarget(int index) const { return m_unlinkedCode->jumpTarget(index); }
397 String nameForRegister(VirtualRegister);
399 unsigned numberOfArgumentValueProfiles()
401 ASSERT(m_numParameters >= 0);
402 ASSERT(m_argumentValueProfiles.size() == static_cast<unsigned>(m_numParameters));
403 return m_argumentValueProfiles.size();
405 ValueProfile* valueProfileForArgument(unsigned argumentIndex)
407 ValueProfile* result = &m_argumentValueProfiles[argumentIndex];
408 ASSERT(result->m_bytecodeOffset == -1);
412 unsigned numberOfValueProfiles() { return m_valueProfiles.size(); }
413 ValueProfile* valueProfile(int index) { return &m_valueProfiles[index]; }
414 ValueProfile* valueProfileForBytecodeOffset(int bytecodeOffset);
415 SpeculatedType valueProfilePredictionForBytecodeOffset(const ConcurrentJSLocker& locker, int bytecodeOffset)
417 if (ValueProfile* valueProfile = valueProfileForBytecodeOffset(bytecodeOffset))
418 return valueProfile->computeUpdatedPrediction(locker);
422 unsigned totalNumberOfValueProfiles()
424 return numberOfArgumentValueProfiles() + numberOfValueProfiles();
426 ValueProfile* getFromAllValueProfiles(unsigned index)
428 if (index < numberOfArgumentValueProfiles())
429 return valueProfileForArgument(index);
430 return valueProfile(index - numberOfArgumentValueProfiles());
433 RareCaseProfile* addRareCaseProfile(int bytecodeOffset);
434 unsigned numberOfRareCaseProfiles() { return m_rareCaseProfiles.size(); }
435 RareCaseProfile* rareCaseProfileForBytecodeOffset(int bytecodeOffset);
436 unsigned rareCaseProfileCountForBytecodeOffset(int bytecodeOffset);
438 bool likelyToTakeSlowCase(int bytecodeOffset)
440 if (!hasBaselineJITProfiling())
442 unsigned value = rareCaseProfileCountForBytecodeOffset(bytecodeOffset);
443 return value >= Options::likelyToTakeSlowCaseMinimumCount();
446 bool couldTakeSlowCase(int bytecodeOffset)
448 if (!hasBaselineJITProfiling())
450 unsigned value = rareCaseProfileCountForBytecodeOffset(bytecodeOffset);
451 return value >= Options::couldTakeSlowCaseMinimumCount();
454 ArithProfile* arithProfileForBytecodeOffset(int bytecodeOffset);
455 ArithProfile* arithProfileForPC(Instruction*);
457 bool couldTakeSpecialFastCase(int bytecodeOffset);
459 unsigned numberOfArrayProfiles() const { return m_arrayProfiles.size(); }
460 const ArrayProfileVector& arrayProfiles() { return m_arrayProfiles; }
461 ArrayProfile* addArrayProfile(const ConcurrentJSLocker&, unsigned bytecodeOffset);
462 ArrayProfile* addArrayProfile(unsigned bytecodeOffset);
463 ArrayProfile* getArrayProfile(const ConcurrentJSLocker&, unsigned bytecodeOffset);
464 ArrayProfile* getArrayProfile(unsigned bytecodeOffset);
465 ArrayProfile* getOrAddArrayProfile(const ConcurrentJSLocker&, unsigned bytecodeOffset);
466 ArrayProfile* getOrAddArrayProfile(unsigned bytecodeOffset);
468 // Exception handling support
470 size_t numberOfExceptionHandlers() const { return m_rareData ? m_rareData->m_exceptionHandlers.size() : 0; }
471 HandlerInfo& exceptionHandler(int index) { RELEASE_ASSERT(m_rareData); return m_rareData->m_exceptionHandlers[index]; }
473 bool hasExpressionInfo() { return m_unlinkedCode->hasExpressionInfo(); }
476 Vector<CodeOrigin, 0, UnsafeVectorOverflow>& codeOrigins();
478 // Having code origins implies that there has been some inlining.
479 bool hasCodeOrigins()
481 return JITCode::isOptimizingJIT(jitType());
484 bool canGetCodeOrigin(CallSiteIndex index)
486 if (!hasCodeOrigins())
488 return index.bits() < codeOrigins().size();
491 CodeOrigin codeOrigin(CallSiteIndex index)
493 return codeOrigins()[index.bits()];
496 bool addFrequentExitSite(const DFG::FrequentExitSite& site)
498 ASSERT(JITCode::isBaselineCode(jitType()));
499 ConcurrentJSLocker locker(m_lock);
500 return m_exitProfile.add(locker, this, site);
503 bool hasExitSite(const ConcurrentJSLocker& locker, const DFG::FrequentExitSite& site) const
505 return m_exitProfile.hasExitSite(locker, site);
507 bool hasExitSite(const DFG::FrequentExitSite& site) const
509 ConcurrentJSLocker locker(m_lock);
510 return hasExitSite(locker, site);
513 DFG::ExitProfile& exitProfile() { return m_exitProfile; }
515 CompressedLazyOperandValueProfileHolder& lazyOperandValueProfiles()
517 return m_lazyOperandValueProfiles;
519 #endif // ENABLE(DFG_JIT)
523 size_t numberOfIdentifiers() const { return m_unlinkedCode->numberOfIdentifiers() + numberOfDFGIdentifiers(); }
524 size_t numberOfDFGIdentifiers() const;
525 const Identifier& identifier(int index) const;
527 size_t numberOfIdentifiers() const { return m_unlinkedCode->numberOfIdentifiers(); }
528 const Identifier& identifier(int index) const { return m_unlinkedCode->identifier(index); }
531 Vector<WriteBarrier<Unknown>>& constants() { return m_constantRegisters; }
532 Vector<SourceCodeRepresentation>& constantsSourceCodeRepresentation() { return m_constantsSourceCodeRepresentation; }
533 unsigned addConstant(JSValue v)
535 unsigned result = m_constantRegisters.size();
536 m_constantRegisters.append(WriteBarrier<Unknown>());
537 m_constantRegisters.last().set(m_globalObject->vm(), this, v);
538 m_constantsSourceCodeRepresentation.append(SourceCodeRepresentation::Other);
542 unsigned addConstantLazily()
544 unsigned result = m_constantRegisters.size();
545 m_constantRegisters.append(WriteBarrier<Unknown>());
546 m_constantsSourceCodeRepresentation.append(SourceCodeRepresentation::Other);
550 const Vector<WriteBarrier<Unknown>>& constantRegisters() { return m_constantRegisters; }
551 WriteBarrier<Unknown>& constantRegister(int index) { return m_constantRegisters[index - FirstConstantRegisterIndex]; }
552 static ALWAYS_INLINE bool isConstantRegisterIndex(int index) { return index >= FirstConstantRegisterIndex; }
553 ALWAYS_INLINE JSValue getConstant(int index) const { return m_constantRegisters[index - FirstConstantRegisterIndex].get(); }
554 ALWAYS_INLINE SourceCodeRepresentation constantSourceCodeRepresentation(int index) const { return m_constantsSourceCodeRepresentation[index - FirstConstantRegisterIndex]; }
556 FunctionExecutable* functionDecl(int index) { return m_functionDecls[index].get(); }
557 int numberOfFunctionDecls() { return m_functionDecls.size(); }
558 FunctionExecutable* functionExpr(int index) { return m_functionExprs[index].get(); }
560 RegExp* regexp(int index) const { return m_unlinkedCode->regexp(index); }
561 unsigned numberOfRegExps() const { return m_unlinkedCode->numberOfRegExps(); }
563 const Vector<BitVector>& bitVectors() const { return m_unlinkedCode->bitVectors(); }
564 const BitVector& bitVector(size_t i) { return m_unlinkedCode->bitVector(i); }
566 unsigned numberOfConstantBuffers() const
570 return m_rareData->m_constantBuffers.size();
572 unsigned addConstantBuffer(const Vector<JSValue>& buffer)
574 createRareDataIfNecessary();
575 unsigned size = m_rareData->m_constantBuffers.size();
576 m_rareData->m_constantBuffers.append(buffer);
580 Vector<JSValue>& constantBufferAsVector(unsigned index)
583 return m_rareData->m_constantBuffers[index];
585 JSValue* constantBuffer(unsigned index)
587 return constantBufferAsVector(index).data();
590 Heap* heap() const { return &m_vm->heap; }
591 JSGlobalObject* globalObject() { return m_globalObject.get(); }
593 JSGlobalObject* globalObjectFor(CodeOrigin);
595 BytecodeLivenessAnalysis& livenessAnalysis()
598 ConcurrentJSLocker locker(m_lock);
599 if (!!m_livenessAnalysis)
600 return *m_livenessAnalysis;
602 return livenessAnalysisSlow();
609 size_t numberOfSwitchJumpTables() const { return m_rareData ? m_rareData->m_switchJumpTables.size() : 0; }
610 SimpleJumpTable& addSwitchJumpTable() { createRareDataIfNecessary(); m_rareData->m_switchJumpTables.append(SimpleJumpTable()); return m_rareData->m_switchJumpTables.last(); }
611 SimpleJumpTable& switchJumpTable(int tableIndex) { RELEASE_ASSERT(m_rareData); return m_rareData->m_switchJumpTables[tableIndex]; }
612 void clearSwitchJumpTables()
616 m_rareData->m_switchJumpTables.clear();
619 size_t numberOfStringSwitchJumpTables() const { return m_rareData ? m_rareData->m_stringSwitchJumpTables.size() : 0; }
620 StringJumpTable& addStringSwitchJumpTable() { createRareDataIfNecessary(); m_rareData->m_stringSwitchJumpTables.append(StringJumpTable()); return m_rareData->m_stringSwitchJumpTables.last(); }
621 StringJumpTable& stringSwitchJumpTable(int tableIndex) { RELEASE_ASSERT(m_rareData); return m_rareData->m_stringSwitchJumpTables[tableIndex]; }
623 DirectEvalCodeCache& directEvalCodeCache() { createRareDataIfNecessary(); return m_rareData->m_directEvalCodeCache; }
626 // Shrink prior to generating machine code that may point directly into vectors.
629 // Shrink after generating machine code, and after possibly creating new vectors
630 // and appending to others. At this time it is not safe to shrink certain vectors
631 // because we would have generated machine code that references them directly.
634 void shrinkToFit(ShrinkMode);
636 // Functions for controlling when JITting kicks in, in a mixed mode
639 bool checkIfJITThresholdReached()
641 return m_llintExecuteCounter.checkIfThresholdCrossedAndSet(this);
644 void dontJITAnytimeSoon()
646 m_llintExecuteCounter.deferIndefinitely();
649 int32_t thresholdForJIT(int32_t threshold);
650 void jitAfterWarmUp();
653 const BaselineExecutionCounter& llintExecuteCounter() const
655 return m_llintExecuteCounter;
658 typedef HashMap<Structure*, Bag<LLIntPrototypeLoadAdaptiveStructureWatchpoint>> StructureWatchpointMap;
659 StructureWatchpointMap& llintGetByIdWatchpointMap() { return m_llintGetByIdWatchpointMap; }
661 // Functions for controlling when tiered compilation kicks in. This
662 // controls both when the optimizing compiler is invoked and when OSR
663 // entry happens. Two triggers exist: the loop trigger and the return
664 // trigger. In either case, when an addition to m_jitExecuteCounter
665 // causes it to become non-negative, the optimizing compiler is
666 // invoked. This includes a fast check to see if this CodeBlock has
667 // already been optimized (i.e. replacement() returns a CodeBlock
668 // that was optimized with a higher tier JIT than this one). In the
669 // case of the loop trigger, if the optimized compilation succeeds
670 // (or has already succeeded in the past) then OSR is attempted to
671 // redirect program flow into the optimized code.
673 // These functions are called from within the optimization triggers,
674 // and are used as a single point at which we define the heuristics
675 // for how much warm-up is mandated before the next optimization
676 // trigger files. All CodeBlocks start out with optimizeAfterWarmUp(),
677 // as this is called from the CodeBlock constructor.
679 // When we observe a lot of speculation failures, we trigger a
680 // reoptimization. But each time, we increase the optimization trigger
681 // to avoid thrashing.
682 JS_EXPORT_PRIVATE unsigned reoptimizationRetryCounter() const;
683 void countReoptimization();
685 static unsigned numberOfLLIntBaselineCalleeSaveRegisters() { return RegisterSet::llintBaselineCalleeSaveRegisters().numberOfSetRegisters(); }
686 static size_t llintBaselineCalleeSaveSpaceAsVirtualRegisters();
687 size_t calleeSaveSpaceAsVirtualRegisters();
689 unsigned numberOfDFGCompiles();
691 int32_t codeTypeThresholdMultiplier() const;
693 int32_t adjustedCounterValue(int32_t desiredThreshold);
695 int32_t* addressOfJITExecuteCounter()
697 return &m_jitExecuteCounter.m_counter;
700 static ptrdiff_t offsetOfJITExecuteCounter() { return OBJECT_OFFSETOF(CodeBlock, m_jitExecuteCounter) + OBJECT_OFFSETOF(BaselineExecutionCounter, m_counter); }
701 static ptrdiff_t offsetOfJITExecutionActiveThreshold() { return OBJECT_OFFSETOF(CodeBlock, m_jitExecuteCounter) + OBJECT_OFFSETOF(BaselineExecutionCounter, m_activeThreshold); }
702 static ptrdiff_t offsetOfJITExecutionTotalCount() { return OBJECT_OFFSETOF(CodeBlock, m_jitExecuteCounter) + OBJECT_OFFSETOF(BaselineExecutionCounter, m_totalCount); }
704 const BaselineExecutionCounter& jitExecuteCounter() const { return m_jitExecuteCounter; }
706 unsigned optimizationDelayCounter() const { return m_optimizationDelayCounter; }
708 // Check if the optimization threshold has been reached, and if not,
709 // adjust the heuristics accordingly. Returns true if the threshold has
711 bool checkIfOptimizationThresholdReached();
713 // Call this to force the next optimization trigger to fire. This is
714 // rarely wise, since optimization triggers are typically more
715 // expensive than executing baseline code.
716 void optimizeNextInvocation();
718 // Call this to prevent optimization from happening again. Note that
719 // optimization will still happen after roughly 2^29 invocations,
720 // so this is really meant to delay that as much as possible. This
721 // is called if optimization failed, and we expect it to fail in
722 // the future as well.
723 void dontOptimizeAnytimeSoon();
725 // Call this to reinitialize the counter to its starting state,
726 // forcing a warm-up to happen before the next optimization trigger
727 // fires. This is called in the CodeBlock constructor. It also
728 // makes sense to call this if an OSR exit occurred. Note that
729 // OSR exit code is code generated, so the value of the execute
730 // counter that this corresponds to is also available directly.
731 void optimizeAfterWarmUp();
733 // Call this to force an optimization trigger to fire only after
735 void optimizeAfterLongWarmUp();
737 // Call this to cause an optimization trigger to fire soon, but
738 // not necessarily the next one. This makes sense if optimization
739 // succeeds. Successfuly optimization means that all calls are
740 // relinked to the optimized code, so this only affects call
741 // frames that are still executing this CodeBlock. The value here
742 // is tuned to strike a balance between the cost of OSR entry
743 // (which is too high to warrant making every loop back edge to
744 // trigger OSR immediately) and the cost of executing baseline
745 // code (which is high enough that we don't necessarily want to
746 // have a full warm-up). The intuition for calling this instead of
747 // optimizeNextInvocation() is for the case of recursive functions
748 // with loops. Consider that there may be N call frames of some
749 // recursive function, for a reasonably large value of N. The top
750 // one triggers optimization, and then returns, and then all of
751 // the others return. We don't want optimization to be triggered on
752 // each return, as that would be superfluous. It only makes sense
753 // to trigger optimization if one of those functions becomes hot
754 // in the baseline code.
757 void forceOptimizationSlowPathConcurrently();
759 void setOptimizationThresholdBasedOnCompilationResult(CompilationResult);
761 uint32_t osrExitCounter() const { return m_osrExitCounter; }
763 void countOSRExit() { m_osrExitCounter++; }
765 uint32_t* addressOfOSRExitCounter() { return &m_osrExitCounter; }
767 static ptrdiff_t offsetOfOSRExitCounter() { return OBJECT_OFFSETOF(CodeBlock, m_osrExitCounter); }
769 uint32_t adjustedExitCountThreshold(uint32_t desiredThreshold);
770 uint32_t exitCountThresholdForReoptimization();
771 uint32_t exitCountThresholdForReoptimizationFromLoop();
772 bool shouldReoptimizeNow();
773 bool shouldReoptimizeFromLoopNow();
775 void setCalleeSaveRegisters(RegisterSet);
776 void setCalleeSaveRegisters(std::unique_ptr<RegisterAtOffsetList>);
778 RegisterAtOffsetList* calleeSaveRegisters() const { return m_calleeSaveRegisters.get(); }
780 static unsigned numberOfLLIntBaselineCalleeSaveRegisters() { return 0; }
781 static size_t llintBaselineCalleeSaveSpaceAsVirtualRegisters() { return 0; };
782 void optimizeAfterWarmUp() { }
783 unsigned numberOfDFGCompiles() { return 0; }
786 bool shouldOptimizeNow();
787 void updateAllValueProfilePredictions();
788 void updateAllArrayPredictions();
789 void updateAllPredictions();
791 unsigned frameRegisterCount();
792 int stackPointerOffset();
794 bool hasOpDebugForLineAndColumn(unsigned line, unsigned column);
796 bool hasDebuggerRequests() const { return m_debuggerRequests; }
797 void* debuggerRequestsAddress() { return &m_debuggerRequests; }
799 void addBreakpoint(unsigned numBreakpoints);
800 void removeBreakpoint(unsigned numBreakpoints)
802 ASSERT(m_numBreakpoints >= numBreakpoints);
803 m_numBreakpoints -= numBreakpoints;
807 SteppingModeDisabled,
810 void setSteppingMode(SteppingMode);
812 void clearDebuggerRequests()
814 m_steppingMode = SteppingModeDisabled;
815 m_numBreakpoints = 0;
818 bool wasCompiledWithDebuggingOpcodes() const { return m_unlinkedCode->wasCompiledWithDebuggingOpcodes(); }
820 // FIXME: Make these remaining members private.
822 int m_numCalleeLocals;
825 // This is intentionally public; it's the responsibility of anyone doing any
826 // of the following to hold the lock:
828 // - Modifying any inline cache in this code block.
830 // - Quering any inline cache in this code block, from a thread other than
833 // Additionally, it's only legal to modify the inline cache on the main
834 // thread. This means that the main thread can query the inline cache without
835 // locking. This is crucial since executing the inline cache is effectively
838 // Another exception to the rules is that the GC can do whatever it wants
839 // without holding any locks, because the GC is guaranteed to wait until any
840 // concurrent compilation threads finish what they're doing.
841 mutable ConcurrentJSLock m_lock;
843 bool m_visitWeaklyHasBeenCalled;
845 bool m_shouldAlwaysBeInlined; // Not a bitfield because the JIT wants to store to it.
848 unsigned m_capabilityLevelState : 2; // DFG::CapabilityLevel
851 bool m_allTransitionsHaveBeenMarked : 1; // Initialized and used on every GC.
853 bool m_didFailJITCompilation : 1;
854 bool m_didFailFTLCompilation : 1;
855 bool m_hasBeenCompiledWithFTL : 1;
856 bool m_isConstructor : 1;
857 bool m_isStrictMode : 1;
858 unsigned m_codeType : 2; // CodeType
860 // Internal methods for use by validation code. It would be private if it wasn't
861 // for the fact that we use it from anonymous namespaces.
862 void beginValidationDidFail();
863 NO_RETURN_DUE_TO_CRASH void endValidationDidFail();
866 WTF_MAKE_FAST_ALLOCATED;
868 Vector<HandlerInfo> m_exceptionHandlers;
870 // Buffers used for large array literals
871 Vector<Vector<JSValue>> m_constantBuffers;
874 Vector<SimpleJumpTable> m_switchJumpTables;
875 Vector<StringJumpTable> m_stringSwitchJumpTables;
877 DirectEvalCodeCache m_directEvalCodeCache;
880 void clearExceptionHandlers()
883 m_rareData->m_exceptionHandlers.clear();
886 void appendExceptionHandler(const HandlerInfo& handler)
888 createRareDataIfNecessary(); // We may be handling the exception of an inlined call frame.
889 m_rareData->m_exceptionHandlers.append(handler);
892 CallSiteIndex newExceptionHandlingCallSiteIndex(CallSiteIndex originalCallSite);
895 void setPCToCodeOriginMap(std::unique_ptr<PCToCodeOriginMap>&&);
896 std::optional<CodeOrigin> findPC(void* pc);
900 void finalizeLLIntInlineCaches();
901 void finalizeBaselineJITInlineCaches();
904 void tallyFrequentExitSites();
906 void tallyFrequentExitSites() { }
910 friend class CodeBlockSet;
912 BytecodeLivenessAnalysis& livenessAnalysisSlow();
914 CodeBlock* specialOSREntryBlockOrNull();
916 void noticeIncomingCall(ExecState* callerFrame);
918 double optimizationThresholdScalingFactor();
920 void updateAllPredictionsAndCountLiveness(unsigned& numberOfLiveNonArgumentValueProfiles, unsigned& numberOfSamplesInProfiles);
922 bool setConstantIdentifierSetRegisters(VM&, const Vector<ConstantIndentifierSetEntry>& constants);
924 void setConstantRegisters(const Vector<WriteBarrier<Unknown>>& constants, const Vector<SourceCodeRepresentation>& constantsSourceCodeRepresentation);
926 void replaceConstant(int index, JSValue value)
928 ASSERT(isConstantRegisterIndex(index) && static_cast<size_t>(index - FirstConstantRegisterIndex) < m_constantRegisters.size());
929 m_constantRegisters[index - FirstConstantRegisterIndex].set(m_globalObject->vm(), this, value);
932 bool shouldVisitStrongly(const ConcurrentJSLocker&);
933 bool shouldJettisonDueToWeakReference();
934 bool shouldJettisonDueToOldAge(const ConcurrentJSLocker&);
936 void propagateTransitions(const ConcurrentJSLocker&, SlotVisitor&);
937 void determineLiveness(const ConcurrentJSLocker&, SlotVisitor&);
939 void stronglyVisitStrongReferences(const ConcurrentJSLocker&, SlotVisitor&);
940 void stronglyVisitWeakReferences(const ConcurrentJSLocker&, SlotVisitor&);
941 void visitOSRExitTargets(const ConcurrentJSLocker&, SlotVisitor&);
943 std::chrono::milliseconds timeSinceCreation()
945 return std::chrono::duration_cast<std::chrono::milliseconds>(
946 std::chrono::steady_clock::now() - m_creationTime);
949 void createRareDataIfNecessary()
952 m_rareData = std::make_unique<RareData>();
955 void insertBasicBlockBoundariesForControlFlowProfiler(RefCountedArray<Instruction>&);
957 WriteBarrier<UnlinkedCodeBlock> m_unlinkedCode;
959 int m_numberOfArgumentsToSkip { 0 };
961 unsigned m_debuggerRequests;
963 unsigned m_hasDebuggerStatement : 1;
964 unsigned m_steppingMode : 1;
965 unsigned m_numBreakpoints : 30;
968 WriteBarrier<ExecutableBase> m_ownerExecutable;
971 RefCountedArray<Instruction> m_instructions;
972 VirtualRegister m_thisRegister;
973 VirtualRegister m_scopeRegister;
974 mutable CodeBlockHash m_hash;
976 RefPtr<SourceProvider> m_source;
977 unsigned m_sourceOffset;
978 unsigned m_firstLineColumnOffset;
980 RefCountedArray<LLIntCallLinkInfo> m_llintCallLinkInfos;
981 SentinelLinkedList<LLIntCallLinkInfo, BasicRawSentinelNode<LLIntCallLinkInfo>> m_incomingLLIntCalls;
982 StructureWatchpointMap m_llintGetByIdWatchpointMap;
983 RefPtr<JITCode> m_jitCode;
985 std::unique_ptr<RegisterAtOffsetList> m_calleeSaveRegisters;
986 Bag<StructureStubInfo> m_stubInfos;
987 Bag<JITAddIC> m_addICs;
988 Bag<JITMulIC> m_mulICs;
989 Bag<JITNegIC> m_negICs;
990 Bag<JITSubIC> m_subICs;
991 Bag<ByValInfo> m_byValInfos;
992 Bag<CallLinkInfo> m_callLinkInfos;
993 SentinelLinkedList<CallLinkInfo, BasicRawSentinelNode<CallLinkInfo>> m_incomingCalls;
994 SentinelLinkedList<PolymorphicCallNode, BasicRawSentinelNode<PolymorphicCallNode>> m_incomingPolymorphicCalls;
995 std::unique_ptr<PCToCodeOriginMap> m_pcToCodeOriginMap;
997 std::unique_ptr<CompactJITCodeMap> m_jitCodeMap;
999 // This is relevant to non-DFG code blocks that serve as the profiled code block
1000 // for DFG code blocks.
1001 DFG::ExitProfile m_exitProfile;
1002 CompressedLazyOperandValueProfileHolder m_lazyOperandValueProfiles;
1004 RefCountedArray<ValueProfile> m_argumentValueProfiles;
1005 RefCountedArray<ValueProfile> m_valueProfiles;
1006 SegmentedVector<RareCaseProfile, 8> m_rareCaseProfiles;
1007 RefCountedArray<ArrayAllocationProfile> m_arrayAllocationProfiles;
1008 ArrayProfileVector m_arrayProfiles;
1009 RefCountedArray<ObjectAllocationProfile> m_objectAllocationProfiles;
1012 COMPILE_ASSERT(sizeof(Register) == sizeof(WriteBarrier<Unknown>), Register_must_be_same_size_as_WriteBarrier_Unknown);
1013 // TODO: This could just be a pointer to m_unlinkedCodeBlock's data, but the DFG mutates
1014 // it, so we're stuck with it for now.
1015 Vector<WriteBarrier<Unknown>> m_constantRegisters;
1016 Vector<SourceCodeRepresentation> m_constantsSourceCodeRepresentation;
1017 RefCountedArray<WriteBarrier<FunctionExecutable>> m_functionDecls;
1018 RefCountedArray<WriteBarrier<FunctionExecutable>> m_functionExprs;
1020 WriteBarrier<CodeBlock> m_alternative;
1022 BaselineExecutionCounter m_llintExecuteCounter;
1024 BaselineExecutionCounter m_jitExecuteCounter;
1025 uint32_t m_osrExitCounter;
1026 uint16_t m_optimizationDelayCounter;
1027 uint16_t m_reoptimizationRetryCounter;
1029 std::chrono::steady_clock::time_point m_creationTime;
1031 std::unique_ptr<BytecodeLivenessAnalysis> m_livenessAnalysis;
1033 std::unique_ptr<RareData> m_rareData;
1035 UnconditionalFinalizer m_unconditionalFinalizer;
1036 WeakReferenceHarvester m_weakReferenceHarvester;
1039 inline Register& ExecState::r(int index)
1041 CodeBlock* codeBlock = this->codeBlock();
1042 if (codeBlock->isConstantRegisterIndex(index))
1043 return *reinterpret_cast<Register*>(&codeBlock->constantRegister(index));
1047 inline Register& ExecState::r(VirtualRegister reg)
1049 return r(reg.offset());
1052 inline Register& ExecState::uncheckedR(int index)
1054 RELEASE_ASSERT(index < FirstConstantRegisterIndex);
1058 inline Register& ExecState::uncheckedR(VirtualRegister reg)
1060 return uncheckedR(reg.offset());
1063 inline void CodeBlock::clearVisitWeaklyHasBeenCalled()
1065 m_visitWeaklyHasBeenCalled = false;
1068 template <typename ExecutableType>
1069 JSObject* ScriptExecutable::prepareForExecution(VM& vm, JSFunction* function, JSScope* scope, CodeSpecializationKind kind, CodeBlock*& resultCodeBlock)
1071 if (hasJITCodeFor(kind)) {
1072 if (std::is_same<ExecutableType, EvalExecutable>::value)
1073 resultCodeBlock = jsCast<CodeBlock*>(jsCast<EvalExecutable*>(this)->codeBlock());
1074 else if (std::is_same<ExecutableType, ProgramExecutable>::value)
1075 resultCodeBlock = jsCast<CodeBlock*>(jsCast<ProgramExecutable*>(this)->codeBlock());
1076 else if (std::is_same<ExecutableType, ModuleProgramExecutable>::value)
1077 resultCodeBlock = jsCast<CodeBlock*>(jsCast<ModuleProgramExecutable*>(this)->codeBlock());
1078 else if (std::is_same<ExecutableType, FunctionExecutable>::value)
1079 resultCodeBlock = jsCast<CodeBlock*>(jsCast<FunctionExecutable*>(this)->codeBlockFor(kind));
1081 RELEASE_ASSERT_NOT_REACHED();
1084 return prepareForExecutionImpl(vm, function, scope, kind, resultCodeBlock);
1087 #define CODEBLOCK_LOG_EVENT(codeBlock, summary, details) \
1088 (codeBlock->vm()->logEvent(codeBlock, summary, [&] () { return toCString details; }))