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 "CodeBlockHash.h"
37 #include "CodeOrigin.h"
39 #include "CompactJITCodeMap.h"
40 #include "CompilationResult.h"
41 #include "ConcurrentJSLock.h"
42 #include "DFGCommon.h"
43 #include "DFGExitProfile.h"
44 #include "DirectEvalCodeCache.h"
45 #include "EvalExecutable.h"
46 #include "ExecutionCounter.h"
47 #include "ExpressionRangeInfo.h"
48 #include "FunctionExecutable.h"
49 #include "HandlerInfo.h"
50 #include "Instruction.h"
52 #include "JITMathICForwards.h"
54 #include "JSGlobalObject.h"
55 #include "JumpTable.h"
56 #include "LLIntCallLinkInfo.h"
57 #include "LLIntPrototypeLoadAdaptiveStructureWatchpoint.h"
58 #include "LazyOperandValueProfile.h"
59 #include "ModuleProgramExecutable.h"
60 #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/FastMalloc.h>
72 #include <wtf/RefCountedArray.h>
73 #include <wtf/RefPtr.h>
74 #include <wtf/SegmentedVector.h>
75 #include <wtf/Vector.h>
76 #include <wtf/text/WTFString.h>
86 class BytecodeLivenessAnalysis;
89 class JSModuleEnvironment;
90 class LLIntOffsetsExtractor;
91 class PCToCodeOriginMap;
92 class RegisterAtOffsetList;
93 class StructureStubInfo;
95 enum class AccessType : int8_t;
99 typedef HashMap<CodeOrigin, StructureStubInfo*, CodeOriginApproximateHash> StubInfoMap;
101 enum ReoptimizationMode { DontCountReoptimization, CountReoptimization };
103 class CodeBlock : public JSCell {
105 friend class BytecodeLivenessAnalysis;
107 friend class LLIntOffsetsExtractor;
109 class UnconditionalFinalizer : public JSC::UnconditionalFinalizer {
110 void finalizeUnconditionally() override;
113 class WeakReferenceHarvester : public JSC::WeakReferenceHarvester {
114 void visitWeakReferences(SlotVisitor&) override;
118 enum CopyParsedBlockTag { CopyParsedBlock };
120 static const unsigned StructureFlags = Base::StructureFlags | StructureIsImmortal;
125 CodeBlock(VM*, Structure*, CopyParsedBlockTag, CodeBlock& other);
126 CodeBlock(VM*, Structure*, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock*, JSScope*, RefPtr<SourceProvider>&&, unsigned sourceOffset, unsigned firstLineColumnOffset);
128 void finishCreation(VM&, CopyParsedBlockTag, CodeBlock& other);
129 bool finishCreation(VM&, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock*, JSScope*);
131 WriteBarrier<JSGlobalObject> m_globalObject;
134 JS_EXPORT_PRIVATE ~CodeBlock();
136 UnlinkedCodeBlock* unlinkedCodeBlock() const { return m_unlinkedCode.get(); }
138 CString inferredName() const;
139 CodeBlockHash hash() const;
140 bool hasHash() const;
141 bool isSafeToComputeHash() const;
142 CString hashAsStringIfPossible() const;
143 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.
144 CString sourceCodeOnOneLine() const; // As sourceCodeForTools(), but replaces all whitespace runs with a single space.
145 void dumpAssumingJITType(PrintStream&, JITCode::JITType) const;
146 JS_EXPORT_PRIVATE void dump(PrintStream&) const;
148 int numParameters() const { return m_numParameters; }
149 void setNumParameters(int newValue);
151 int numberOfArgumentsToSkip() const { return m_numberOfArgumentsToSkip; }
153 int numCalleeLocals() const { return m_numCalleeLocals; }
155 int* addressOfNumParameters() { return &m_numParameters; }
156 static ptrdiff_t offsetOfNumParameters() { return OBJECT_OFFSETOF(CodeBlock, m_numParameters); }
158 CodeBlock* alternative() const { return static_cast<CodeBlock*>(m_alternative.get()); }
159 void setAlternative(VM&, CodeBlock*);
161 template <typename Functor> void forEachRelatedCodeBlock(Functor&& functor)
163 Functor f(std::forward<Functor>(functor));
164 Vector<CodeBlock*, 4> codeBlocks;
165 codeBlocks.append(this);
167 while (!codeBlocks.isEmpty()) {
168 CodeBlock* currentCodeBlock = codeBlocks.takeLast();
171 if (CodeBlock* alternative = currentCodeBlock->alternative())
172 codeBlocks.append(alternative);
173 if (CodeBlock* osrEntryBlock = currentCodeBlock->specialOSREntryBlockOrNull())
174 codeBlocks.append(osrEntryBlock);
178 CodeSpecializationKind specializationKind() const
180 return specializationFromIsConstruct(m_isConstructor);
183 CodeBlock* alternativeForJettison();
184 JS_EXPORT_PRIVATE CodeBlock* baselineAlternative();
186 // FIXME: Get rid of this.
187 // https://bugs.webkit.org/show_bug.cgi?id=123677
188 CodeBlock* baselineVersion();
190 static size_t estimatedSize(JSCell*);
191 static void visitChildren(JSCell*, SlotVisitor&);
192 void visitChildren(SlotVisitor&);
193 void visitWeakly(SlotVisitor&);
194 void clearVisitWeaklyHasBeenCalled();
197 void dumpSource(PrintStream&);
200 void dumpBytecode(PrintStream&);
201 void dumpBytecode(PrintStream& out, const Instruction* begin, const Instruction*& it, const StubInfoMap& = StubInfoMap(), const CallLinkInfoMap& = CallLinkInfoMap());
202 void dumpBytecode(PrintStream& out, unsigned bytecodeOffset, const StubInfoMap& = StubInfoMap(), const CallLinkInfoMap& = CallLinkInfoMap());
204 void dumpExceptionHandlers(PrintStream&);
205 void printStructures(PrintStream&, const Instruction*);
206 void printStructure(PrintStream&, const char* name, const Instruction*, int operand);
208 void dumpMathICStats();
210 bool isStrictMode() const { return m_isStrictMode; }
211 ECMAMode ecmaMode() const { return isStrictMode() ? StrictMode : NotStrictMode; }
213 bool hasInstalledVMTrapBreakpoints() const;
214 bool installVMTrapBreakpoints();
216 inline bool isKnownNotImmediate(int index)
218 if (index == m_thisRegister.offset() && !m_isStrictMode)
221 if (isConstantRegisterIndex(index))
222 return getConstant(index).isCell();
227 ALWAYS_INLINE bool isTemporaryRegisterIndex(int index)
229 return index >= m_numVars;
232 HandlerInfo* handlerForBytecodeOffset(unsigned bytecodeOffset, RequiredHandler = RequiredHandler::AnyHandler);
233 HandlerInfo* handlerForIndex(unsigned, RequiredHandler = RequiredHandler::AnyHandler);
234 void removeExceptionHandlerForCallSite(CallSiteIndex);
235 unsigned lineNumberForBytecodeOffset(unsigned bytecodeOffset);
236 unsigned columnNumberForBytecodeOffset(unsigned bytecodeOffset);
237 void expressionRangeForBytecodeOffset(unsigned bytecodeOffset, int& divot,
238 int& startOffset, int& endOffset, unsigned& line, unsigned& column) const;
240 std::optional<unsigned> bytecodeOffsetFromCallSiteIndex(CallSiteIndex);
242 void getStubInfoMap(const ConcurrentJSLocker&, StubInfoMap& result);
243 void getStubInfoMap(StubInfoMap& result);
245 void getCallLinkInfoMap(const ConcurrentJSLocker&, CallLinkInfoMap& result);
246 void getCallLinkInfoMap(CallLinkInfoMap& result);
248 void getByValInfoMap(const ConcurrentJSLocker&, ByValInfoMap& result);
249 void getByValInfoMap(ByValInfoMap& result);
252 StructureStubInfo* addStubInfo(AccessType);
253 JITAddIC* addJITAddIC(ArithProfile*);
254 JITMulIC* addJITMulIC(ArithProfile*);
255 JITNegIC* addJITNegIC(ArithProfile*);
256 JITSubIC* addJITSubIC(ArithProfile*);
257 Bag<StructureStubInfo>::iterator stubInfoBegin() { return m_stubInfos.begin(); }
258 Bag<StructureStubInfo>::iterator stubInfoEnd() { return m_stubInfos.end(); }
260 // O(n) operation. Use getStubInfoMap() unless you really only intend to get one
262 StructureStubInfo* findStubInfo(CodeOrigin);
264 ByValInfo* addByValInfo();
266 CallLinkInfo* addCallLinkInfo();
267 Bag<CallLinkInfo>::iterator callLinkInfosBegin() { return m_callLinkInfos.begin(); }
268 Bag<CallLinkInfo>::iterator callLinkInfosEnd() { return m_callLinkInfos.end(); }
270 // This is a slow function call used primarily for compiling OSR exits in the case
271 // that there had been inlining. Chances are if you want to use this, you're really
272 // looking for a CallLinkInfoMap to amortize the cost of calling this.
273 CallLinkInfo* getCallLinkInfoForBytecodeIndex(unsigned bytecodeIndex);
275 // We call this when we want to reattempt compiling something with the baseline JIT. Ideally
276 // the baseline JIT would not add data to CodeBlock, but instead it would put its data into
277 // a newly created JITCode, which could be thrown away if we bail on JIT compilation. Then we
278 // would be able to get rid of this silly function.
279 // FIXME: https://bugs.webkit.org/show_bug.cgi?id=159061
281 #endif // ENABLE(JIT)
283 void unlinkIncomingCalls();
286 void linkIncomingCall(ExecState* callerFrame, CallLinkInfo*);
287 void linkIncomingPolymorphicCall(ExecState* callerFrame, PolymorphicCallNode*);
288 #endif // ENABLE(JIT)
290 void linkIncomingCall(ExecState* callerFrame, LLIntCallLinkInfo*);
292 void setJITCodeMap(std::unique_ptr<CompactJITCodeMap> jitCodeMap)
294 m_jitCodeMap = WTFMove(jitCodeMap);
296 CompactJITCodeMap* jitCodeMap()
298 return m_jitCodeMap.get();
301 static void clearLLIntGetByIdCache(Instruction*);
303 unsigned bytecodeOffset(Instruction* returnAddress)
305 RELEASE_ASSERT(returnAddress >= instructions().begin() && returnAddress < instructions().end());
306 return static_cast<Instruction*>(returnAddress) - instructions().begin();
309 typedef JSC::Instruction Instruction;
310 typedef RefCountedArray<Instruction>& UnpackedInstructions;
312 unsigned numberOfInstructions() const { return m_instructions.size(); }
313 RefCountedArray<Instruction>& instructions() { return m_instructions; }
314 const RefCountedArray<Instruction>& instructions() const { return m_instructions; }
316 size_t predictedMachineCodeSize();
318 bool usesOpcode(OpcodeID);
320 unsigned instructionCount() const { return m_instructions.size(); }
322 // Exactly equivalent to codeBlock->ownerExecutable()->newReplacementCodeBlockFor(codeBlock->specializationKind())
323 CodeBlock* newReplacement();
325 void setJITCode(Ref<JITCode>&& code)
327 ASSERT(heap()->isDeferred());
328 heap()->reportExtraMemoryAllocated(code->size());
329 ConcurrentJSLocker locker(m_lock);
330 WTF::storeStoreFence(); // This is probably not needed because the lock will also do something similar, but it's good to be paranoid.
331 m_jitCode = WTFMove(code);
333 RefPtr<JITCode> jitCode() { return m_jitCode; }
334 static ptrdiff_t jitCodeOffset() { return OBJECT_OFFSETOF(CodeBlock, m_jitCode); }
335 JITCode::JITType jitType() const
337 JITCode* jitCode = m_jitCode.get();
338 WTF::loadLoadFence();
339 JITCode::JITType result = JITCode::jitTypeFor(jitCode);
340 WTF::loadLoadFence(); // This probably isn't needed. Oh well, paranoia is good.
344 bool hasBaselineJITProfiling() const
346 return jitType() == JITCode::BaselineJIT;
350 CodeBlock* replacement();
352 DFG::CapabilityLevel computeCapabilityLevel();
353 DFG::CapabilityLevel capabilityLevel();
354 DFG::CapabilityLevel capabilityLevelState() { return static_cast<DFG::CapabilityLevel>(m_capabilityLevelState); }
356 bool hasOptimizedReplacement(JITCode::JITType typeToReplace);
357 bool hasOptimizedReplacement(); // the typeToReplace is my JITType
360 void jettison(Profiler::JettisonReason, ReoptimizationMode = DontCountReoptimization, const FireDetail* = nullptr);
362 ExecutableBase* ownerExecutable() const { return m_ownerExecutable.get(); }
363 ScriptExecutable* ownerScriptExecutable() const { return jsCast<ScriptExecutable*>(m_ownerExecutable.get()); }
365 VM* vm() const { return m_vm; }
367 void setThisRegister(VirtualRegister thisRegister) { m_thisRegister = thisRegister; }
368 VirtualRegister thisRegister() const { return m_thisRegister; }
370 bool usesEval() const { return m_unlinkedCode->usesEval(); }
372 void setScopeRegister(VirtualRegister scopeRegister)
374 ASSERT(scopeRegister.isLocal() || !scopeRegister.isValid());
375 m_scopeRegister = scopeRegister;
378 VirtualRegister scopeRegister() const
380 return m_scopeRegister;
383 CodeType codeType() const
385 return static_cast<CodeType>(m_codeType);
388 PutPropertySlot::Context putByIdContext() const
390 if (codeType() == EvalCode)
391 return PutPropertySlot::PutByIdEval;
392 return PutPropertySlot::PutById;
395 SourceProvider* source() const { return m_source.get(); }
396 unsigned sourceOffset() const { return m_sourceOffset; }
397 unsigned firstLineColumnOffset() const { return m_firstLineColumnOffset; }
399 size_t numberOfJumpTargets() const { return m_unlinkedCode->numberOfJumpTargets(); }
400 unsigned jumpTarget(int index) const { return m_unlinkedCode->jumpTarget(index); }
402 String nameForRegister(VirtualRegister);
404 unsigned numberOfArgumentValueProfiles()
406 ASSERT(m_numParameters >= 0);
407 ASSERT(m_argumentValueProfiles.size() == static_cast<unsigned>(m_numParameters));
408 return m_argumentValueProfiles.size();
410 ValueProfile& valueProfileForArgument(unsigned argumentIndex)
412 ValueProfile& result = m_argumentValueProfiles[argumentIndex];
413 ASSERT(result.m_bytecodeOffset == -1);
417 unsigned numberOfValueProfiles() { return m_valueProfiles.size(); }
418 ValueProfile& valueProfile(int index) { return m_valueProfiles[index]; }
419 ValueProfile& valueProfileForBytecodeOffset(int bytecodeOffset);
420 ValueProfile* tryGetValueProfileForBytecodeOffset(int bytecodeOffset);
421 SpeculatedType valueProfilePredictionForBytecodeOffset(const ConcurrentJSLocker& locker, int bytecodeOffset)
423 if (ValueProfile* valueProfile = tryGetValueProfileForBytecodeOffset(bytecodeOffset))
424 return valueProfile->computeUpdatedPrediction(locker);
428 unsigned totalNumberOfValueProfiles()
430 return numberOfArgumentValueProfiles() + numberOfValueProfiles();
432 ValueProfile& getFromAllValueProfiles(unsigned index)
434 if (index < numberOfArgumentValueProfiles())
435 return valueProfileForArgument(index);
436 return valueProfile(index - numberOfArgumentValueProfiles());
439 RareCaseProfile* addRareCaseProfile(int bytecodeOffset);
440 unsigned numberOfRareCaseProfiles() { return m_rareCaseProfiles.size(); }
441 RareCaseProfile* rareCaseProfileForBytecodeOffset(int bytecodeOffset);
442 unsigned rareCaseProfileCountForBytecodeOffset(int bytecodeOffset);
444 bool likelyToTakeSlowCase(int bytecodeOffset)
446 if (!hasBaselineJITProfiling())
448 unsigned value = rareCaseProfileCountForBytecodeOffset(bytecodeOffset);
449 return value >= Options::likelyToTakeSlowCaseMinimumCount();
452 bool couldTakeSlowCase(int bytecodeOffset)
454 if (!hasBaselineJITProfiling())
456 unsigned value = rareCaseProfileCountForBytecodeOffset(bytecodeOffset);
457 return value >= Options::couldTakeSlowCaseMinimumCount();
460 ArithProfile* arithProfileForBytecodeOffset(int bytecodeOffset);
461 ArithProfile* arithProfileForPC(Instruction*);
463 bool couldTakeSpecialFastCase(int bytecodeOffset);
465 unsigned numberOfArrayProfiles() const { return m_arrayProfiles.size(); }
466 const ArrayProfileVector& arrayProfiles() { return m_arrayProfiles; }
467 ArrayProfile* addArrayProfile(const ConcurrentJSLocker&, unsigned bytecodeOffset);
468 ArrayProfile* addArrayProfile(unsigned bytecodeOffset);
469 ArrayProfile* getArrayProfile(const ConcurrentJSLocker&, unsigned bytecodeOffset);
470 ArrayProfile* getArrayProfile(unsigned bytecodeOffset);
471 ArrayProfile* getOrAddArrayProfile(const ConcurrentJSLocker&, unsigned bytecodeOffset);
472 ArrayProfile* getOrAddArrayProfile(unsigned bytecodeOffset);
474 // Exception handling support
476 size_t numberOfExceptionHandlers() const { return m_rareData ? m_rareData->m_exceptionHandlers.size() : 0; }
477 HandlerInfo& exceptionHandler(int index) { RELEASE_ASSERT(m_rareData); return m_rareData->m_exceptionHandlers[index]; }
479 bool hasExpressionInfo() { return m_unlinkedCode->hasExpressionInfo(); }
482 Vector<CodeOrigin, 0, UnsafeVectorOverflow>& codeOrigins();
484 // Having code origins implies that there has been some inlining.
485 bool hasCodeOrigins()
487 return JITCode::isOptimizingJIT(jitType());
490 bool canGetCodeOrigin(CallSiteIndex index)
492 if (!hasCodeOrigins())
494 return index.bits() < codeOrigins().size();
497 CodeOrigin codeOrigin(CallSiteIndex index)
499 return codeOrigins()[index.bits()];
502 bool addFrequentExitSite(const DFG::FrequentExitSite& site)
504 ASSERT(JITCode::isBaselineCode(jitType()));
505 ConcurrentJSLocker locker(m_lock);
506 return m_exitProfile.add(locker, this, site);
509 bool hasExitSite(const ConcurrentJSLocker& locker, const DFG::FrequentExitSite& site) const
511 return m_exitProfile.hasExitSite(locker, site);
513 bool hasExitSite(const DFG::FrequentExitSite& site) const
515 ConcurrentJSLocker locker(m_lock);
516 return hasExitSite(locker, site);
519 DFG::ExitProfile& exitProfile() { return m_exitProfile; }
521 CompressedLazyOperandValueProfileHolder& lazyOperandValueProfiles()
523 return m_lazyOperandValueProfiles;
525 #endif // ENABLE(DFG_JIT)
529 size_t numberOfIdentifiers() const { return m_unlinkedCode->numberOfIdentifiers() + numberOfDFGIdentifiers(); }
530 size_t numberOfDFGIdentifiers() const;
531 const Identifier& identifier(int index) const;
533 size_t numberOfIdentifiers() const { return m_unlinkedCode->numberOfIdentifiers(); }
534 const Identifier& identifier(int index) const { return m_unlinkedCode->identifier(index); }
537 Vector<WriteBarrier<Unknown>>& constants() { return m_constantRegisters; }
538 Vector<SourceCodeRepresentation>& constantsSourceCodeRepresentation() { return m_constantsSourceCodeRepresentation; }
539 unsigned addConstant(JSValue v)
541 unsigned result = m_constantRegisters.size();
542 m_constantRegisters.append(WriteBarrier<Unknown>());
543 m_constantRegisters.last().set(*m_vm, this, v);
544 m_constantsSourceCodeRepresentation.append(SourceCodeRepresentation::Other);
548 unsigned addConstantLazily()
550 unsigned result = m_constantRegisters.size();
551 m_constantRegisters.append(WriteBarrier<Unknown>());
552 m_constantsSourceCodeRepresentation.append(SourceCodeRepresentation::Other);
556 const Vector<WriteBarrier<Unknown>>& constantRegisters() { return m_constantRegisters; }
557 WriteBarrier<Unknown>& constantRegister(int index) { return m_constantRegisters[index - FirstConstantRegisterIndex]; }
558 static ALWAYS_INLINE bool isConstantRegisterIndex(int index) { return index >= FirstConstantRegisterIndex; }
559 ALWAYS_INLINE JSValue getConstant(int index) const { return m_constantRegisters[index - FirstConstantRegisterIndex].get(); }
560 ALWAYS_INLINE SourceCodeRepresentation constantSourceCodeRepresentation(int index) const { return m_constantsSourceCodeRepresentation[index - FirstConstantRegisterIndex]; }
562 FunctionExecutable* functionDecl(int index) { return m_functionDecls[index].get(); }
563 int numberOfFunctionDecls() { return m_functionDecls.size(); }
564 FunctionExecutable* functionExpr(int index) { return m_functionExprs[index].get(); }
566 RegExp* regexp(int index) const { return m_unlinkedCode->regexp(index); }
567 unsigned numberOfRegExps() const { return m_unlinkedCode->numberOfRegExps(); }
569 const Vector<BitVector>& bitVectors() const { return m_unlinkedCode->bitVectors(); }
570 const BitVector& bitVector(size_t i) { return m_unlinkedCode->bitVector(i); }
572 unsigned numberOfConstantBuffers() const
576 return m_rareData->m_constantBuffers.size();
578 unsigned addConstantBuffer(const Vector<JSValue>& buffer)
580 createRareDataIfNecessary();
581 unsigned size = m_rareData->m_constantBuffers.size();
582 m_rareData->m_constantBuffers.append(buffer);
586 Vector<JSValue>& constantBufferAsVector(unsigned index)
589 return m_rareData->m_constantBuffers[index];
591 JSValue* constantBuffer(unsigned index)
593 return constantBufferAsVector(index).data();
596 Heap* heap() const { return &m_vm->heap; }
597 JSGlobalObject* globalObject() { return m_globalObject.get(); }
599 JSGlobalObject* globalObjectFor(CodeOrigin);
601 BytecodeLivenessAnalysis& livenessAnalysis()
604 ConcurrentJSLocker locker(m_lock);
605 if (!!m_livenessAnalysis)
606 return *m_livenessAnalysis;
608 return livenessAnalysisSlow();
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 DirectEvalCodeCache& directEvalCodeCache() { createRareDataIfNecessary(); return m_rareData->m_directEvalCodeCache; }
632 // Shrink prior to generating machine code that may point directly into vectors.
635 // Shrink after generating machine code, and after possibly creating new vectors
636 // and appending to others. At this time it is not safe to shrink certain vectors
637 // because we would have generated machine code that references them directly.
640 void shrinkToFit(ShrinkMode);
642 // Functions for controlling when JITting kicks in, in a mixed mode
645 bool checkIfJITThresholdReached()
647 return m_llintExecuteCounter.checkIfThresholdCrossedAndSet(this);
650 void dontJITAnytimeSoon()
652 m_llintExecuteCounter.deferIndefinitely();
655 int32_t thresholdForJIT(int32_t threshold);
656 void jitAfterWarmUp();
659 const BaselineExecutionCounter& llintExecuteCounter() const
661 return m_llintExecuteCounter;
664 typedef HashMap<Structure*, Bag<LLIntPrototypeLoadAdaptiveStructureWatchpoint>> StructureWatchpointMap;
665 StructureWatchpointMap& llintGetByIdWatchpointMap() { return m_llintGetByIdWatchpointMap; }
667 // Functions for controlling when tiered compilation kicks in. This
668 // controls both when the optimizing compiler is invoked and when OSR
669 // entry happens. Two triggers exist: the loop trigger and the return
670 // trigger. In either case, when an addition to m_jitExecuteCounter
671 // causes it to become non-negative, the optimizing compiler is
672 // invoked. This includes a fast check to see if this CodeBlock has
673 // already been optimized (i.e. replacement() returns a CodeBlock
674 // that was optimized with a higher tier JIT than this one). In the
675 // case of the loop trigger, if the optimized compilation succeeds
676 // (or has already succeeded in the past) then OSR is attempted to
677 // redirect program flow into the optimized code.
679 // These functions are called from within the optimization triggers,
680 // and are used as a single point at which we define the heuristics
681 // for how much warm-up is mandated before the next optimization
682 // trigger files. All CodeBlocks start out with optimizeAfterWarmUp(),
683 // as this is called from the CodeBlock constructor.
685 // When we observe a lot of speculation failures, we trigger a
686 // reoptimization. But each time, we increase the optimization trigger
687 // to avoid thrashing.
688 JS_EXPORT_PRIVATE unsigned reoptimizationRetryCounter() const;
689 void countReoptimization();
691 static unsigned numberOfLLIntBaselineCalleeSaveRegisters() { return RegisterSet::llintBaselineCalleeSaveRegisters().numberOfSetRegisters(); }
692 static size_t llintBaselineCalleeSaveSpaceAsVirtualRegisters();
693 size_t calleeSaveSpaceAsVirtualRegisters();
695 unsigned numberOfDFGCompiles();
697 int32_t codeTypeThresholdMultiplier() const;
699 int32_t adjustedCounterValue(int32_t desiredThreshold);
701 int32_t* addressOfJITExecuteCounter()
703 return &m_jitExecuteCounter.m_counter;
706 static ptrdiff_t offsetOfJITExecuteCounter() { return OBJECT_OFFSETOF(CodeBlock, m_jitExecuteCounter) + OBJECT_OFFSETOF(BaselineExecutionCounter, m_counter); }
707 static ptrdiff_t offsetOfJITExecutionActiveThreshold() { return OBJECT_OFFSETOF(CodeBlock, m_jitExecuteCounter) + OBJECT_OFFSETOF(BaselineExecutionCounter, m_activeThreshold); }
708 static ptrdiff_t offsetOfJITExecutionTotalCount() { return OBJECT_OFFSETOF(CodeBlock, m_jitExecuteCounter) + OBJECT_OFFSETOF(BaselineExecutionCounter, m_totalCount); }
710 const BaselineExecutionCounter& jitExecuteCounter() const { return m_jitExecuteCounter; }
712 unsigned optimizationDelayCounter() const { return m_optimizationDelayCounter; }
714 // Check if the optimization threshold has been reached, and if not,
715 // adjust the heuristics accordingly. Returns true if the threshold has
717 bool checkIfOptimizationThresholdReached();
719 // Call this to force the next optimization trigger to fire. This is
720 // rarely wise, since optimization triggers are typically more
721 // expensive than executing baseline code.
722 void optimizeNextInvocation();
724 // Call this to prevent optimization from happening again. Note that
725 // optimization will still happen after roughly 2^29 invocations,
726 // so this is really meant to delay that as much as possible. This
727 // is called if optimization failed, and we expect it to fail in
728 // the future as well.
729 void dontOptimizeAnytimeSoon();
731 // Call this to reinitialize the counter to its starting state,
732 // forcing a warm-up to happen before the next optimization trigger
733 // fires. This is called in the CodeBlock constructor. It also
734 // makes sense to call this if an OSR exit occurred. Note that
735 // OSR exit code is code generated, so the value of the execute
736 // counter that this corresponds to is also available directly.
737 void optimizeAfterWarmUp();
739 // Call this to force an optimization trigger to fire only after
741 void optimizeAfterLongWarmUp();
743 // Call this to cause an optimization trigger to fire soon, but
744 // not necessarily the next one. This makes sense if optimization
745 // succeeds. Successfuly optimization means that all calls are
746 // relinked to the optimized code, so this only affects call
747 // frames that are still executing this CodeBlock. The value here
748 // is tuned to strike a balance between the cost of OSR entry
749 // (which is too high to warrant making every loop back edge to
750 // trigger OSR immediately) and the cost of executing baseline
751 // code (which is high enough that we don't necessarily want to
752 // have a full warm-up). The intuition for calling this instead of
753 // optimizeNextInvocation() is for the case of recursive functions
754 // with loops. Consider that there may be N call frames of some
755 // recursive function, for a reasonably large value of N. The top
756 // one triggers optimization, and then returns, and then all of
757 // the others return. We don't want optimization to be triggered on
758 // each return, as that would be superfluous. It only makes sense
759 // to trigger optimization if one of those functions becomes hot
760 // in the baseline code.
763 void forceOptimizationSlowPathConcurrently();
765 void setOptimizationThresholdBasedOnCompilationResult(CompilationResult);
767 uint32_t osrExitCounter() const { return m_osrExitCounter; }
769 void countOSRExit() { m_osrExitCounter++; }
771 enum class OptimizeAction { None, ReoptimizeNow };
773 OptimizeAction updateOSRExitCounterAndCheckIfNeedToReoptimize(DFG::OSRExitState&);
776 static ptrdiff_t offsetOfOSRExitCounter() { return OBJECT_OFFSETOF(CodeBlock, m_osrExitCounter); }
778 uint32_t adjustedExitCountThreshold(uint32_t desiredThreshold);
779 uint32_t exitCountThresholdForReoptimization();
780 uint32_t exitCountThresholdForReoptimizationFromLoop();
781 bool shouldReoptimizeNow();
782 bool shouldReoptimizeFromLoopNow();
784 void setCalleeSaveRegisters(RegisterSet);
785 void setCalleeSaveRegisters(std::unique_ptr<RegisterAtOffsetList>);
787 RegisterAtOffsetList* calleeSaveRegisters() const { return m_calleeSaveRegisters.get(); }
789 static unsigned numberOfLLIntBaselineCalleeSaveRegisters() { return 0; }
790 static size_t llintBaselineCalleeSaveSpaceAsVirtualRegisters() { return 0; };
791 void optimizeAfterWarmUp() { }
792 unsigned numberOfDFGCompiles() { return 0; }
795 bool shouldOptimizeNow();
796 void updateAllValueProfilePredictions();
797 void updateAllArrayPredictions();
798 void updateAllPredictions();
800 unsigned frameRegisterCount();
801 int stackPointerOffset();
803 bool hasOpDebugForLineAndColumn(unsigned line, unsigned column);
805 bool hasDebuggerRequests() const { return m_debuggerRequests; }
806 void* debuggerRequestsAddress() { return &m_debuggerRequests; }
808 void addBreakpoint(unsigned numBreakpoints);
809 void removeBreakpoint(unsigned numBreakpoints)
811 ASSERT(m_numBreakpoints >= numBreakpoints);
812 m_numBreakpoints -= numBreakpoints;
816 SteppingModeDisabled,
819 void setSteppingMode(SteppingMode);
821 void clearDebuggerRequests()
823 m_steppingMode = SteppingModeDisabled;
824 m_numBreakpoints = 0;
827 bool wasCompiledWithDebuggingOpcodes() const { return m_unlinkedCode->wasCompiledWithDebuggingOpcodes(); }
829 // FIXME: Make these remaining members private.
831 int m_numCalleeLocals;
834 // This is intentionally public; it's the responsibility of anyone doing any
835 // of the following to hold the lock:
837 // - Modifying any inline cache in this code block.
839 // - Quering any inline cache in this code block, from a thread other than
842 // Additionally, it's only legal to modify the inline cache on the main
843 // thread. This means that the main thread can query the inline cache without
844 // locking. This is crucial since executing the inline cache is effectively
847 // Another exception to the rules is that the GC can do whatever it wants
848 // without holding any locks, because the GC is guaranteed to wait until any
849 // concurrent compilation threads finish what they're doing.
850 mutable ConcurrentJSLock m_lock;
852 bool m_visitWeaklyHasBeenCalled;
854 bool m_shouldAlwaysBeInlined; // Not a bitfield because the JIT wants to store to it.
857 unsigned m_capabilityLevelState : 2; // DFG::CapabilityLevel
860 bool m_allTransitionsHaveBeenMarked : 1; // Initialized and used on every GC.
862 bool m_didFailJITCompilation : 1;
863 bool m_didFailFTLCompilation : 1;
864 bool m_hasBeenCompiledWithFTL : 1;
865 bool m_isConstructor : 1;
866 bool m_isStrictMode : 1;
867 unsigned m_codeType : 2; // CodeType
869 // Internal methods for use by validation code. It would be private if it wasn't
870 // for the fact that we use it from anonymous namespaces.
871 void beginValidationDidFail();
872 NO_RETURN_DUE_TO_CRASH void endValidationDidFail();
875 WTF_MAKE_FAST_ALLOCATED;
877 Vector<HandlerInfo> m_exceptionHandlers;
879 // Buffers used for large array literals
880 Vector<Vector<JSValue>> m_constantBuffers;
883 Vector<SimpleJumpTable> m_switchJumpTables;
884 Vector<StringJumpTable> m_stringSwitchJumpTables;
886 DirectEvalCodeCache m_directEvalCodeCache;
889 void clearExceptionHandlers()
892 m_rareData->m_exceptionHandlers.clear();
895 void appendExceptionHandler(const HandlerInfo& handler)
897 createRareDataIfNecessary(); // We may be handling the exception of an inlined call frame.
898 m_rareData->m_exceptionHandlers.append(handler);
901 CallSiteIndex newExceptionHandlingCallSiteIndex(CallSiteIndex originalCallSite);
903 void ensureCatchLivenessIsComputedForBytecodeOffset(unsigned bytecodeOffset)
905 if (!!m_instructions[bytecodeOffset + 3].u.pointer) {
907 ConcurrentJSLocker locker(m_lock);
909 for (auto& profile : m_catchProfiles) {
910 if (profile.get() == m_instructions[bytecodeOffset + 3].u.pointer) {
920 ensureCatchLivenessIsComputedForBytecodeOffsetSlow(bytecodeOffset);
924 void setPCToCodeOriginMap(std::unique_ptr<PCToCodeOriginMap>&&);
925 std::optional<CodeOrigin> findPC(void* pc);
929 void finalizeLLIntInlineCaches();
930 void finalizeBaselineJITInlineCaches();
933 void tallyFrequentExitSites();
935 void tallyFrequentExitSites() { }
939 friend class CodeBlockSet;
941 BytecodeLivenessAnalysis& livenessAnalysisSlow();
943 CodeBlock* specialOSREntryBlockOrNull();
945 void noticeIncomingCall(ExecState* callerFrame);
947 double optimizationThresholdScalingFactor();
949 void updateAllPredictionsAndCountLiveness(unsigned& numberOfLiveNonArgumentValueProfiles, unsigned& numberOfSamplesInProfiles);
951 void setConstantIdentifierSetRegisters(VM&, const Vector<ConstantIndentifierSetEntry>& constants);
953 void setConstantRegisters(const Vector<WriteBarrier<Unknown>>& constants, const Vector<SourceCodeRepresentation>& constantsSourceCodeRepresentation);
955 void replaceConstant(int index, JSValue value)
957 ASSERT(isConstantRegisterIndex(index) && static_cast<size_t>(index - FirstConstantRegisterIndex) < m_constantRegisters.size());
958 m_constantRegisters[index - FirstConstantRegisterIndex].set(*m_vm, this, value);
961 bool shouldVisitStrongly(const ConcurrentJSLocker&);
962 bool shouldJettisonDueToWeakReference();
963 bool shouldJettisonDueToOldAge(const ConcurrentJSLocker&);
965 void propagateTransitions(const ConcurrentJSLocker&, SlotVisitor&);
966 void determineLiveness(const ConcurrentJSLocker&, SlotVisitor&);
968 void stronglyVisitStrongReferences(const ConcurrentJSLocker&, SlotVisitor&);
969 void stronglyVisitWeakReferences(const ConcurrentJSLocker&, SlotVisitor&);
970 void visitOSRExitTargets(const ConcurrentJSLocker&, SlotVisitor&);
972 std::chrono::milliseconds timeSinceCreation()
974 return std::chrono::duration_cast<std::chrono::milliseconds>(
975 std::chrono::steady_clock::now() - m_creationTime);
978 void createRareDataIfNecessary()
981 m_rareData = std::make_unique<RareData>();
984 void insertBasicBlockBoundariesForControlFlowProfiler(RefCountedArray<Instruction>&);
985 void ensureCatchLivenessIsComputedForBytecodeOffsetSlow(unsigned);
987 WriteBarrier<UnlinkedCodeBlock> m_unlinkedCode;
989 int m_numberOfArgumentsToSkip { 0 };
991 unsigned m_debuggerRequests;
993 unsigned m_hasDebuggerStatement : 1;
994 unsigned m_steppingMode : 1;
995 unsigned m_numBreakpoints : 30;
998 WriteBarrier<ExecutableBase> m_ownerExecutable;
1001 RefCountedArray<Instruction> m_instructions;
1002 VirtualRegister m_thisRegister;
1003 VirtualRegister m_scopeRegister;
1004 mutable CodeBlockHash m_hash;
1006 RefPtr<SourceProvider> m_source;
1007 unsigned m_sourceOffset;
1008 unsigned m_firstLineColumnOffset;
1010 RefCountedArray<LLIntCallLinkInfo> m_llintCallLinkInfos;
1011 SentinelLinkedList<LLIntCallLinkInfo, BasicRawSentinelNode<LLIntCallLinkInfo>> m_incomingLLIntCalls;
1012 StructureWatchpointMap m_llintGetByIdWatchpointMap;
1013 RefPtr<JITCode> m_jitCode;
1015 std::unique_ptr<RegisterAtOffsetList> m_calleeSaveRegisters;
1016 Bag<StructureStubInfo> m_stubInfos;
1017 Bag<JITAddIC> m_addICs;
1018 Bag<JITMulIC> m_mulICs;
1019 Bag<JITNegIC> m_negICs;
1020 Bag<JITSubIC> m_subICs;
1021 Bag<ByValInfo> m_byValInfos;
1022 Bag<CallLinkInfo> m_callLinkInfos;
1023 SentinelLinkedList<CallLinkInfo, BasicRawSentinelNode<CallLinkInfo>> m_incomingCalls;
1024 SentinelLinkedList<PolymorphicCallNode, BasicRawSentinelNode<PolymorphicCallNode>> m_incomingPolymorphicCalls;
1025 std::unique_ptr<PCToCodeOriginMap> m_pcToCodeOriginMap;
1027 std::unique_ptr<CompactJITCodeMap> m_jitCodeMap;
1029 // This is relevant to non-DFG code blocks that serve as the profiled code block
1030 // for DFG code blocks.
1031 DFG::ExitProfile m_exitProfile;
1032 CompressedLazyOperandValueProfileHolder m_lazyOperandValueProfiles;
1034 RefCountedArray<ValueProfile> m_argumentValueProfiles;
1035 RefCountedArray<ValueProfile> m_valueProfiles;
1036 Vector<std::unique_ptr<ValueProfileAndOperandBuffer>> m_catchProfiles;
1037 SegmentedVector<RareCaseProfile, 8> m_rareCaseProfiles;
1038 RefCountedArray<ArrayAllocationProfile> m_arrayAllocationProfiles;
1039 ArrayProfileVector m_arrayProfiles;
1040 RefCountedArray<ObjectAllocationProfile> m_objectAllocationProfiles;
1043 COMPILE_ASSERT(sizeof(Register) == sizeof(WriteBarrier<Unknown>), Register_must_be_same_size_as_WriteBarrier_Unknown);
1044 // TODO: This could just be a pointer to m_unlinkedCodeBlock's data, but the DFG mutates
1045 // it, so we're stuck with it for now.
1046 Vector<WriteBarrier<Unknown>> m_constantRegisters;
1047 Vector<SourceCodeRepresentation> m_constantsSourceCodeRepresentation;
1048 RefCountedArray<WriteBarrier<FunctionExecutable>> m_functionDecls;
1049 RefCountedArray<WriteBarrier<FunctionExecutable>> m_functionExprs;
1051 WriteBarrier<CodeBlock> m_alternative;
1053 BaselineExecutionCounter m_llintExecuteCounter;
1055 BaselineExecutionCounter m_jitExecuteCounter;
1056 uint32_t m_osrExitCounter;
1057 uint16_t m_optimizationDelayCounter;
1058 uint16_t m_reoptimizationRetryCounter;
1060 std::chrono::steady_clock::time_point m_creationTime;
1062 std::unique_ptr<BytecodeLivenessAnalysis> m_livenessAnalysis;
1064 std::unique_ptr<RareData> m_rareData;
1066 UnconditionalFinalizer m_unconditionalFinalizer;
1067 WeakReferenceHarvester m_weakReferenceHarvester;
1070 inline Register& ExecState::r(int index)
1072 CodeBlock* codeBlock = this->codeBlock();
1073 if (codeBlock->isConstantRegisterIndex(index))
1074 return *reinterpret_cast<Register*>(&codeBlock->constantRegister(index));
1078 inline Register& ExecState::r(VirtualRegister reg)
1080 return r(reg.offset());
1083 inline Register& ExecState::uncheckedR(int index)
1085 RELEASE_ASSERT(index < FirstConstantRegisterIndex);
1089 inline Register& ExecState::uncheckedR(VirtualRegister reg)
1091 return uncheckedR(reg.offset());
1094 inline void CodeBlock::clearVisitWeaklyHasBeenCalled()
1096 m_visitWeaklyHasBeenCalled = false;
1099 template <typename ExecutableType>
1100 JSObject* ScriptExecutable::prepareForExecution(VM& vm, JSFunction* function, JSScope* scope, CodeSpecializationKind kind, CodeBlock*& resultCodeBlock)
1102 if (hasJITCodeFor(kind)) {
1103 if (std::is_same<ExecutableType, EvalExecutable>::value)
1104 resultCodeBlock = jsCast<CodeBlock*>(jsCast<EvalExecutable*>(this)->codeBlock());
1105 else if (std::is_same<ExecutableType, ProgramExecutable>::value)
1106 resultCodeBlock = jsCast<CodeBlock*>(jsCast<ProgramExecutable*>(this)->codeBlock());
1107 else if (std::is_same<ExecutableType, ModuleProgramExecutable>::value)
1108 resultCodeBlock = jsCast<CodeBlock*>(jsCast<ModuleProgramExecutable*>(this)->codeBlock());
1109 else if (std::is_same<ExecutableType, FunctionExecutable>::value)
1110 resultCodeBlock = jsCast<CodeBlock*>(jsCast<FunctionExecutable*>(this)->codeBlockFor(kind));
1112 RELEASE_ASSERT_NOT_REACHED();
1115 return prepareForExecutionImpl(vm, function, scope, kind, resultCodeBlock);
1118 #define CODEBLOCK_LOG_EVENT(codeBlock, summary, details) \
1119 (codeBlock->vm()->logEvent(codeBlock, summary, [&] () { return toCString details; }))
1122 void setPrinter(Printer::PrintRecord&, CodeBlock*);
1128 JS_EXPORT_PRIVATE void printInternal(PrintStream&, JSC::CodeBlock*);