Need to handle CodeBlock::replacement() being null.
[WebKit-https.git] / Source / JavaScriptCore / bytecode / CodeBlock.cpp
1 /*
2  * Copyright (C) 2008-2018 Apple Inc. All rights reserved.
3  * Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca>
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1.  Redistributions of source code must retain the above copyright
10  *     notice, this list of conditions and the following disclaimer.
11  * 2.  Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution.
14  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
15  *     its contributors may be used to endorse or promote products derived
16  *     from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include "config.h"
31 #include "CodeBlock.h"
32
33 #include "ArithProfile.h"
34 #include "BasicBlockLocation.h"
35 #include "BytecodeDumper.h"
36 #include "BytecodeGenerator.h"
37 #include "BytecodeLivenessAnalysis.h"
38 #include "BytecodeStructs.h"
39 #include "BytecodeUseDef.h"
40 #include "CallLinkStatus.h"
41 #include "CodeBlockSet.h"
42 #include "DFGCapabilities.h"
43 #include "DFGCommon.h"
44 #include "DFGDriver.h"
45 #include "DFGJITCode.h"
46 #include "DFGWorklist.h"
47 #include "Debugger.h"
48 #include "EvalCodeBlock.h"
49 #include "FullCodeOrigin.h"
50 #include "FunctionCodeBlock.h"
51 #include "FunctionExecutableDump.h"
52 #include "GetPutInfo.h"
53 #include "InlineCallFrame.h"
54 #include "InterpreterInlines.h"
55 #include "IsoCellSetInlines.h"
56 #include "JIT.h"
57 #include "JITMathIC.h"
58 #include "JSBigInt.h"
59 #include "JSCInlines.h"
60 #include "JSCJSValue.h"
61 #include "JSFunction.h"
62 #include "JSLexicalEnvironment.h"
63 #include "JSModuleEnvironment.h"
64 #include "JSSet.h"
65 #include "JSString.h"
66 #include "JSTemplateObjectDescriptor.h"
67 #include "LLIntData.h"
68 #include "LLIntEntrypoint.h"
69 #include "LLIntPrototypeLoadAdaptiveStructureWatchpoint.h"
70 #include "LowLevelInterpreter.h"
71 #include "ModuleProgramCodeBlock.h"
72 #include "ObjectAllocationProfileInlines.h"
73 #include "PCToCodeOriginMap.h"
74 #include "PolymorphicAccess.h"
75 #include "ProfilerDatabase.h"
76 #include "ProgramCodeBlock.h"
77 #include "ReduceWhitespace.h"
78 #include "Repatch.h"
79 #include "SlotVisitorInlines.h"
80 #include "StackVisitor.h"
81 #include "StructureStubInfo.h"
82 #include "TypeLocationCache.h"
83 #include "TypeProfiler.h"
84 #include "UnlinkedInstructionStream.h"
85 #include "VMInlines.h"
86 #include <wtf/BagToHashMap.h>
87 #include <wtf/CommaPrinter.h>
88 #include <wtf/SimpleStats.h>
89 #include <wtf/StringPrintStream.h>
90 #include <wtf/text/UniquedStringImpl.h>
91
92 #if ENABLE(JIT)
93 #include "RegisterAtOffsetList.h"
94 #endif
95
96 #if ENABLE(DFG_JIT)
97 #include "DFGOperations.h"
98 #endif
99
100 #if ENABLE(FTL_JIT)
101 #include "FTLJITCode.h"
102 #endif
103
104 namespace JSC {
105
106 const ClassInfo CodeBlock::s_info = {
107     "CodeBlock", nullptr, nullptr, nullptr,
108     CREATE_METHOD_TABLE(CodeBlock)
109 };
110
111 CString CodeBlock::inferredName() const
112 {
113     switch (codeType()) {
114     case GlobalCode:
115         return "<global>";
116     case EvalCode:
117         return "<eval>";
118     case FunctionCode:
119         return jsCast<FunctionExecutable*>(ownerExecutable())->inferredName().utf8();
120     case ModuleCode:
121         return "<module>";
122     default:
123         CRASH();
124         return CString("", 0);
125     }
126 }
127
128 bool CodeBlock::hasHash() const
129 {
130     return !!m_hash;
131 }
132
133 bool CodeBlock::isSafeToComputeHash() const
134 {
135     return !isCompilationThread();
136 }
137
138 CodeBlockHash CodeBlock::hash() const
139 {
140     if (!m_hash) {
141         RELEASE_ASSERT(isSafeToComputeHash());
142         m_hash = CodeBlockHash(ownerScriptExecutable()->source(), specializationKind());
143     }
144     return m_hash;
145 }
146
147 CString CodeBlock::sourceCodeForTools() const
148 {
149     if (codeType() != FunctionCode)
150         return ownerScriptExecutable()->source().toUTF8();
151     
152     SourceProvider* provider = source();
153     FunctionExecutable* executable = jsCast<FunctionExecutable*>(ownerExecutable());
154     UnlinkedFunctionExecutable* unlinked = executable->unlinkedExecutable();
155     unsigned unlinkedStartOffset = unlinked->startOffset();
156     unsigned linkedStartOffset = executable->source().startOffset();
157     int delta = linkedStartOffset - unlinkedStartOffset;
158     unsigned rangeStart = delta + unlinked->unlinkedFunctionNameStart();
159     unsigned rangeEnd = delta + unlinked->startOffset() + unlinked->sourceLength();
160     return toCString(
161         "function ",
162         provider->source().substring(rangeStart, rangeEnd - rangeStart).utf8());
163 }
164
165 CString CodeBlock::sourceCodeOnOneLine() const
166 {
167     return reduceWhitespace(sourceCodeForTools());
168 }
169
170 CString CodeBlock::hashAsStringIfPossible() const
171 {
172     if (hasHash() || isSafeToComputeHash())
173         return toCString(hash());
174     return "<no-hash>";
175 }
176
177 void CodeBlock::dumpAssumingJITType(PrintStream& out, JITCode::JITType jitType) const
178 {
179     out.print(inferredName(), "#", hashAsStringIfPossible());
180     out.print(":[", RawPointer(this), "->");
181     if (!!m_alternative)
182         out.print(RawPointer(alternative()), "->");
183     out.print(RawPointer(ownerExecutable()), ", ", jitType, codeType());
184
185     if (codeType() == FunctionCode)
186         out.print(specializationKind());
187     out.print(", ", instructionCount());
188     if (this->jitType() == JITCode::BaselineJIT && m_shouldAlwaysBeInlined)
189         out.print(" (ShouldAlwaysBeInlined)");
190     if (ownerScriptExecutable()->neverInline())
191         out.print(" (NeverInline)");
192     if (ownerScriptExecutable()->neverOptimize())
193         out.print(" (NeverOptimize)");
194     else if (ownerScriptExecutable()->neverFTLOptimize())
195         out.print(" (NeverFTLOptimize)");
196     if (ownerScriptExecutable()->didTryToEnterInLoop())
197         out.print(" (DidTryToEnterInLoop)");
198     if (ownerScriptExecutable()->isStrictMode())
199         out.print(" (StrictMode)");
200     if (m_didFailJITCompilation)
201         out.print(" (JITFail)");
202     if (this->jitType() == JITCode::BaselineJIT && m_didFailFTLCompilation)
203         out.print(" (FTLFail)");
204     if (this->jitType() == JITCode::BaselineJIT && m_hasBeenCompiledWithFTL)
205         out.print(" (HadFTLReplacement)");
206     out.print("]");
207 }
208
209 void CodeBlock::dump(PrintStream& out) const
210 {
211     dumpAssumingJITType(out, jitType());
212 }
213
214 void CodeBlock::dumpSource()
215 {
216     dumpSource(WTF::dataFile());
217 }
218
219 void CodeBlock::dumpSource(PrintStream& out)
220 {
221     ScriptExecutable* executable = ownerScriptExecutable();
222     if (executable->isFunctionExecutable()) {
223         FunctionExecutable* functionExecutable = reinterpret_cast<FunctionExecutable*>(executable);
224         StringView source = functionExecutable->source().provider()->getRange(
225             functionExecutable->parametersStartOffset(),
226             functionExecutable->typeProfilingEndOffset() + 1); // Type profiling end offset is the character before the '}'.
227         
228         out.print("function ", inferredName(), source);
229         return;
230     }
231     out.print(executable->source().view());
232 }
233
234 void CodeBlock::dumpBytecode()
235 {
236     dumpBytecode(WTF::dataFile());
237 }
238
239 void CodeBlock::dumpBytecode(PrintStream& out)
240 {
241     StubInfoMap stubInfos;
242     CallLinkInfoMap callLinkInfos;
243     getStubInfoMap(stubInfos);
244     getCallLinkInfoMap(callLinkInfos);
245     BytecodeDumper<CodeBlock>::dumpBlock(this, instructions(), out, stubInfos, callLinkInfos);
246 }
247
248 void CodeBlock::dumpBytecode(PrintStream& out, const Instruction* begin, const Instruction*& it, const StubInfoMap& stubInfos, const CallLinkInfoMap& callLinkInfos)
249 {
250     BytecodeDumper<CodeBlock>::dumpBytecode(this, out, begin, it, stubInfos, callLinkInfos);
251 }
252
253 void CodeBlock::dumpBytecode(
254     PrintStream& out, unsigned bytecodeOffset,
255     const StubInfoMap& stubInfos, const CallLinkInfoMap& callLinkInfos)
256 {
257     const Instruction* it = &instructions()[bytecodeOffset];
258     dumpBytecode(out, instructions().begin(), it, stubInfos, callLinkInfos);
259 }
260
261 #define FOR_EACH_MEMBER_VECTOR(macro) \
262     macro(instructions) \
263     macro(callLinkInfos) \
264     macro(linkedCallerList) \
265     macro(identifiers) \
266     macro(functionExpressions) \
267     macro(constantRegisters)
268
269 template<typename T>
270 static size_t sizeInBytes(const Vector<T>& vector)
271 {
272     return vector.capacity() * sizeof(T);
273 }
274
275 namespace {
276
277 class PutToScopeFireDetail : public FireDetail {
278 public:
279     PutToScopeFireDetail(CodeBlock* codeBlock, const Identifier& ident)
280         : m_codeBlock(codeBlock)
281         , m_ident(ident)
282     {
283     }
284     
285     void dump(PrintStream& out) const override
286     {
287         out.print("Linking put_to_scope in ", FunctionExecutableDump(jsCast<FunctionExecutable*>(m_codeBlock->ownerExecutable())), " for ", m_ident);
288     }
289     
290 private:
291     CodeBlock* m_codeBlock;
292     const Identifier& m_ident;
293 };
294
295 } // anonymous namespace
296
297 CodeBlock::CodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, CodeBlock& other)
298     : JSCell(*vm, structure)
299     , m_globalObject(other.m_globalObject)
300     , m_shouldAlwaysBeInlined(true)
301 #if ENABLE(JIT)
302     , m_capabilityLevelState(DFG::CapabilityLevelNotSet)
303 #endif
304     , m_didFailJITCompilation(false)
305     , m_didFailFTLCompilation(false)
306     , m_hasBeenCompiledWithFTL(false)
307     , m_isConstructor(other.m_isConstructor)
308     , m_isStrictMode(other.m_isStrictMode)
309     , m_codeType(other.m_codeType)
310     , m_numCalleeLocals(other.m_numCalleeLocals)
311     , m_numVars(other.m_numVars)
312     , m_numberOfArgumentsToSkip(other.m_numberOfArgumentsToSkip)
313     , m_hasDebuggerStatement(false)
314     , m_steppingMode(SteppingModeDisabled)
315     , m_numBreakpoints(0)
316     , m_unlinkedCode(*other.vm(), this, other.m_unlinkedCode.get())
317     , m_ownerExecutable(*other.vm(), this, other.m_ownerExecutable.get())
318     , m_poisonedVM(other.m_poisonedVM)
319     , m_instructions(other.m_instructions)
320     , m_thisRegister(other.m_thisRegister)
321     , m_scopeRegister(other.m_scopeRegister)
322     , m_hash(other.m_hash)
323     , m_source(other.m_source)
324     , m_sourceOffset(other.m_sourceOffset)
325     , m_firstLineColumnOffset(other.m_firstLineColumnOffset)
326     , m_constantRegisters(other.m_constantRegisters)
327     , m_constantsSourceCodeRepresentation(other.m_constantsSourceCodeRepresentation)
328     , m_functionDecls(other.m_functionDecls)
329     , m_functionExprs(other.m_functionExprs)
330     , m_osrExitCounter(0)
331     , m_optimizationDelayCounter(0)
332     , m_reoptimizationRetryCounter(0)
333     , m_creationTime(MonotonicTime::now())
334 {
335     ASSERT(heap()->isDeferred());
336     ASSERT(m_scopeRegister.isLocal());
337
338     setNumParameters(other.numParameters());
339     
340     vm->heap.codeBlockSet().add(this);
341 }
342
343 void CodeBlock::finishCreation(VM& vm, CopyParsedBlockTag, CodeBlock& other)
344 {
345     Base::finishCreation(vm);
346     finishCreationCommon(vm);
347
348     optimizeAfterWarmUp();
349     jitAfterWarmUp();
350
351     if (other.m_rareData) {
352         createRareDataIfNecessary();
353         
354         m_rareData->m_exceptionHandlers = other.m_rareData->m_exceptionHandlers;
355         m_rareData->m_switchJumpTables = other.m_rareData->m_switchJumpTables;
356         m_rareData->m_stringSwitchJumpTables = other.m_rareData->m_stringSwitchJumpTables;
357     }
358 }
359
360 CodeBlock::CodeBlock(VM* vm, Structure* structure, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock,
361     JSScope* scope, RefPtr<SourceProvider>&& sourceProvider, unsigned sourceOffset, unsigned firstLineColumnOffset)
362     : JSCell(*vm, structure)
363     , m_globalObject(*vm, this, scope->globalObject(*vm))
364     , m_shouldAlwaysBeInlined(true)
365 #if ENABLE(JIT)
366     , m_capabilityLevelState(DFG::CapabilityLevelNotSet)
367 #endif
368     , m_didFailJITCompilation(false)
369     , m_didFailFTLCompilation(false)
370     , m_hasBeenCompiledWithFTL(false)
371     , m_isConstructor(unlinkedCodeBlock->isConstructor())
372     , m_isStrictMode(unlinkedCodeBlock->isStrictMode())
373     , m_codeType(unlinkedCodeBlock->codeType())
374     , m_numCalleeLocals(unlinkedCodeBlock->numCalleeLocals())
375     , m_numVars(unlinkedCodeBlock->numVars())
376     , m_hasDebuggerStatement(false)
377     , m_steppingMode(SteppingModeDisabled)
378     , m_numBreakpoints(0)
379     , m_unlinkedCode(*vm, this, unlinkedCodeBlock)
380     , m_ownerExecutable(*vm, this, ownerExecutable)
381     , m_poisonedVM(vm)
382     , m_thisRegister(unlinkedCodeBlock->thisRegister())
383     , m_scopeRegister(unlinkedCodeBlock->scopeRegister())
384     , m_source(WTFMove(sourceProvider))
385     , m_sourceOffset(sourceOffset)
386     , m_firstLineColumnOffset(firstLineColumnOffset)
387     , m_osrExitCounter(0)
388     , m_optimizationDelayCounter(0)
389     , m_reoptimizationRetryCounter(0)
390     , m_creationTime(MonotonicTime::now())
391 {
392     ASSERT(heap()->isDeferred());
393     ASSERT(m_scopeRegister.isLocal());
394
395     ASSERT(m_source);
396     setNumParameters(unlinkedCodeBlock->numParameters());
397     
398     vm->heap.codeBlockSet().add(this);
399 }
400
401 // The main purpose of this function is to generate linked bytecode from unlinked bytecode. The process
402 // of linking is taking an abstract representation of bytecode and tying it to a GlobalObject and scope
403 // chain. For example, this process allows us to cache the depth of lexical environment reads that reach
404 // outside of this CodeBlock's compilation unit. It also allows us to generate particular constants that
405 // we can't generate during unlinked bytecode generation. This process is not allowed to generate control
406 // flow or introduce new locals. The reason for this is we rely on liveness analysis to be the same for
407 // all the CodeBlocks of an UnlinkedCodeBlock. We rely on this fact by caching the liveness analysis
408 // inside UnlinkedCodeBlock.
409 bool CodeBlock::finishCreation(VM& vm, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock,
410     JSScope* scope)
411 {
412     Base::finishCreation(vm);
413     finishCreationCommon(vm);
414
415     auto throwScope = DECLARE_THROW_SCOPE(vm);
416
417     if (vm.typeProfiler() || vm.controlFlowProfiler())
418         vm.functionHasExecutedCache()->removeUnexecutedRange(ownerExecutable->sourceID(), ownerExecutable->typeProfilingStartOffset(), ownerExecutable->typeProfilingEndOffset());
419
420     setConstantRegisters(unlinkedCodeBlock->constantRegisters(), unlinkedCodeBlock->constantsSourceCodeRepresentation());
421     RETURN_IF_EXCEPTION(throwScope, false);
422
423     setConstantIdentifierSetRegisters(vm, unlinkedCodeBlock->constantIdentifierSets());
424     RETURN_IF_EXCEPTION(throwScope, false);
425
426     if (unlinkedCodeBlock->usesGlobalObject())
427         m_constantRegisters[unlinkedCodeBlock->globalObjectRegister().toConstantIndex()].set(vm, this, m_globalObject.get());
428
429     for (unsigned i = 0; i < LinkTimeConstantCount; i++) {
430         LinkTimeConstant type = static_cast<LinkTimeConstant>(i);
431         if (unsigned registerIndex = unlinkedCodeBlock->registerIndexForLinkTimeConstant(type))
432             m_constantRegisters[registerIndex].set(vm, this, m_globalObject->jsCellForLinkTimeConstant(type));
433     }
434
435     // We already have the cloned symbol table for the module environment since we need to instantiate
436     // the module environments before linking the code block. We replace the stored symbol table with the already cloned one.
437     if (UnlinkedModuleProgramCodeBlock* unlinkedModuleProgramCodeBlock = jsDynamicCast<UnlinkedModuleProgramCodeBlock*>(vm, unlinkedCodeBlock)) {
438         SymbolTable* clonedSymbolTable = jsCast<ModuleProgramExecutable*>(ownerExecutable)->moduleEnvironmentSymbolTable();
439         if (vm.typeProfiler()) {
440             ConcurrentJSLocker locker(clonedSymbolTable->m_lock);
441             clonedSymbolTable->prepareForTypeProfiling(locker);
442         }
443         replaceConstant(unlinkedModuleProgramCodeBlock->moduleEnvironmentSymbolTableConstantRegisterOffset(), clonedSymbolTable);
444     }
445
446     bool shouldUpdateFunctionHasExecutedCache = vm.typeProfiler() || vm.controlFlowProfiler();
447     m_functionDecls = RefCountedArray<WriteBarrier<FunctionExecutable>>(unlinkedCodeBlock->numberOfFunctionDecls());
448     for (size_t count = unlinkedCodeBlock->numberOfFunctionDecls(), i = 0; i < count; ++i) {
449         UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionDecl(i);
450         if (shouldUpdateFunctionHasExecutedCache)
451             vm.functionHasExecutedCache()->insertUnexecutedRange(ownerExecutable->sourceID(), unlinkedExecutable->typeProfilingStartOffset(), unlinkedExecutable->typeProfilingEndOffset());
452         m_functionDecls[i].set(vm, this, unlinkedExecutable->link(vm, ownerExecutable->source()));
453     }
454
455     m_functionExprs = RefCountedArray<WriteBarrier<FunctionExecutable>>(unlinkedCodeBlock->numberOfFunctionExprs());
456     for (size_t count = unlinkedCodeBlock->numberOfFunctionExprs(), i = 0; i < count; ++i) {
457         UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionExpr(i);
458         if (shouldUpdateFunctionHasExecutedCache)
459             vm.functionHasExecutedCache()->insertUnexecutedRange(ownerExecutable->sourceID(), unlinkedExecutable->typeProfilingStartOffset(), unlinkedExecutable->typeProfilingEndOffset());
460         m_functionExprs[i].set(vm, this, unlinkedExecutable->link(vm, ownerExecutable->source()));
461     }
462
463     if (unlinkedCodeBlock->hasRareData()) {
464         createRareDataIfNecessary();
465         if (size_t count = unlinkedCodeBlock->numberOfExceptionHandlers()) {
466             m_rareData->m_exceptionHandlers.resizeToFit(count);
467             for (size_t i = 0; i < count; i++) {
468                 const UnlinkedHandlerInfo& unlinkedHandler = unlinkedCodeBlock->exceptionHandler(i);
469                 HandlerInfo& handler = m_rareData->m_exceptionHandlers[i];
470 #if ENABLE(JIT)
471                 handler.initialize(unlinkedHandler, CodeLocationLabel<ExceptionHandlerPtrTag>(LLInt::getCodePtr<BytecodePtrTag>(op_catch).retagged<ExceptionHandlerPtrTag>()));
472 #else
473                 handler.initialize(unlinkedHandler);
474 #endif
475             }
476         }
477
478         if (size_t count = unlinkedCodeBlock->numberOfStringSwitchJumpTables()) {
479             m_rareData->m_stringSwitchJumpTables.grow(count);
480             for (size_t i = 0; i < count; i++) {
481                 UnlinkedStringJumpTable::StringOffsetTable::iterator ptr = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.begin();
482                 UnlinkedStringJumpTable::StringOffsetTable::iterator end = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.end();
483                 for (; ptr != end; ++ptr) {
484                     OffsetLocation offset;
485                     offset.branchOffset = ptr->value.branchOffset;
486                     m_rareData->m_stringSwitchJumpTables[i].offsetTable.add(ptr->key, offset);
487                 }
488             }
489         }
490
491         if (size_t count = unlinkedCodeBlock->numberOfSwitchJumpTables()) {
492             m_rareData->m_switchJumpTables.grow(count);
493             for (size_t i = 0; i < count; i++) {
494                 UnlinkedSimpleJumpTable& sourceTable = unlinkedCodeBlock->switchJumpTable(i);
495                 SimpleJumpTable& destTable = m_rareData->m_switchJumpTables[i];
496                 destTable.branchOffsets = sourceTable.branchOffsets;
497                 destTable.min = sourceTable.min;
498             }
499         }
500     }
501
502     // Allocate metadata buffers for the bytecode
503     if (size_t size = unlinkedCodeBlock->numberOfLLintCallLinkInfos())
504         m_llintCallLinkInfos = RefCountedArray<LLIntCallLinkInfo>(size);
505     if (size_t size = unlinkedCodeBlock->numberOfArrayProfiles())
506         m_arrayProfiles.grow(size);
507     if (size_t size = unlinkedCodeBlock->numberOfArrayAllocationProfiles())
508         m_arrayAllocationProfiles = RefCountedArray<ArrayAllocationProfile>(size);
509     if (size_t size = unlinkedCodeBlock->numberOfValueProfiles())
510         m_valueProfiles = RefCountedArray<ValueProfile>(size);
511     if (!vm.canUseJIT())
512         RELEASE_ASSERT(!m_valueProfiles.size());
513     if (size_t size = unlinkedCodeBlock->numberOfObjectAllocationProfiles())
514         m_objectAllocationProfiles = RefCountedArray<ObjectAllocationProfile>(size);
515
516 #if ENABLE(JIT)
517     setCalleeSaveRegisters(RegisterSet::llintBaselineCalleeSaveRegisters());
518 #endif
519
520     // Copy and translate the UnlinkedInstructions
521     unsigned instructionCount = unlinkedCodeBlock->instructions().count();
522     UnlinkedInstructionStream::Reader instructionReader(unlinkedCodeBlock->instructions());
523
524     // Bookkeep the strongly referenced module environments.
525     HashSet<JSModuleEnvironment*> stronglyReferencedModuleEnvironments;
526
527     RefCountedArray<Instruction> instructions(instructionCount);
528
529     unsigned valueProfileCount = 0;
530     auto linkValueProfile = [&](unsigned bytecodeOffset, unsigned opLength) {
531         if (!vm.canUseJIT()) {
532             ASSERT(vm.noJITValueProfileSingleton);
533             instructions[bytecodeOffset + opLength - 1] = vm.noJITValueProfileSingleton.get();
534             return;
535         }
536
537         unsigned valueProfileIndex = valueProfileCount++;
538         ValueProfile* profile = &m_valueProfiles[valueProfileIndex];
539         ASSERT(profile->m_bytecodeOffset == -1);
540         profile->m_bytecodeOffset = bytecodeOffset;
541         instructions[bytecodeOffset + opLength - 1] = profile;
542     };
543
544     for (unsigned i = 0; !instructionReader.atEnd(); ) {
545         const UnlinkedInstruction* pc = instructionReader.next();
546
547         unsigned opLength = opcodeLength(pc[0].u.opcode);
548
549         instructions[i] = Interpreter::getOpcode(pc[0].u.opcode);
550         for (size_t j = 1; j < opLength; ++j) {
551             if (sizeof(int32_t) != sizeof(intptr_t))
552                 instructions[i + j].u.pointer = 0;
553             instructions[i + j].u.operand = pc[j].u.operand;
554         }
555         switch (pc[0].u.opcode) {
556         case op_has_indexed_property: {
557             int arrayProfileIndex = pc[opLength - 1].u.operand;
558             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
559
560             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
561             break;
562         }
563         case op_call_varargs:
564         case op_tail_call_varargs:
565         case op_tail_call_forward_arguments:
566         case op_construct_varargs:
567         case op_get_by_val: {
568             int arrayProfileIndex = pc[opLength - 2].u.operand;
569             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
570
571             instructions[i + opLength - 2] = &m_arrayProfiles[arrayProfileIndex];
572             FALLTHROUGH;
573         }
574         case op_get_direct_pname:
575         case op_get_by_id:
576         case op_get_by_id_with_this:
577         case op_try_get_by_id:
578         case op_get_by_id_direct:
579         case op_get_by_val_with_this:
580         case op_get_from_arguments:
581         case op_to_number:
582         case op_to_object:
583         case op_get_argument: {
584             linkValueProfile(i, opLength);
585             break;
586         }
587
588         case op_to_this: {
589             linkValueProfile(i, opLength);
590             break;
591         }
592
593         case op_in_by_val:
594         case op_put_by_val:
595         case op_put_by_val_direct: {
596             int arrayProfileIndex = pc[opLength - 1].u.operand;
597             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
598             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
599             break;
600         }
601
602         case op_new_array:
603         case op_new_array_with_size:
604         case op_new_array_buffer: {
605             unsigned arrayAllocationProfileIndex;
606             IndexingType recommendedIndexingType;
607             std::tie(arrayAllocationProfileIndex, recommendedIndexingType) = UnlinkedCodeBlock::decompressArrayAllocationProfile(pc[opLength - 1].u.operand);
608
609             ArrayAllocationProfile* profile = &m_arrayAllocationProfiles[arrayAllocationProfileIndex];
610             if (pc[0].u.opcode == op_new_array_buffer)
611                 profile->initializeIndexingMode(recommendedIndexingType);
612             instructions[i + opLength - 1] = profile;
613             break;
614         }
615
616         case op_new_object: {
617             int objectAllocationProfileIndex = pc[opLength - 1].u.operand;
618             ObjectAllocationProfile* objectAllocationProfile = &m_objectAllocationProfiles[objectAllocationProfileIndex];
619             int inferredInlineCapacity = pc[opLength - 2].u.operand;
620
621             instructions[i + opLength - 1] = objectAllocationProfile;
622             objectAllocationProfile->initializeProfile(vm,
623                 m_globalObject.get(), this, m_globalObject->objectPrototype(), inferredInlineCapacity);
624             break;
625         }
626
627         case op_call:
628         case op_tail_call:
629         case op_call_eval: {
630             linkValueProfile(i, opLength);
631             int arrayProfileIndex = pc[opLength - 2].u.operand;
632             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
633             instructions[i + opLength - 2] = &m_arrayProfiles[arrayProfileIndex];
634             instructions[i + 5] = &m_llintCallLinkInfos[pc[5].u.operand];
635             break;
636         }
637         case op_construct: {
638             instructions[i + 5] = &m_llintCallLinkInfos[pc[5].u.operand];
639             linkValueProfile(i, opLength);
640             break;
641         }
642         case op_get_array_length:
643             CRASH();
644
645         case op_resolve_scope: {
646             const Identifier& ident = identifier(pc[3].u.operand);
647             ResolveType type = static_cast<ResolveType>(pc[4].u.operand);
648             RELEASE_ASSERT(type != LocalClosureVar);
649             int localScopeDepth = pc[5].u.operand;
650
651             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Get, type, InitializationMode::NotInitialization);
652             RETURN_IF_EXCEPTION(throwScope, false);
653
654             instructions[i + 4].u.operand = op.type;
655             instructions[i + 5].u.operand = op.depth;
656             if (op.lexicalEnvironment) {
657                 if (op.type == ModuleVar) {
658                     // Keep the linked module environment strongly referenced.
659                     if (stronglyReferencedModuleEnvironments.add(jsCast<JSModuleEnvironment*>(op.lexicalEnvironment)).isNewEntry)
660                         addConstant(op.lexicalEnvironment);
661                     instructions[i + 6].u.jsCell.set(vm, this, op.lexicalEnvironment);
662                 } else
663                     instructions[i + 6].u.symbolTable.set(vm, this, op.lexicalEnvironment->symbolTable());
664             } else if (JSScope* constantScope = JSScope::constantScopeForCodeBlock(op.type, this))
665                 instructions[i + 6].u.jsCell.set(vm, this, constantScope);
666             else
667                 instructions[i + 6].u.pointer = nullptr;
668             break;
669         }
670
671         case op_get_from_scope: {
672             linkValueProfile(i, opLength);
673
674             // get_from_scope dst, scope, id, GetPutInfo, Structure, Operand
675
676             int localScopeDepth = pc[5].u.operand;
677             instructions[i + 5].u.pointer = nullptr;
678
679             GetPutInfo getPutInfo = GetPutInfo(pc[4].u.operand);
680             ASSERT(!isInitialization(getPutInfo.initializationMode()));
681             if (getPutInfo.resolveType() == LocalClosureVar) {
682                 instructions[i + 4] = GetPutInfo(getPutInfo.resolveMode(), ClosureVar, getPutInfo.initializationMode()).operand();
683                 break;
684             }
685
686             const Identifier& ident = identifier(pc[3].u.operand);
687             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Get, getPutInfo.resolveType(), InitializationMode::NotInitialization);
688             RETURN_IF_EXCEPTION(throwScope, false);
689
690             instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), op.type, getPutInfo.initializationMode()).operand();
691             if (op.type == ModuleVar)
692                 instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), ClosureVar, getPutInfo.initializationMode()).operand();
693             if (op.type == GlobalVar || op.type == GlobalVarWithVarInjectionChecks || op.type == GlobalLexicalVar || op.type == GlobalLexicalVarWithVarInjectionChecks)
694                 instructions[i + 5].u.watchpointSet = op.watchpointSet;
695             else if (op.structure)
696                 instructions[i + 5].u.structure.set(vm, this, op.structure);
697             instructions[i + 6].u.pointer = reinterpret_cast<void*>(op.operand);
698             break;
699         }
700
701         case op_put_to_scope: {
702             // put_to_scope scope, id, value, GetPutInfo, Structure, Operand
703             GetPutInfo getPutInfo = GetPutInfo(pc[4].u.operand);
704             if (getPutInfo.resolveType() == LocalClosureVar) {
705                 // Only do watching if the property we're putting to is not anonymous.
706                 if (static_cast<unsigned>(pc[2].u.operand) != UINT_MAX) {
707                     int symbolTableIndex = pc[5].u.operand;
708                     SymbolTable* symbolTable = jsCast<SymbolTable*>(getConstant(symbolTableIndex));
709                     const Identifier& ident = identifier(pc[2].u.operand);
710                     ConcurrentJSLocker locker(symbolTable->m_lock);
711                     auto iter = symbolTable->find(locker, ident.impl());
712                     ASSERT(iter != symbolTable->end(locker));
713                     iter->value.prepareToWatch();
714                     instructions[i + 5].u.watchpointSet = iter->value.watchpointSet();
715                 } else
716                     instructions[i + 5].u.watchpointSet = nullptr;
717                 break;
718             }
719
720             const Identifier& ident = identifier(pc[2].u.operand);
721             int localScopeDepth = pc[5].u.operand;
722             instructions[i + 5].u.pointer = nullptr;
723             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Put, getPutInfo.resolveType(), getPutInfo.initializationMode());
724             RETURN_IF_EXCEPTION(throwScope, false);
725
726             instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), op.type, getPutInfo.initializationMode()).operand();
727             if (op.type == GlobalVar || op.type == GlobalVarWithVarInjectionChecks || op.type == GlobalLexicalVar || op.type == GlobalLexicalVarWithVarInjectionChecks)
728                 instructions[i + 5].u.watchpointSet = op.watchpointSet;
729             else if (op.type == ClosureVar || op.type == ClosureVarWithVarInjectionChecks) {
730                 if (op.watchpointSet)
731                     op.watchpointSet->invalidate(vm, PutToScopeFireDetail(this, ident));
732             } else if (op.structure)
733                 instructions[i + 5].u.structure.set(vm, this, op.structure);
734             instructions[i + 6].u.pointer = reinterpret_cast<void*>(op.operand);
735
736             break;
737         }
738
739         case op_profile_type: {
740             RELEASE_ASSERT(vm.typeProfiler());
741             // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType?
742             size_t instructionOffset = i + opLength - 1;
743             unsigned divotStart, divotEnd;
744             GlobalVariableID globalVariableID = 0;
745             RefPtr<TypeSet> globalTypeSet;
746             bool shouldAnalyze = m_unlinkedCode->typeProfilerExpressionInfoForBytecodeOffset(instructionOffset, divotStart, divotEnd);
747             VirtualRegister profileRegister(pc[1].u.operand);
748             ProfileTypeBytecodeFlag flag = static_cast<ProfileTypeBytecodeFlag>(pc[3].u.operand);
749             SymbolTable* symbolTable = nullptr;
750
751             switch (flag) {
752             case ProfileTypeBytecodeClosureVar: {
753                 const Identifier& ident = identifier(pc[4].u.operand);
754                 int localScopeDepth = pc[2].u.operand;
755                 ResolveType type = static_cast<ResolveType>(pc[5].u.operand);
756                 // Even though type profiling may be profiling either a Get or a Put, we can always claim a Get because
757                 // we're abstractly "read"ing from a JSScope.
758                 ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Get, type, InitializationMode::NotInitialization);
759                 RETURN_IF_EXCEPTION(throwScope, false);
760
761                 if (op.type == ClosureVar || op.type == ModuleVar)
762                     symbolTable = op.lexicalEnvironment->symbolTable();
763                 else if (op.type == GlobalVar)
764                     symbolTable = m_globalObject.get()->symbolTable();
765
766                 UniquedStringImpl* impl = (op.type == ModuleVar) ? op.importedName.get() : ident.impl();
767                 if (symbolTable) {
768                     ConcurrentJSLocker locker(symbolTable->m_lock);
769                     // If our parent scope was created while profiling was disabled, it will not have prepared for profiling yet.
770                     symbolTable->prepareForTypeProfiling(locker);
771                     globalVariableID = symbolTable->uniqueIDForVariable(locker, impl, vm);
772                     globalTypeSet = symbolTable->globalTypeSetForVariable(locker, impl, vm);
773                 } else
774                     globalVariableID = TypeProfilerNoGlobalIDExists;
775
776                 break;
777             }
778             case ProfileTypeBytecodeLocallyResolved: {
779                 int symbolTableIndex = pc[2].u.operand;
780                 SymbolTable* symbolTable = jsCast<SymbolTable*>(getConstant(symbolTableIndex));
781                 const Identifier& ident = identifier(pc[4].u.operand);
782                 ConcurrentJSLocker locker(symbolTable->m_lock);
783                 // If our parent scope was created while profiling was disabled, it will not have prepared for profiling yet.
784                 globalVariableID = symbolTable->uniqueIDForVariable(locker, ident.impl(), vm);
785                 globalTypeSet = symbolTable->globalTypeSetForVariable(locker, ident.impl(), vm);
786
787                 break;
788             }
789             case ProfileTypeBytecodeDoesNotHaveGlobalID: 
790             case ProfileTypeBytecodeFunctionArgument: {
791                 globalVariableID = TypeProfilerNoGlobalIDExists;
792                 break;
793             }
794             case ProfileTypeBytecodeFunctionReturnStatement: {
795                 RELEASE_ASSERT(ownerExecutable->isFunctionExecutable());
796                 globalTypeSet = jsCast<FunctionExecutable*>(ownerExecutable)->returnStatementTypeSet();
797                 globalVariableID = TypeProfilerReturnStatement;
798                 if (!shouldAnalyze) {
799                     // Because a return statement can be added implicitly to return undefined at the end of a function,
800                     // and these nodes don't emit expression ranges because they aren't in the actual source text of
801                     // the user's program, give the type profiler some range to identify these return statements.
802                     // Currently, the text offset that is used as identification is "f" in the function keyword
803                     // and is stored on TypeLocation's m_divotForFunctionOffsetIfReturnStatement member variable.
804                     divotStart = divotEnd = ownerExecutable->typeProfilingStartOffset();
805                     shouldAnalyze = true;
806                 }
807                 break;
808             }
809             }
810
811             std::pair<TypeLocation*, bool> locationPair = vm.typeProfiler()->typeLocationCache()->getTypeLocation(globalVariableID,
812                 ownerExecutable->sourceID(), divotStart, divotEnd, WTFMove(globalTypeSet), &vm);
813             TypeLocation* location = locationPair.first;
814             bool isNewLocation = locationPair.second;
815
816             if (flag == ProfileTypeBytecodeFunctionReturnStatement)
817                 location->m_divotForFunctionOffsetIfReturnStatement = ownerExecutable->typeProfilingStartOffset();
818
819             if (shouldAnalyze && isNewLocation)
820                 vm.typeProfiler()->insertNewLocation(location);
821
822             instructions[i + 2].u.location = location;
823             break;
824         }
825
826         case op_debug: {
827             if (pc[1].u.unsignedValue == DidReachBreakpoint)
828                 m_hasDebuggerStatement = true;
829             break;
830         }
831
832         case op_create_rest: {
833             int numberOfArgumentsToSkip = instructions[i + 3].u.operand;
834             ASSERT_UNUSED(numberOfArgumentsToSkip, numberOfArgumentsToSkip >= 0);
835             // This is used when rematerializing the rest parameter during OSR exit in the FTL JIT.");
836             m_numberOfArgumentsToSkip = numberOfArgumentsToSkip;
837             break;
838         }
839         
840         default:
841             break;
842         }
843
844         i += opLength;
845     }
846
847     if (vm.controlFlowProfiler())
848         insertBasicBlockBoundariesForControlFlowProfiler(instructions);
849
850     m_instructions = WTFMove(instructions);
851
852     // Set optimization thresholds only after m_instructions is initialized, since these
853     // rely on the instruction count (and are in theory permitted to also inspect the
854     // instruction stream to more accurate assess the cost of tier-up).
855     optimizeAfterWarmUp();
856     jitAfterWarmUp();
857
858     // If the concurrent thread will want the code block's hash, then compute it here
859     // synchronously.
860     if (Options::alwaysComputeHash())
861         hash();
862
863     if (Options::dumpGeneratedBytecodes())
864         dumpBytecode();
865
866     heap()->reportExtraMemoryAllocated(m_instructions.size() * sizeof(Instruction));
867
868     return true;
869 }
870
871 void CodeBlock::finishCreationCommon(VM& vm)
872 {
873     m_ownerEdge.set(vm, this, ExecutableToCodeBlockEdge::create(vm, this));
874 }
875
876 CodeBlock::~CodeBlock()
877 {
878     VM& vm = *m_poisonedVM;
879
880     vm.heap.codeBlockSet().remove(this);
881     
882     if (UNLIKELY(vm.m_perBytecodeProfiler))
883         vm.m_perBytecodeProfiler->notifyDestruction(this);
884
885     if (!vm.heap.isShuttingDown() && unlinkedCodeBlock()->didOptimize() == MixedTriState)
886         unlinkedCodeBlock()->setDidOptimize(FalseTriState);
887
888 #if ENABLE(VERBOSE_VALUE_PROFILE)
889     dumpValueProfiles();
890 #endif
891
892     // We may be destroyed before any CodeBlocks that refer to us are destroyed.
893     // Consider that two CodeBlocks become unreachable at the same time. There
894     // is no guarantee about the order in which the CodeBlocks are destroyed.
895     // So, if we don't remove incoming calls, and get destroyed before the
896     // CodeBlock(s) that have calls into us, then the CallLinkInfo vector's
897     // destructor will try to remove nodes from our (no longer valid) linked list.
898     unlinkIncomingCalls();
899     
900     // Note that our outgoing calls will be removed from other CodeBlocks'
901     // m_incomingCalls linked lists through the execution of the ~CallLinkInfo
902     // destructors.
903
904 #if ENABLE(JIT)
905     for (auto iter = m_stubInfos.begin(); !!iter; ++iter) {
906         StructureStubInfo* stub = *iter;
907         stub->aboutToDie();
908         stub->deref();
909     }
910 #endif // ENABLE(JIT)
911 }
912
913 void CodeBlock::setConstantIdentifierSetRegisters(VM& vm, const Vector<ConstantIndentifierSetEntry>& constants)
914 {
915     auto scope = DECLARE_THROW_SCOPE(vm);
916     JSGlobalObject* globalObject = m_globalObject.get();
917     ExecState* exec = globalObject->globalExec();
918
919     for (const auto& entry : constants) {
920         const IdentifierSet& set = entry.first;
921
922         Structure* setStructure = globalObject->setStructure();
923         RETURN_IF_EXCEPTION(scope, void());
924         JSSet* jsSet = JSSet::create(exec, vm, setStructure, set.size());
925         RETURN_IF_EXCEPTION(scope, void());
926
927         for (auto setEntry : set) {
928             JSString* jsString = jsOwnedString(&vm, setEntry.get()); 
929             jsSet->add(exec, jsString);
930             RETURN_IF_EXCEPTION(scope, void());
931         }
932         m_constantRegisters[entry.second].set(vm, this, jsSet);
933     }
934 }
935
936 void CodeBlock::setConstantRegisters(const Vector<WriteBarrier<Unknown>>& constants, const Vector<SourceCodeRepresentation>& constantsSourceCodeRepresentation)
937 {
938     VM& vm = *m_poisonedVM;
939     auto scope = DECLARE_THROW_SCOPE(vm);
940     JSGlobalObject* globalObject = m_globalObject.get();
941     ExecState* exec = globalObject->globalExec();
942
943     ASSERT(constants.size() == constantsSourceCodeRepresentation.size());
944     size_t count = constants.size();
945     m_constantRegisters.resizeToFit(count);
946     bool hasTypeProfiler = !!vm.typeProfiler();
947     for (size_t i = 0; i < count; i++) {
948         JSValue constant = constants[i].get();
949
950         if (!constant.isEmpty()) {
951             if (constant.isCell()) {
952                 JSCell* cell = constant.asCell();
953                 if (SymbolTable* symbolTable = jsDynamicCast<SymbolTable*>(vm, cell)) {
954                     if (hasTypeProfiler) {
955                         ConcurrentJSLocker locker(symbolTable->m_lock);
956                         symbolTable->prepareForTypeProfiling(locker);
957                     }
958
959                     SymbolTable* clone = symbolTable->cloneScopePart(vm);
960                     if (wasCompiledWithDebuggingOpcodes())
961                         clone->setRareDataCodeBlock(this);
962
963                     constant = clone;
964                 } else if (auto* descriptor = jsDynamicCast<JSTemplateObjectDescriptor*>(vm, cell)) {
965                     auto* templateObject = descriptor->createTemplateObject(exec);
966                     RETURN_IF_EXCEPTION(scope, void());
967                     constant = templateObject;
968                 }
969             }
970         }
971
972         m_constantRegisters[i].set(vm, this, constant);
973     }
974
975     m_constantsSourceCodeRepresentation = constantsSourceCodeRepresentation;
976 }
977
978 void CodeBlock::setAlternative(VM& vm, CodeBlock* alternative)
979 {
980     m_alternative.set(vm, this, alternative);
981 }
982
983 void CodeBlock::setNumParameters(int newValue)
984 {
985     m_numParameters = newValue;
986
987     m_argumentValueProfiles = RefCountedArray<ValueProfile>(vm()->canUseJIT() ? newValue : 0);
988 }
989
990 CodeBlock* CodeBlock::specialOSREntryBlockOrNull()
991 {
992 #if ENABLE(FTL_JIT)
993     if (jitType() != JITCode::DFGJIT)
994         return 0;
995     DFG::JITCode* jitCode = m_jitCode->dfg();
996     return jitCode->osrEntryBlock();
997 #else // ENABLE(FTL_JIT)
998     return 0;
999 #endif // ENABLE(FTL_JIT)
1000 }
1001
1002 size_t CodeBlock::estimatedSize(JSCell* cell, VM& vm)
1003 {
1004     CodeBlock* thisObject = jsCast<CodeBlock*>(cell);
1005     size_t extraMemoryAllocated = thisObject->m_instructions.size() * sizeof(Instruction);
1006     if (thisObject->m_jitCode)
1007         extraMemoryAllocated += thisObject->m_jitCode->size();
1008     return Base::estimatedSize(cell, vm) + extraMemoryAllocated;
1009 }
1010
1011 void CodeBlock::visitChildren(JSCell* cell, SlotVisitor& visitor)
1012 {
1013     CodeBlock* thisObject = jsCast<CodeBlock*>(cell);
1014     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
1015     Base::visitChildren(cell, visitor);
1016     visitor.append(thisObject->m_ownerEdge);
1017     thisObject->visitChildren(visitor);
1018 }
1019
1020 void CodeBlock::visitChildren(SlotVisitor& visitor)
1021 {
1022     ConcurrentJSLocker locker(m_lock);
1023     if (CodeBlock* otherBlock = specialOSREntryBlockOrNull())
1024         visitor.appendUnbarriered(otherBlock);
1025
1026     if (m_jitCode)
1027         visitor.reportExtraMemoryVisited(m_jitCode->size());
1028     if (m_instructions.size()) {
1029         unsigned refCount = m_instructions.refCount();
1030         if (!refCount) {
1031             dataLog("CodeBlock: ", RawPointer(this), "\n");
1032             dataLog("m_instructions.data(): ", RawPointer(m_instructions.data()), "\n");
1033             dataLog("refCount: ", refCount, "\n");
1034             RELEASE_ASSERT_NOT_REACHED();
1035         }
1036         visitor.reportExtraMemoryVisited(m_instructions.size() * sizeof(Instruction) / refCount);
1037     }
1038
1039     stronglyVisitStrongReferences(locker, visitor);
1040     stronglyVisitWeakReferences(locker, visitor);
1041     
1042     VM::SpaceAndFinalizerSet::finalizerSetFor(*subspace()).add(this);
1043 }
1044
1045 bool CodeBlock::shouldVisitStrongly(const ConcurrentJSLocker& locker)
1046 {
1047     if (Options::forceCodeBlockLiveness())
1048         return true;
1049
1050     if (shouldJettisonDueToOldAge(locker))
1051         return false;
1052
1053     // Interpreter and Baseline JIT CodeBlocks don't need to be jettisoned when
1054     // their weak references go stale. So if a basline JIT CodeBlock gets
1055     // scanned, we can assume that this means that it's live.
1056     if (!JITCode::isOptimizingJIT(jitType()))
1057         return true;
1058
1059     return false;
1060 }
1061
1062 bool CodeBlock::shouldJettisonDueToWeakReference()
1063 {
1064     if (!JITCode::isOptimizingJIT(jitType()))
1065         return false;
1066     return !Heap::isMarked(this);
1067 }
1068
1069 static Seconds timeToLive(JITCode::JITType jitType)
1070 {
1071     if (UNLIKELY(Options::useEagerCodeBlockJettisonTiming())) {
1072         switch (jitType) {
1073         case JITCode::InterpreterThunk:
1074             return 10_ms;
1075         case JITCode::BaselineJIT:
1076             return 30_ms;
1077         case JITCode::DFGJIT:
1078             return 40_ms;
1079         case JITCode::FTLJIT:
1080             return 120_ms;
1081         default:
1082             return Seconds::infinity();
1083         }
1084     }
1085
1086     switch (jitType) {
1087     case JITCode::InterpreterThunk:
1088         return 5_s;
1089     case JITCode::BaselineJIT:
1090         // Effectively 10 additional seconds, since BaselineJIT and
1091         // InterpreterThunk share a CodeBlock.
1092         return 15_s;
1093     case JITCode::DFGJIT:
1094         return 20_s;
1095     case JITCode::FTLJIT:
1096         return 60_s;
1097     default:
1098         return Seconds::infinity();
1099     }
1100 }
1101
1102 bool CodeBlock::shouldJettisonDueToOldAge(const ConcurrentJSLocker&)
1103 {
1104     if (Heap::isMarked(this))
1105         return false;
1106
1107     if (UNLIKELY(Options::forceCodeBlockToJettisonDueToOldAge()))
1108         return true;
1109     
1110     if (timeSinceCreation() < timeToLive(jitType()))
1111         return false;
1112     
1113     return true;
1114 }
1115
1116 #if ENABLE(DFG_JIT)
1117 static bool shouldMarkTransition(DFG::WeakReferenceTransition& transition)
1118 {
1119     if (transition.m_codeOrigin && !Heap::isMarked(transition.m_codeOrigin.get()))
1120         return false;
1121     
1122     if (!Heap::isMarked(transition.m_from.get()))
1123         return false;
1124     
1125     return true;
1126 }
1127 #endif // ENABLE(DFG_JIT)
1128
1129 void CodeBlock::propagateTransitions(const ConcurrentJSLocker&, SlotVisitor& visitor)
1130 {
1131     UNUSED_PARAM(visitor);
1132
1133     VM& vm = *m_poisonedVM;
1134
1135     if (jitType() == JITCode::InterpreterThunk) {
1136         const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
1137         for (size_t i = 0; i < propertyAccessInstructions.size(); ++i) {
1138             Instruction* instruction = &instructions()[propertyAccessInstructions[i]];
1139             switch (Interpreter::getOpcodeID(instruction[0])) {
1140             case op_put_by_id: {
1141                 StructureID oldStructureID = instruction[4].u.structureID;
1142                 StructureID newStructureID = instruction[6].u.structureID;
1143                 if (!oldStructureID || !newStructureID)
1144                     break;
1145                 Structure* oldStructure =
1146                     vm.heap.structureIDTable().get(oldStructureID);
1147                 Structure* newStructure =
1148                     vm.heap.structureIDTable().get(newStructureID);
1149                 if (Heap::isMarked(oldStructure))
1150                     visitor.appendUnbarriered(newStructure);
1151                 break;
1152             }
1153             default:
1154                 break;
1155             }
1156         }
1157     }
1158
1159 #if ENABLE(JIT)
1160     if (JITCode::isJIT(jitType())) {
1161         for (auto iter = m_stubInfos.begin(); !!iter; ++iter)
1162             (*iter)->propagateTransitions(visitor);
1163     }
1164 #endif // ENABLE(JIT)
1165     
1166 #if ENABLE(DFG_JIT)
1167     if (JITCode::isOptimizingJIT(jitType())) {
1168         DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
1169         for (auto& weakReference : dfgCommon->weakStructureReferences)
1170             weakReference->markIfCheap(visitor);
1171
1172         for (auto& transition : dfgCommon->transitions) {
1173             if (shouldMarkTransition(transition)) {
1174                 // If the following three things are live, then the target of the
1175                 // transition is also live:
1176                 //
1177                 // - This code block. We know it's live already because otherwise
1178                 //   we wouldn't be scanning ourselves.
1179                 //
1180                 // - The code origin of the transition. Transitions may arise from
1181                 //   code that was inlined. They are not relevant if the user's
1182                 //   object that is required for the inlinee to run is no longer
1183                 //   live.
1184                 //
1185                 // - The source of the transition. The transition checks if some
1186                 //   heap location holds the source, and if so, stores the target.
1187                 //   Hence the source must be live for the transition to be live.
1188                 //
1189                 // We also short-circuit the liveness if the structure is harmless
1190                 // to mark (i.e. its global object and prototype are both already
1191                 // live).
1192
1193                 visitor.append(transition.m_to);
1194             }
1195         }
1196     }
1197 #endif // ENABLE(DFG_JIT)
1198 }
1199
1200 void CodeBlock::determineLiveness(const ConcurrentJSLocker&, SlotVisitor& visitor)
1201 {
1202     UNUSED_PARAM(visitor);
1203     
1204 #if ENABLE(DFG_JIT)
1205     if (Heap::isMarked(this))
1206         return;
1207     
1208     // In rare and weird cases, this could be called on a baseline CodeBlock. One that I found was
1209     // that we might decide that the CodeBlock should be jettisoned due to old age, so the
1210     // isMarked check doesn't protect us.
1211     if (!JITCode::isOptimizingJIT(jitType()))
1212         return;
1213     
1214     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
1215     // Now check all of our weak references. If all of them are live, then we
1216     // have proved liveness and so we scan our strong references. If at end of
1217     // GC we still have not proved liveness, then this code block is toast.
1218     bool allAreLiveSoFar = true;
1219     for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
1220         JSCell* reference = dfgCommon->weakReferences[i].get();
1221         ASSERT(!jsDynamicCast<CodeBlock*>(*reference->vm(), reference));
1222         if (!Heap::isMarked(reference)) {
1223             allAreLiveSoFar = false;
1224             break;
1225         }
1226     }
1227     if (allAreLiveSoFar) {
1228         for (unsigned i = 0; i < dfgCommon->weakStructureReferences.size(); ++i) {
1229             if (!Heap::isMarked(dfgCommon->weakStructureReferences[i].get())) {
1230                 allAreLiveSoFar = false;
1231                 break;
1232             }
1233         }
1234     }
1235     
1236     // If some weak references are dead, then this fixpoint iteration was
1237     // unsuccessful.
1238     if (!allAreLiveSoFar)
1239         return;
1240     
1241     // All weak references are live. Record this information so we don't
1242     // come back here again, and scan the strong references.
1243     visitor.appendUnbarriered(this);
1244 #endif // ENABLE(DFG_JIT)
1245 }
1246
1247 void CodeBlock::clearLLIntGetByIdCache(Instruction* instruction)
1248 {
1249     instruction[0].u.opcode = LLInt::getOpcode(op_get_by_id);
1250     instruction[4].u.pointer = nullptr;
1251     instruction[5].u.pointer = nullptr;
1252     instruction[6].u.pointer = nullptr;
1253 }
1254
1255 void CodeBlock::finalizeLLIntInlineCaches()
1256 {
1257     VM& vm = *m_poisonedVM;
1258     const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
1259     for (size_t size = propertyAccessInstructions.size(), i = 0; i < size; ++i) {
1260         Instruction* curInstruction = &instructions()[propertyAccessInstructions[i]];
1261         switch (Interpreter::getOpcodeID(curInstruction[0])) {
1262         case op_get_by_id: {
1263             StructureID oldStructureID = curInstruction[4].u.structureID;
1264             if (!oldStructureID || Heap::isMarked(vm.heap.structureIDTable().get(oldStructureID)))
1265                 break;
1266             if (Options::verboseOSR())
1267                 dataLogF("Clearing LLInt property access.\n");
1268             clearLLIntGetByIdCache(curInstruction);
1269             break;
1270         }
1271         case op_get_by_id_direct: {
1272             StructureID oldStructureID = curInstruction[4].u.structureID;
1273             if (!oldStructureID || Heap::isMarked(vm.heap.structureIDTable().get(oldStructureID)))
1274                 break;
1275             if (Options::verboseOSR())
1276                 dataLogF("Clearing LLInt property access.\n");
1277             curInstruction[4].u.pointer = nullptr;
1278             curInstruction[5].u.pointer = nullptr;
1279             break;
1280         }
1281         case op_put_by_id: {
1282             StructureID oldStructureID = curInstruction[4].u.structureID;
1283             StructureID newStructureID = curInstruction[6].u.structureID;
1284             StructureChain* chain = curInstruction[7].u.structureChain.get();
1285             if ((!oldStructureID || Heap::isMarked(vm.heap.structureIDTable().get(oldStructureID)))
1286                 && (!newStructureID || Heap::isMarked(vm.heap.structureIDTable().get(newStructureID)))
1287                 && (!chain || Heap::isMarked(chain)))
1288                 break;
1289             if (Options::verboseOSR())
1290                 dataLogF("Clearing LLInt put transition.\n");
1291             curInstruction[4].u.structureID = 0;
1292             curInstruction[5].u.operand = 0;
1293             curInstruction[6].u.structureID = 0;
1294             curInstruction[7].u.structureChain.clear();
1295             break;
1296         }
1297         // FIXME: https://bugs.webkit.org/show_bug.cgi?id=166418
1298         // We need to add optimizations for op_resolve_scope_for_hoisting_func_decl_in_eval to do link time scope resolution.
1299         case op_resolve_scope_for_hoisting_func_decl_in_eval:
1300             break;
1301         case op_get_by_id_proto_load:
1302         case op_get_by_id_unset:
1303         case op_get_array_length:
1304             break;
1305         case op_to_this:
1306             if (!curInstruction[2].u.structure || Heap::isMarked(curInstruction[2].u.structure.get()))
1307                 break;
1308             if (Options::verboseOSR())
1309                 dataLogF("Clearing LLInt to_this with structure %p.\n", curInstruction[2].u.structure.get());
1310             curInstruction[2].u.structure.clear();
1311             curInstruction[3].u.toThisStatus = merge(
1312                 curInstruction[3].u.toThisStatus, ToThisClearedByGC);
1313             break;
1314         case op_create_this: {
1315             auto& cacheWriteBarrier = curInstruction[4].u.jsCell;
1316             if (!cacheWriteBarrier || cacheWriteBarrier.unvalidatedGet() == JSCell::seenMultipleCalleeObjects())
1317                 break;
1318             JSCell* cachedFunction = cacheWriteBarrier.get();
1319             if (Heap::isMarked(cachedFunction))
1320                 break;
1321             if (Options::verboseOSR())
1322                 dataLogF("Clearing LLInt create_this with cached callee %p.\n", cachedFunction);
1323             cacheWriteBarrier.clear();
1324             break;
1325         }
1326         case op_resolve_scope: {
1327             // Right now this isn't strictly necessary. Any symbol tables that this will refer to
1328             // are for outer functions, and we refer to those functions strongly, and they refer
1329             // to the symbol table strongly. But it's nice to be on the safe side.
1330             WriteBarrierBase<SymbolTable>& symbolTable = curInstruction[6].u.symbolTable;
1331             if (!symbolTable || Heap::isMarked(symbolTable.get()))
1332                 break;
1333             if (Options::verboseOSR())
1334                 dataLogF("Clearing dead symbolTable %p.\n", symbolTable.get());
1335             symbolTable.clear();
1336             break;
1337         }
1338         case op_get_from_scope:
1339         case op_put_to_scope: {
1340             GetPutInfo getPutInfo = GetPutInfo(curInstruction[4].u.operand);
1341             if (getPutInfo.resolveType() == GlobalVar || getPutInfo.resolveType() == GlobalVarWithVarInjectionChecks 
1342                 || getPutInfo.resolveType() == LocalClosureVar || getPutInfo.resolveType() == GlobalLexicalVar || getPutInfo.resolveType() == GlobalLexicalVarWithVarInjectionChecks)
1343                 continue;
1344             WriteBarrierBase<Structure>& structure = curInstruction[5].u.structure;
1345             if (!structure || Heap::isMarked(structure.get()))
1346                 break;
1347             if (Options::verboseOSR())
1348                 dataLogF("Clearing scope access with structure %p.\n", structure.get());
1349             structure.clear();
1350             break;
1351         }
1352         default:
1353             OpcodeID opcodeID = Interpreter::getOpcodeID(curInstruction[0]);
1354             ASSERT_WITH_MESSAGE_UNUSED(opcodeID, false, "Unhandled opcode in CodeBlock::finalizeUnconditionally, %s(%d) at bc %u", opcodeNames[opcodeID], opcodeID, propertyAccessInstructions[i]);
1355         }
1356     }
1357
1358     // We can't just remove all the sets when we clear the caches since we might have created a watchpoint set
1359     // then cleared the cache without GCing in between.
1360     m_llintGetByIdWatchpointMap.removeIf([&] (const StructureWatchpointMap::KeyValuePairType& pair) -> bool {
1361         auto clear = [&] () {
1362             Instruction* instruction = std::get<1>(pair.key);
1363             OpcodeID opcode = Interpreter::getOpcodeID(*instruction);
1364             if (opcode == op_get_by_id_proto_load || opcode == op_get_by_id_unset) {
1365                 if (Options::verboseOSR())
1366                     dataLogF("Clearing LLInt property access.\n");
1367                 clearLLIntGetByIdCache(instruction);
1368             }
1369             return true;
1370         };
1371
1372         if (!Heap::isMarked(std::get<0>(pair.key)))
1373             return clear();
1374
1375         for (const LLIntPrototypeLoadAdaptiveStructureWatchpoint* watchpoint : pair.value) {
1376             if (!watchpoint->key().isStillLive())
1377                 return clear();
1378         }
1379
1380         return false;
1381     });
1382
1383     for (unsigned i = 0; i < m_llintCallLinkInfos.size(); ++i) {
1384         if (m_llintCallLinkInfos[i].isLinked() && !Heap::isMarked(m_llintCallLinkInfos[i].callee.get())) {
1385             if (Options::verboseOSR())
1386                 dataLog("Clearing LLInt call from ", *this, "\n");
1387             m_llintCallLinkInfos[i].unlink();
1388         }
1389         if (!!m_llintCallLinkInfos[i].lastSeenCallee && !Heap::isMarked(m_llintCallLinkInfos[i].lastSeenCallee.get()))
1390             m_llintCallLinkInfos[i].lastSeenCallee.clear();
1391     }
1392 }
1393
1394 void CodeBlock::finalizeBaselineJITInlineCaches()
1395 {
1396 #if ENABLE(JIT)
1397     for (auto iter = callLinkInfosBegin(); !!iter; ++iter)
1398         (*iter)->visitWeak(*vm());
1399
1400     for (auto iter = m_stubInfos.begin(); !!iter; ++iter) {
1401         StructureStubInfo& stubInfo = **iter;
1402         stubInfo.visitWeakReferences(this);
1403     }
1404 #endif
1405 }
1406
1407 void CodeBlock::finalizeUnconditionally(VM&)
1408 {
1409     updateAllPredictions();
1410     
1411     if (JITCode::couldBeInterpreted(jitType()))
1412         finalizeLLIntInlineCaches();
1413
1414 #if ENABLE(JIT)
1415     if (!!jitCode())
1416         finalizeBaselineJITInlineCaches();
1417 #endif
1418
1419     VM::SpaceAndFinalizerSet::finalizerSetFor(*subspace()).remove(this);
1420 }
1421
1422 void CodeBlock::getStubInfoMap(const ConcurrentJSLocker&, StubInfoMap& result)
1423 {
1424 #if ENABLE(JIT)
1425     if (JITCode::isJIT(jitType()))
1426         toHashMap(m_stubInfos, getStructureStubInfoCodeOrigin, result);
1427 #else
1428     UNUSED_PARAM(result);
1429 #endif
1430 }
1431
1432 void CodeBlock::getStubInfoMap(StubInfoMap& result)
1433 {
1434     ConcurrentJSLocker locker(m_lock);
1435     getStubInfoMap(locker, result);
1436 }
1437
1438 void CodeBlock::getCallLinkInfoMap(const ConcurrentJSLocker&, CallLinkInfoMap& result)
1439 {
1440 #if ENABLE(JIT)
1441     if (JITCode::isJIT(jitType()))
1442         toHashMap(m_callLinkInfos, getCallLinkInfoCodeOrigin, result);
1443 #else
1444     UNUSED_PARAM(result);
1445 #endif
1446 }
1447
1448 void CodeBlock::getCallLinkInfoMap(CallLinkInfoMap& result)
1449 {
1450     ConcurrentJSLocker locker(m_lock);
1451     getCallLinkInfoMap(locker, result);
1452 }
1453
1454 void CodeBlock::getByValInfoMap(const ConcurrentJSLocker&, ByValInfoMap& result)
1455 {
1456 #if ENABLE(JIT)
1457     if (JITCode::isJIT(jitType())) {
1458         for (auto* byValInfo : m_byValInfos)
1459             result.add(CodeOrigin(byValInfo->bytecodeIndex), byValInfo);
1460     }
1461 #else
1462     UNUSED_PARAM(result);
1463 #endif
1464 }
1465
1466 void CodeBlock::getByValInfoMap(ByValInfoMap& result)
1467 {
1468     ConcurrentJSLocker locker(m_lock);
1469     getByValInfoMap(locker, result);
1470 }
1471
1472 #if ENABLE(JIT)
1473 StructureStubInfo* CodeBlock::addStubInfo(AccessType accessType)
1474 {
1475     ConcurrentJSLocker locker(m_lock);
1476     return m_stubInfos.add(accessType);
1477 }
1478
1479 JITAddIC* CodeBlock::addJITAddIC(ArithProfile* arithProfile, Instruction* instruction)
1480 {
1481     return m_addICs.add(arithProfile, instruction);
1482 }
1483
1484 JITMulIC* CodeBlock::addJITMulIC(ArithProfile* arithProfile, Instruction* instruction)
1485 {
1486     return m_mulICs.add(arithProfile, instruction);
1487 }
1488
1489 JITSubIC* CodeBlock::addJITSubIC(ArithProfile* arithProfile, Instruction* instruction)
1490 {
1491     return m_subICs.add(arithProfile, instruction);
1492 }
1493
1494 JITNegIC* CodeBlock::addJITNegIC(ArithProfile* arithProfile, Instruction* instruction)
1495 {
1496     return m_negICs.add(arithProfile, instruction);
1497 }
1498
1499 StructureStubInfo* CodeBlock::findStubInfo(CodeOrigin codeOrigin)
1500 {
1501     for (StructureStubInfo* stubInfo : m_stubInfos) {
1502         if (stubInfo->codeOrigin == codeOrigin)
1503             return stubInfo;
1504     }
1505     return nullptr;
1506 }
1507
1508 ByValInfo* CodeBlock::addByValInfo()
1509 {
1510     ConcurrentJSLocker locker(m_lock);
1511     return m_byValInfos.add();
1512 }
1513
1514 CallLinkInfo* CodeBlock::addCallLinkInfo()
1515 {
1516     ConcurrentJSLocker locker(m_lock);
1517     return m_callLinkInfos.add();
1518 }
1519
1520 CallLinkInfo* CodeBlock::getCallLinkInfoForBytecodeIndex(unsigned index)
1521 {
1522     for (auto iter = m_callLinkInfos.begin(); !!iter; ++iter) {
1523         if ((*iter)->codeOrigin() == CodeOrigin(index))
1524             return *iter;
1525     }
1526     return nullptr;
1527 }
1528
1529 void CodeBlock::resetJITData()
1530 {
1531     RELEASE_ASSERT(!JITCode::isJIT(jitType()));
1532     ConcurrentJSLocker locker(m_lock);
1533     
1534     // We can clear these because no other thread will have references to any stub infos, call
1535     // link infos, or by val infos if we don't have JIT code. Attempts to query these data
1536     // structures using the concurrent API (getStubInfoMap and friends) will return nothing if we
1537     // don't have JIT code.
1538     m_stubInfos.clear();
1539     m_callLinkInfos.clear();
1540     m_byValInfos.clear();
1541     
1542     // We can clear this because the DFG's queries to these data structures are guarded by whether
1543     // there is JIT code.
1544     m_rareCaseProfiles.clear();
1545 }
1546 #endif
1547
1548 void CodeBlock::visitOSRExitTargets(const ConcurrentJSLocker&, SlotVisitor& visitor)
1549 {
1550     // We strongly visit OSR exits targets because we don't want to deal with
1551     // the complexity of generating an exit target CodeBlock on demand and
1552     // guaranteeing that it matches the details of the CodeBlock we compiled
1553     // the OSR exit against.
1554
1555     visitor.append(m_alternative);
1556
1557 #if ENABLE(DFG_JIT)
1558     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
1559     if (dfgCommon->inlineCallFrames) {
1560         for (auto* inlineCallFrame : *dfgCommon->inlineCallFrames) {
1561             ASSERT(inlineCallFrame->baselineCodeBlock);
1562             visitor.append(inlineCallFrame->baselineCodeBlock);
1563         }
1564     }
1565 #endif
1566 }
1567
1568 void CodeBlock::stronglyVisitStrongReferences(const ConcurrentJSLocker& locker, SlotVisitor& visitor)
1569 {
1570     UNUSED_PARAM(locker);
1571     
1572     visitor.append(m_globalObject);
1573     visitor.append(m_ownerExecutable); // This is extra important since it causes the ExecutableToCodeBlockEdge to be marked.
1574     visitor.append(m_unlinkedCode);
1575     if (m_rareData)
1576         m_rareData->m_directEvalCodeCache.visitAggregate(visitor);
1577     visitor.appendValues(m_constantRegisters.data(), m_constantRegisters.size());
1578     for (auto& functionExpr : m_functionExprs)
1579         visitor.append(functionExpr);
1580     for (auto& functionDecl : m_functionDecls)
1581         visitor.append(functionDecl);
1582     for (auto& objectAllocationProfile : m_objectAllocationProfiles)
1583         objectAllocationProfile.visitAggregate(visitor);
1584
1585 #if ENABLE(JIT)
1586     for (ByValInfo* byValInfo : m_byValInfos)
1587         visitor.append(byValInfo->cachedSymbol);
1588 #endif
1589
1590 #if ENABLE(DFG_JIT)
1591     if (JITCode::isOptimizingJIT(jitType()))
1592         visitOSRExitTargets(locker, visitor);
1593 #endif
1594 }
1595
1596 void CodeBlock::stronglyVisitWeakReferences(const ConcurrentJSLocker&, SlotVisitor& visitor)
1597 {
1598     UNUSED_PARAM(visitor);
1599
1600 #if ENABLE(DFG_JIT)
1601     if (!JITCode::isOptimizingJIT(jitType()))
1602         return;
1603     
1604     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
1605
1606     for (auto& transition : dfgCommon->transitions) {
1607         if (!!transition.m_codeOrigin)
1608             visitor.append(transition.m_codeOrigin); // Almost certainly not necessary, since the code origin should also be a weak reference. Better to be safe, though.
1609         visitor.append(transition.m_from);
1610         visitor.append(transition.m_to);
1611     }
1612
1613     for (auto& weakReference : dfgCommon->weakReferences)
1614         visitor.append(weakReference);
1615
1616     for (auto& weakStructureReference : dfgCommon->weakStructureReferences)
1617         visitor.append(weakStructureReference);
1618
1619     dfgCommon->livenessHasBeenProved = true;
1620 #endif    
1621 }
1622
1623 CodeBlock* CodeBlock::baselineAlternative()
1624 {
1625 #if ENABLE(JIT)
1626     CodeBlock* result = this;
1627     while (result->alternative())
1628         result = result->alternative();
1629     RELEASE_ASSERT(result);
1630     RELEASE_ASSERT(JITCode::isBaselineCode(result->jitType()) || result->jitType() == JITCode::None);
1631     return result;
1632 #else
1633     return this;
1634 #endif
1635 }
1636
1637 CodeBlock* CodeBlock::baselineVersion()
1638 {
1639 #if ENABLE(JIT)
1640     if (JITCode::isBaselineCode(jitType()))
1641         return this;
1642     CodeBlock* result = replacement();
1643     if (!result) {
1644         // This can happen if we're creating the original CodeBlock for an executable.
1645         // Assume that we're the baseline CodeBlock.
1646         RELEASE_ASSERT(jitType() == JITCode::None);
1647         return this;
1648     }
1649     result = result->baselineAlternative();
1650     return result;
1651 #else
1652     return this;
1653 #endif
1654 }
1655
1656 #if ENABLE(JIT)
1657 bool CodeBlock::hasOptimizedReplacement(JITCode::JITType typeToReplace)
1658 {
1659     CodeBlock* replacement = this->replacement();
1660     return replacement && JITCode::isHigherTier(replacement->jitType(), typeToReplace);
1661 }
1662
1663 bool CodeBlock::hasOptimizedReplacement()
1664 {
1665     return hasOptimizedReplacement(jitType());
1666 }
1667 #endif
1668
1669 HandlerInfo* CodeBlock::handlerForBytecodeOffset(unsigned bytecodeOffset, RequiredHandler requiredHandler)
1670 {
1671     RELEASE_ASSERT(bytecodeOffset < instructions().size());
1672     return handlerForIndex(bytecodeOffset, requiredHandler);
1673 }
1674
1675 HandlerInfo* CodeBlock::handlerForIndex(unsigned index, RequiredHandler requiredHandler)
1676 {
1677     if (!m_rareData)
1678         return 0;
1679     return HandlerInfo::handlerForIndex(m_rareData->m_exceptionHandlers, index, requiredHandler);
1680 }
1681
1682 CallSiteIndex CodeBlock::newExceptionHandlingCallSiteIndex(CallSiteIndex originalCallSite)
1683 {
1684 #if ENABLE(DFG_JIT)
1685     RELEASE_ASSERT(JITCode::isOptimizingJIT(jitType()));
1686     RELEASE_ASSERT(canGetCodeOrigin(originalCallSite));
1687     ASSERT(!!handlerForIndex(originalCallSite.bits()));
1688     CodeOrigin originalOrigin = codeOrigin(originalCallSite);
1689     return m_jitCode->dfgCommon()->addUniqueCallSiteIndex(originalOrigin);
1690 #else
1691     // We never create new on-the-fly exception handling
1692     // call sites outside the DFG/FTL inline caches.
1693     UNUSED_PARAM(originalCallSite);
1694     RELEASE_ASSERT_NOT_REACHED();
1695     return CallSiteIndex(0u);
1696 #endif
1697 }
1698
1699 void CodeBlock::ensureCatchLivenessIsComputedForBytecodeOffsetSlow(unsigned bytecodeOffset)
1700 {
1701     ASSERT(Interpreter::getOpcodeID(m_instructions[bytecodeOffset]) == op_catch);
1702     BytecodeLivenessAnalysis& bytecodeLiveness = livenessAnalysis();
1703
1704     // We get the live-out set of variables at op_catch, not the live-in. This
1705     // is because the variables that the op_catch defines might be dead, and
1706     // we can avoid profiling them and extracting them when doing OSR entry
1707     // into the DFG.
1708     FastBitVector liveLocals = bytecodeLiveness.getLivenessInfoAtBytecodeOffset(this, bytecodeOffset + OPCODE_LENGTH(op_catch));
1709     Vector<VirtualRegister> liveOperands;
1710     liveOperands.reserveInitialCapacity(liveLocals.bitCount());
1711     liveLocals.forEachSetBit([&] (unsigned liveLocal) {
1712         liveOperands.append(virtualRegisterForLocal(liveLocal));
1713     });
1714
1715     for (int i = 0; i < numParameters(); ++i)
1716         liveOperands.append(virtualRegisterForArgument(i));
1717
1718     auto profiles = std::make_unique<ValueProfileAndOperandBuffer>(liveOperands.size());
1719     RELEASE_ASSERT(profiles->m_size == liveOperands.size());
1720     for (unsigned i = 0; i < profiles->m_size; ++i)
1721         profiles->m_buffer.get()[i].m_operand = liveOperands[i].offset();
1722
1723     // The compiler thread will read this pointer value and then proceed to dereference it
1724     // if it is not null. We need to make sure all above stores happen before this store so
1725     // the compiler thread reads fully initialized data.
1726     WTF::storeStoreFence(); 
1727
1728     m_instructions[bytecodeOffset + 3].u.pointer = profiles.get();
1729
1730     {
1731         ConcurrentJSLocker locker(m_lock);
1732         m_catchProfiles.append(WTFMove(profiles));
1733     }
1734 }
1735
1736 void CodeBlock::removeExceptionHandlerForCallSite(CallSiteIndex callSiteIndex)
1737 {
1738     RELEASE_ASSERT(m_rareData);
1739     Vector<HandlerInfo>& exceptionHandlers = m_rareData->m_exceptionHandlers;
1740     unsigned index = callSiteIndex.bits();
1741     for (size_t i = 0; i < exceptionHandlers.size(); ++i) {
1742         HandlerInfo& handler = exceptionHandlers[i];
1743         if (handler.start <= index && handler.end > index) {
1744             exceptionHandlers.remove(i);
1745             return;
1746         }
1747     }
1748
1749     RELEASE_ASSERT_NOT_REACHED();
1750 }
1751
1752 unsigned CodeBlock::lineNumberForBytecodeOffset(unsigned bytecodeOffset)
1753 {
1754     RELEASE_ASSERT(bytecodeOffset < instructions().size());
1755     return ownerScriptExecutable()->firstLine() + m_unlinkedCode->lineNumberForBytecodeOffset(bytecodeOffset);
1756 }
1757
1758 unsigned CodeBlock::columnNumberForBytecodeOffset(unsigned bytecodeOffset)
1759 {
1760     int divot;
1761     int startOffset;
1762     int endOffset;
1763     unsigned line;
1764     unsigned column;
1765     expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
1766     return column;
1767 }
1768
1769 void CodeBlock::expressionRangeForBytecodeOffset(unsigned bytecodeOffset, int& divot, int& startOffset, int& endOffset, unsigned& line, unsigned& column) const
1770 {
1771     m_unlinkedCode->expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
1772     divot += m_sourceOffset;
1773     column += line ? 1 : firstLineColumnOffset();
1774     line += ownerScriptExecutable()->firstLine();
1775 }
1776
1777 bool CodeBlock::hasOpDebugForLineAndColumn(unsigned line, unsigned column)
1778 {
1779     const Instruction* begin = instructions().begin();
1780     const Instruction* end = instructions().end();
1781     for (const Instruction* it = begin; it != end;) {
1782         OpcodeID opcodeID = Interpreter::getOpcodeID(*it);
1783         if (opcodeID == op_debug) {
1784             unsigned bytecodeOffset = it - begin;
1785             int unused;
1786             unsigned opDebugLine;
1787             unsigned opDebugColumn;
1788             expressionRangeForBytecodeOffset(bytecodeOffset, unused, unused, unused, opDebugLine, opDebugColumn);
1789             if (line == opDebugLine && (column == Breakpoint::unspecifiedColumn || column == opDebugColumn))
1790                 return true;
1791         }
1792         it += opcodeLengths[opcodeID];
1793     }
1794     return false;
1795 }
1796
1797 void CodeBlock::shrinkToFit(ShrinkMode shrinkMode)
1798 {
1799     ConcurrentJSLocker locker(m_lock);
1800
1801     m_rareCaseProfiles.shrinkToFit();
1802     
1803     if (shrinkMode == EarlyShrink) {
1804         m_constantRegisters.shrinkToFit();
1805         m_constantsSourceCodeRepresentation.shrinkToFit();
1806         
1807         if (m_rareData) {
1808             m_rareData->m_switchJumpTables.shrinkToFit();
1809             m_rareData->m_stringSwitchJumpTables.shrinkToFit();
1810         }
1811     } // else don't shrink these, because we would have already pointed pointers into these tables.
1812 }
1813
1814 #if ENABLE(JIT)
1815 void CodeBlock::linkIncomingCall(ExecState* callerFrame, CallLinkInfo* incoming)
1816 {
1817     noticeIncomingCall(callerFrame);
1818     m_incomingCalls.push(incoming);
1819 }
1820
1821 void CodeBlock::linkIncomingPolymorphicCall(ExecState* callerFrame, PolymorphicCallNode* incoming)
1822 {
1823     noticeIncomingCall(callerFrame);
1824     m_incomingPolymorphicCalls.push(incoming);
1825 }
1826 #endif // ENABLE(JIT)
1827
1828 void CodeBlock::unlinkIncomingCalls()
1829 {
1830     while (m_incomingLLIntCalls.begin() != m_incomingLLIntCalls.end())
1831         m_incomingLLIntCalls.begin()->unlink();
1832 #if ENABLE(JIT)
1833     while (m_incomingCalls.begin() != m_incomingCalls.end())
1834         m_incomingCalls.begin()->unlink(*vm());
1835     while (m_incomingPolymorphicCalls.begin() != m_incomingPolymorphicCalls.end())
1836         m_incomingPolymorphicCalls.begin()->unlink(*vm());
1837 #endif // ENABLE(JIT)
1838 }
1839
1840 void CodeBlock::linkIncomingCall(ExecState* callerFrame, LLIntCallLinkInfo* incoming)
1841 {
1842     noticeIncomingCall(callerFrame);
1843     m_incomingLLIntCalls.push(incoming);
1844 }
1845
1846 CodeBlock* CodeBlock::newReplacement()
1847 {
1848     return ownerScriptExecutable()->newReplacementCodeBlockFor(specializationKind());
1849 }
1850
1851 #if ENABLE(JIT)
1852 CodeBlock* CodeBlock::replacement()
1853 {
1854     const ClassInfo* classInfo = this->classInfo(*vm());
1855
1856     if (classInfo == FunctionCodeBlock::info())
1857         return jsCast<FunctionExecutable*>(ownerExecutable())->codeBlockFor(m_isConstructor ? CodeForConstruct : CodeForCall);
1858
1859     if (classInfo == EvalCodeBlock::info())
1860         return jsCast<EvalExecutable*>(ownerExecutable())->codeBlock();
1861
1862     if (classInfo == ProgramCodeBlock::info())
1863         return jsCast<ProgramExecutable*>(ownerExecutable())->codeBlock();
1864
1865     if (classInfo == ModuleProgramCodeBlock::info())
1866         return jsCast<ModuleProgramExecutable*>(ownerExecutable())->codeBlock();
1867
1868     RELEASE_ASSERT_NOT_REACHED();
1869     return nullptr;
1870 }
1871
1872 DFG::CapabilityLevel CodeBlock::computeCapabilityLevel()
1873 {
1874     const ClassInfo* classInfo = this->classInfo(*vm());
1875
1876     if (classInfo == FunctionCodeBlock::info()) {
1877         if (m_isConstructor)
1878             return DFG::functionForConstructCapabilityLevel(this);
1879         return DFG::functionForCallCapabilityLevel(this);
1880     }
1881
1882     if (classInfo == EvalCodeBlock::info())
1883         return DFG::evalCapabilityLevel(this);
1884
1885     if (classInfo == ProgramCodeBlock::info())
1886         return DFG::programCapabilityLevel(this);
1887
1888     if (classInfo == ModuleProgramCodeBlock::info())
1889         return DFG::programCapabilityLevel(this);
1890
1891     RELEASE_ASSERT_NOT_REACHED();
1892     return DFG::CannotCompile;
1893 }
1894
1895 #endif // ENABLE(JIT)
1896
1897 void CodeBlock::jettison(Profiler::JettisonReason reason, ReoptimizationMode mode, const FireDetail* detail)
1898 {
1899 #if !ENABLE(DFG_JIT)
1900     UNUSED_PARAM(mode);
1901     UNUSED_PARAM(detail);
1902 #endif
1903     
1904     CODEBLOCK_LOG_EVENT(this, "jettison", ("due to ", reason, ", counting = ", mode == CountReoptimization, ", detail = ", pointerDump(detail)));
1905
1906     RELEASE_ASSERT(reason != Profiler::NotJettisoned);
1907     
1908 #if ENABLE(DFG_JIT)
1909     if (DFG::shouldDumpDisassembly()) {
1910         dataLog("Jettisoning ", *this);
1911         if (mode == CountReoptimization)
1912             dataLog(" and counting reoptimization");
1913         dataLog(" due to ", reason);
1914         if (detail)
1915             dataLog(", ", *detail);
1916         dataLog(".\n");
1917     }
1918     
1919     if (reason == Profiler::JettisonDueToWeakReference) {
1920         if (DFG::shouldDumpDisassembly()) {
1921             dataLog(*this, " will be jettisoned because of the following dead references:\n");
1922             DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
1923             for (auto& transition : dfgCommon->transitions) {
1924                 JSCell* origin = transition.m_codeOrigin.get();
1925                 JSCell* from = transition.m_from.get();
1926                 JSCell* to = transition.m_to.get();
1927                 if ((!origin || Heap::isMarked(origin)) && Heap::isMarked(from))
1928                     continue;
1929                 dataLog("    Transition under ", RawPointer(origin), ", ", RawPointer(from), " -> ", RawPointer(to), ".\n");
1930             }
1931             for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
1932                 JSCell* weak = dfgCommon->weakReferences[i].get();
1933                 if (Heap::isMarked(weak))
1934                     continue;
1935                 dataLog("    Weak reference ", RawPointer(weak), ".\n");
1936             }
1937         }
1938     }
1939 #endif // ENABLE(DFG_JIT)
1940
1941     VM& vm = *m_poisonedVM;
1942     DeferGCForAWhile deferGC(*heap());
1943     
1944     // We want to accomplish two things here:
1945     // 1) Make sure that if this CodeBlock is on the stack right now, then if we return to it
1946     //    we should OSR exit at the top of the next bytecode instruction after the return.
1947     // 2) Make sure that if we call the owner executable, then we shouldn't call this CodeBlock.
1948
1949 #if ENABLE(DFG_JIT)
1950     if (reason != Profiler::JettisonDueToOldAge) {
1951         Profiler::Compilation* compilation = jitCode()->dfgCommon()->compilation.get();
1952         if (UNLIKELY(compilation))
1953             compilation->setJettisonReason(reason, detail);
1954         
1955         // This accomplishes (1), and does its own book-keeping about whether it has already happened.
1956         if (!jitCode()->dfgCommon()->invalidate()) {
1957             // We've already been invalidated.
1958             RELEASE_ASSERT(this != replacement() || (vm.heap.isCurrentThreadBusy() && !Heap::isMarked(ownerScriptExecutable())));
1959             return;
1960         }
1961     }
1962     
1963     if (DFG::shouldDumpDisassembly())
1964         dataLog("    Did invalidate ", *this, "\n");
1965     
1966     // Count the reoptimization if that's what the user wanted.
1967     if (mode == CountReoptimization) {
1968         // FIXME: Maybe this should call alternative().
1969         // https://bugs.webkit.org/show_bug.cgi?id=123677
1970         baselineAlternative()->countReoptimization();
1971         if (DFG::shouldDumpDisassembly())
1972             dataLog("    Did count reoptimization for ", *this, "\n");
1973     }
1974     
1975     if (this != replacement()) {
1976         // This means that we were never the entrypoint. This can happen for OSR entry code
1977         // blocks.
1978         return;
1979     }
1980
1981     if (alternative())
1982         alternative()->optimizeAfterWarmUp();
1983
1984     if (reason != Profiler::JettisonDueToOldAge && reason != Profiler::JettisonDueToVMTraps)
1985         tallyFrequentExitSites();
1986 #endif // ENABLE(DFG_JIT)
1987
1988     // Jettison can happen during GC. We don't want to install code to a dead executable
1989     // because that would add a dead object to the remembered set.
1990     if (vm.heap.isCurrentThreadBusy() && !Heap::isMarked(ownerScriptExecutable()))
1991         return;
1992
1993     // This accomplishes (2).
1994     ownerScriptExecutable()->installCode(vm, alternative(), codeType(), specializationKind());
1995
1996 #if ENABLE(DFG_JIT)
1997     if (DFG::shouldDumpDisassembly())
1998         dataLog("    Did install baseline version of ", *this, "\n");
1999 #endif // ENABLE(DFG_JIT)
2000 }
2001
2002 JSGlobalObject* CodeBlock::globalObjectFor(CodeOrigin codeOrigin)
2003 {
2004     if (!codeOrigin.inlineCallFrame)
2005         return globalObject();
2006     return codeOrigin.inlineCallFrame->baselineCodeBlock->globalObject();
2007 }
2008
2009 class RecursionCheckFunctor {
2010 public:
2011     RecursionCheckFunctor(CallFrame* startCallFrame, CodeBlock* codeBlock, unsigned depthToCheck)
2012         : m_startCallFrame(startCallFrame)
2013         , m_codeBlock(codeBlock)
2014         , m_depthToCheck(depthToCheck)
2015         , m_foundStartCallFrame(false)
2016         , m_didRecurse(false)
2017     { }
2018
2019     StackVisitor::Status operator()(StackVisitor& visitor) const
2020     {
2021         CallFrame* currentCallFrame = visitor->callFrame();
2022
2023         if (currentCallFrame == m_startCallFrame)
2024             m_foundStartCallFrame = true;
2025
2026         if (m_foundStartCallFrame) {
2027             if (visitor->callFrame()->codeBlock() == m_codeBlock) {
2028                 m_didRecurse = true;
2029                 return StackVisitor::Done;
2030             }
2031
2032             if (!m_depthToCheck--)
2033                 return StackVisitor::Done;
2034         }
2035
2036         return StackVisitor::Continue;
2037     }
2038
2039     bool didRecurse() const { return m_didRecurse; }
2040
2041 private:
2042     CallFrame* m_startCallFrame;
2043     CodeBlock* m_codeBlock;
2044     mutable unsigned m_depthToCheck;
2045     mutable bool m_foundStartCallFrame;
2046     mutable bool m_didRecurse;
2047 };
2048
2049 void CodeBlock::noticeIncomingCall(ExecState* callerFrame)
2050 {
2051     CodeBlock* callerCodeBlock = callerFrame->codeBlock();
2052     
2053     if (Options::verboseCallLink())
2054         dataLog("Noticing call link from ", pointerDump(callerCodeBlock), " to ", *this, "\n");
2055     
2056 #if ENABLE(DFG_JIT)
2057     if (!m_shouldAlwaysBeInlined)
2058         return;
2059     
2060     if (!callerCodeBlock) {
2061         m_shouldAlwaysBeInlined = false;
2062         if (Options::verboseCallLink())
2063             dataLog("    Clearing SABI because caller is native.\n");
2064         return;
2065     }
2066
2067     if (!hasBaselineJITProfiling())
2068         return;
2069
2070     if (!DFG::mightInlineFunction(this))
2071         return;
2072
2073     if (!canInline(capabilityLevelState()))
2074         return;
2075     
2076     if (!DFG::isSmallEnoughToInlineCodeInto(callerCodeBlock)) {
2077         m_shouldAlwaysBeInlined = false;
2078         if (Options::verboseCallLink())
2079             dataLog("    Clearing SABI because caller is too large.\n");
2080         return;
2081     }
2082
2083     if (callerCodeBlock->jitType() == JITCode::InterpreterThunk) {
2084         // If the caller is still in the interpreter, then we can't expect inlining to
2085         // happen anytime soon. Assume it's profitable to optimize it separately. This
2086         // ensures that a function is SABI only if it is called no more frequently than
2087         // any of its callers.
2088         m_shouldAlwaysBeInlined = false;
2089         if (Options::verboseCallLink())
2090             dataLog("    Clearing SABI because caller is in LLInt.\n");
2091         return;
2092     }
2093     
2094     if (JITCode::isOptimizingJIT(callerCodeBlock->jitType())) {
2095         m_shouldAlwaysBeInlined = false;
2096         if (Options::verboseCallLink())
2097             dataLog("    Clearing SABI bcause caller was already optimized.\n");
2098         return;
2099     }
2100     
2101     if (callerCodeBlock->codeType() != FunctionCode) {
2102         // If the caller is either eval or global code, assume that that won't be
2103         // optimized anytime soon. For eval code this is particularly true since we
2104         // delay eval optimization by a *lot*.
2105         m_shouldAlwaysBeInlined = false;
2106         if (Options::verboseCallLink())
2107             dataLog("    Clearing SABI because caller is not a function.\n");
2108         return;
2109     }
2110
2111     // Recursive calls won't be inlined.
2112     RecursionCheckFunctor functor(callerFrame, this, Options::maximumInliningDepth());
2113     vm()->topCallFrame->iterate(functor);
2114
2115     if (functor.didRecurse()) {
2116         if (Options::verboseCallLink())
2117             dataLog("    Clearing SABI because recursion was detected.\n");
2118         m_shouldAlwaysBeInlined = false;
2119         return;
2120     }
2121     
2122     if (callerCodeBlock->capabilityLevelState() == DFG::CapabilityLevelNotSet) {
2123         dataLog("In call from ", FullCodeOrigin(callerCodeBlock, callerFrame->codeOrigin()), " to ", *this, ": caller's DFG capability level is not set.\n");
2124         CRASH();
2125     }
2126     
2127     if (canCompile(callerCodeBlock->capabilityLevelState()))
2128         return;
2129     
2130     if (Options::verboseCallLink())
2131         dataLog("    Clearing SABI because the caller is not a DFG candidate.\n");
2132     
2133     m_shouldAlwaysBeInlined = false;
2134 #endif
2135 }
2136
2137 unsigned CodeBlock::reoptimizationRetryCounter() const
2138 {
2139 #if ENABLE(JIT)
2140     ASSERT(m_reoptimizationRetryCounter <= Options::reoptimizationRetryCounterMax());
2141     return m_reoptimizationRetryCounter;
2142 #else
2143     return 0;
2144 #endif // ENABLE(JIT)
2145 }
2146
2147 #if ENABLE(JIT)
2148 void CodeBlock::setCalleeSaveRegisters(RegisterSet calleeSaveRegisters)
2149 {
2150     m_calleeSaveRegisters = std::make_unique<RegisterAtOffsetList>(calleeSaveRegisters);
2151 }
2152
2153 void CodeBlock::setCalleeSaveRegisters(std::unique_ptr<RegisterAtOffsetList> registerAtOffsetList)
2154 {
2155     m_calleeSaveRegisters = WTFMove(registerAtOffsetList);
2156 }
2157     
2158 static size_t roundCalleeSaveSpaceAsVirtualRegisters(size_t calleeSaveRegisters)
2159 {
2160     static const unsigned cpuRegisterSize = sizeof(void*);
2161     return (WTF::roundUpToMultipleOf(sizeof(Register), calleeSaveRegisters * cpuRegisterSize) / sizeof(Register));
2162
2163 }
2164
2165 size_t CodeBlock::llintBaselineCalleeSaveSpaceAsVirtualRegisters()
2166 {
2167     return roundCalleeSaveSpaceAsVirtualRegisters(numberOfLLIntBaselineCalleeSaveRegisters());
2168 }
2169
2170 size_t CodeBlock::calleeSaveSpaceAsVirtualRegisters()
2171 {
2172     return roundCalleeSaveSpaceAsVirtualRegisters(m_calleeSaveRegisters->size());
2173 }
2174
2175 void CodeBlock::countReoptimization()
2176 {
2177     m_reoptimizationRetryCounter++;
2178     if (m_reoptimizationRetryCounter > Options::reoptimizationRetryCounterMax())
2179         m_reoptimizationRetryCounter = Options::reoptimizationRetryCounterMax();
2180 }
2181
2182 unsigned CodeBlock::numberOfDFGCompiles()
2183 {
2184     ASSERT(JITCode::isBaselineCode(jitType()));
2185     if (Options::testTheFTL()) {
2186         if (m_didFailFTLCompilation)
2187             return 1000000;
2188         return (m_hasBeenCompiledWithFTL ? 1 : 0) + m_reoptimizationRetryCounter;
2189     }
2190     CodeBlock* replacement = this->replacement();
2191     return ((replacement && JITCode::isOptimizingJIT(replacement->jitType())) ? 1 : 0) + m_reoptimizationRetryCounter;
2192 }
2193
2194 int32_t CodeBlock::codeTypeThresholdMultiplier() const
2195 {
2196     if (codeType() == EvalCode)
2197         return Options::evalThresholdMultiplier();
2198     
2199     return 1;
2200 }
2201
2202 double CodeBlock::optimizationThresholdScalingFactor()
2203 {
2204     // This expression arises from doing a least-squares fit of
2205     //
2206     // F[x_] =: a * Sqrt[x + b] + Abs[c * x] + d
2207     //
2208     // against the data points:
2209     //
2210     //    x       F[x_]
2211     //    10       0.9          (smallest reasonable code block)
2212     //   200       1.0          (typical small-ish code block)
2213     //   320       1.2          (something I saw in 3d-cube that I wanted to optimize)
2214     //  1268       5.0          (something I saw in 3d-cube that I didn't want to optimize)
2215     //  4000       5.5          (random large size, used to cause the function to converge to a shallow curve of some sort)
2216     // 10000       6.0          (similar to above)
2217     //
2218     // I achieve the minimization using the following Mathematica code:
2219     //
2220     // MyFunctionTemplate[x_, a_, b_, c_, d_] := a*Sqrt[x + b] + Abs[c*x] + d
2221     //
2222     // samples = {{10, 0.9}, {200, 1}, {320, 1.2}, {1268, 5}, {4000, 5.5}, {10000, 6}}
2223     //
2224     // solution = 
2225     //     Minimize[Plus @@ ((MyFunctionTemplate[#[[1]], a, b, c, d] - #[[2]])^2 & /@ samples),
2226     //         {a, b, c, d}][[2]]
2227     //
2228     // And the code below (to initialize a, b, c, d) is generated by:
2229     //
2230     // Print["const double " <> ToString[#[[1]]] <> " = " <>
2231     //     If[#[[2]] < 0.00001, "0.0", ToString[#[[2]]]] <> ";"] & /@ solution
2232     //
2233     // We've long known the following to be true:
2234     // - Small code blocks are cheap to optimize and so we should do it sooner rather
2235     //   than later.
2236     // - Large code blocks are expensive to optimize and so we should postpone doing so,
2237     //   and sometimes have a large enough threshold that we never optimize them.
2238     // - The difference in cost is not totally linear because (a) just invoking the
2239     //   DFG incurs some base cost and (b) for large code blocks there is enough slop
2240     //   in the correlation between instruction count and the actual compilation cost
2241     //   that for those large blocks, the instruction count should not have a strong
2242     //   influence on our threshold.
2243     //
2244     // I knew the goals but I didn't know how to achieve them; so I picked an interesting
2245     // example where the heuristics were right (code block in 3d-cube with instruction
2246     // count 320, which got compiled early as it should have been) and one where they were
2247     // totally wrong (code block in 3d-cube with instruction count 1268, which was expensive
2248     // to compile and didn't run often enough to warrant compilation in my opinion), and
2249     // then threw in additional data points that represented my own guess of what our
2250     // heuristics should do for some round-numbered examples.
2251     //
2252     // The expression to which I decided to fit the data arose because I started with an
2253     // affine function, and then did two things: put the linear part in an Abs to ensure
2254     // that the fit didn't end up choosing a negative value of c (which would result in
2255     // the function turning over and going negative for large x) and I threw in a Sqrt
2256     // term because Sqrt represents my intution that the function should be more sensitive
2257     // to small changes in small values of x, but less sensitive when x gets large.
2258     
2259     // Note that the current fit essentially eliminates the linear portion of the
2260     // expression (c == 0.0).
2261     const double a = 0.061504;
2262     const double b = 1.02406;
2263     const double c = 0.0;
2264     const double d = 0.825914;
2265     
2266     double instructionCount = this->instructionCount();
2267     
2268     ASSERT(instructionCount); // Make sure this is called only after we have an instruction stream; otherwise it'll just return the value of d, which makes no sense.
2269     
2270     double result = d + a * sqrt(instructionCount + b) + c * instructionCount;
2271     
2272     result *= codeTypeThresholdMultiplier();
2273     
2274     if (Options::verboseOSR()) {
2275         dataLog(
2276             *this, ": instruction count is ", instructionCount,
2277             ", scaling execution counter by ", result, " * ", codeTypeThresholdMultiplier(),
2278             "\n");
2279     }
2280     return result;
2281 }
2282
2283 static int32_t clipThreshold(double threshold)
2284 {
2285     if (threshold < 1.0)
2286         return 1;
2287     
2288     if (threshold > static_cast<double>(std::numeric_limits<int32_t>::max()))
2289         return std::numeric_limits<int32_t>::max();
2290     
2291     return static_cast<int32_t>(threshold);
2292 }
2293
2294 int32_t CodeBlock::adjustedCounterValue(int32_t desiredThreshold)
2295 {
2296     return clipThreshold(
2297         static_cast<double>(desiredThreshold) *
2298         optimizationThresholdScalingFactor() *
2299         (1 << reoptimizationRetryCounter()));
2300 }
2301
2302 bool CodeBlock::checkIfOptimizationThresholdReached()
2303 {
2304 #if ENABLE(DFG_JIT)
2305     if (DFG::Worklist* worklist = DFG::existingGlobalDFGWorklistOrNull()) {
2306         if (worklist->compilationState(DFG::CompilationKey(this, DFG::DFGMode))
2307             == DFG::Worklist::Compiled) {
2308             optimizeNextInvocation();
2309             return true;
2310         }
2311     }
2312 #endif
2313     
2314     return m_jitExecuteCounter.checkIfThresholdCrossedAndSet(this);
2315 }
2316
2317 #if ENABLE(DFG_JIT)
2318 auto CodeBlock::updateOSRExitCounterAndCheckIfNeedToReoptimize(DFG::OSRExitState& exitState) -> OptimizeAction
2319 {
2320     DFG::OSRExitBase& exit = exitState.exit;
2321     if (!exitKindMayJettison(exit.m_kind)) {
2322         // FIXME: We may want to notice that we're frequently exiting
2323         // at an op_catch that we didn't compile an entrypoint for, and
2324         // then trigger a reoptimization of this CodeBlock:
2325         // https://bugs.webkit.org/show_bug.cgi?id=175842
2326         return OptimizeAction::None;
2327     }
2328
2329     exit.m_count++;
2330     m_osrExitCounter++;
2331
2332     CodeBlock* baselineCodeBlock = exitState.baselineCodeBlock;
2333     ASSERT(baselineCodeBlock == baselineAlternative());
2334     if (UNLIKELY(baselineCodeBlock->jitExecuteCounter().hasCrossedThreshold()))
2335         return OptimizeAction::ReoptimizeNow;
2336
2337     // We want to figure out if there's a possibility that we're in a loop. For the outermost
2338     // code block in the inline stack, we handle this appropriately by having the loop OSR trigger
2339     // check the exit count of the replacement of the CodeBlock from which we are OSRing. The
2340     // problem is the inlined functions, which might also have loops, but whose baseline versions
2341     // don't know where to look for the exit count. Figure out if those loops are severe enough
2342     // that we had tried to OSR enter. If so, then we should use the loop reoptimization trigger.
2343     // Otherwise, we should use the normal reoptimization trigger.
2344
2345     bool didTryToEnterInLoop = false;
2346     for (InlineCallFrame* inlineCallFrame = exit.m_codeOrigin.inlineCallFrame; inlineCallFrame; inlineCallFrame = inlineCallFrame->directCaller.inlineCallFrame) {
2347         if (inlineCallFrame->baselineCodeBlock->ownerScriptExecutable()->didTryToEnterInLoop()) {
2348             didTryToEnterInLoop = true;
2349             break;
2350         }
2351     }
2352
2353     uint32_t exitCountThreshold = didTryToEnterInLoop
2354         ? exitCountThresholdForReoptimizationFromLoop()
2355         : exitCountThresholdForReoptimization();
2356
2357     if (m_osrExitCounter > exitCountThreshold)
2358         return OptimizeAction::ReoptimizeNow;
2359
2360     // Too few fails. Adjust the execution counter such that the target is to only optimize after a while.
2361     baselineCodeBlock->m_jitExecuteCounter.setNewThresholdForOSRExit(exitState.activeThreshold, exitState.memoryUsageAdjustedThreshold);
2362     return OptimizeAction::None;
2363 }
2364 #endif
2365
2366 void CodeBlock::optimizeNextInvocation()
2367 {
2368     if (Options::verboseOSR())
2369         dataLog(*this, ": Optimizing next invocation.\n");
2370     m_jitExecuteCounter.setNewThreshold(0, this);
2371 }
2372
2373 void CodeBlock::dontOptimizeAnytimeSoon()
2374 {
2375     if (Options::verboseOSR())
2376         dataLog(*this, ": Not optimizing anytime soon.\n");
2377     m_jitExecuteCounter.deferIndefinitely();
2378 }
2379
2380 void CodeBlock::optimizeAfterWarmUp()
2381 {
2382     if (Options::verboseOSR())
2383         dataLog(*this, ": Optimizing after warm-up.\n");
2384 #if ENABLE(DFG_JIT)
2385     m_jitExecuteCounter.setNewThreshold(
2386         adjustedCounterValue(Options::thresholdForOptimizeAfterWarmUp()), this);
2387 #endif
2388 }
2389
2390 void CodeBlock::optimizeAfterLongWarmUp()
2391 {
2392     if (Options::verboseOSR())
2393         dataLog(*this, ": Optimizing after long warm-up.\n");
2394 #if ENABLE(DFG_JIT)
2395     m_jitExecuteCounter.setNewThreshold(
2396         adjustedCounterValue(Options::thresholdForOptimizeAfterLongWarmUp()), this);
2397 #endif
2398 }
2399
2400 void CodeBlock::optimizeSoon()
2401 {
2402     if (Options::verboseOSR())
2403         dataLog(*this, ": Optimizing soon.\n");
2404 #if ENABLE(DFG_JIT)
2405     m_jitExecuteCounter.setNewThreshold(
2406         adjustedCounterValue(Options::thresholdForOptimizeSoon()), this);
2407 #endif
2408 }
2409
2410 void CodeBlock::forceOptimizationSlowPathConcurrently()
2411 {
2412     if (Options::verboseOSR())
2413         dataLog(*this, ": Forcing slow path concurrently.\n");
2414     m_jitExecuteCounter.forceSlowPathConcurrently();
2415 }
2416
2417 #if ENABLE(DFG_JIT)
2418 void CodeBlock::setOptimizationThresholdBasedOnCompilationResult(CompilationResult result)
2419 {
2420     JITCode::JITType type = jitType();
2421     if (type != JITCode::BaselineJIT) {
2422         dataLog(*this, ": expected to have baseline code but have ", type, "\n");
2423         RELEASE_ASSERT_NOT_REACHED();
2424     }
2425     
2426     CodeBlock* replacement = this->replacement();
2427     bool hasReplacement = (replacement && replacement != this);
2428     if ((result == CompilationSuccessful) != hasReplacement) {
2429         dataLog(*this, ": we have result = ", result, " but ");
2430         if (replacement == this)
2431             dataLog("we are our own replacement.\n");
2432         else
2433             dataLog("our replacement is ", pointerDump(replacement), "\n");
2434         RELEASE_ASSERT_NOT_REACHED();
2435     }
2436     
2437     switch (result) {
2438     case CompilationSuccessful:
2439         RELEASE_ASSERT(replacement && JITCode::isOptimizingJIT(replacement->jitType()));
2440         optimizeNextInvocation();
2441         return;
2442     case CompilationFailed:
2443         dontOptimizeAnytimeSoon();
2444         return;
2445     case CompilationDeferred:
2446         // We'd like to do dontOptimizeAnytimeSoon() but we cannot because
2447         // forceOptimizationSlowPathConcurrently() is inherently racy. It won't
2448         // necessarily guarantee anything. So, we make sure that even if that
2449         // function ends up being a no-op, we still eventually retry and realize
2450         // that we have optimized code ready.
2451         optimizeAfterWarmUp();
2452         return;
2453     case CompilationInvalidated:
2454         // Retry with exponential backoff.
2455         countReoptimization();
2456         optimizeAfterWarmUp();
2457         return;
2458     }
2459     
2460     dataLog("Unrecognized result: ", static_cast<int>(result), "\n");
2461     RELEASE_ASSERT_NOT_REACHED();
2462 }
2463
2464 #endif
2465     
2466 uint32_t CodeBlock::adjustedExitCountThreshold(uint32_t desiredThreshold)
2467 {
2468     ASSERT(JITCode::isOptimizingJIT(jitType()));
2469     // Compute this the lame way so we don't saturate. This is called infrequently
2470     // enough that this loop won't hurt us.
2471     unsigned result = desiredThreshold;
2472     for (unsigned n = baselineVersion()->reoptimizationRetryCounter(); n--;) {
2473         unsigned newResult = result << 1;
2474         if (newResult < result)
2475             return std::numeric_limits<uint32_t>::max();
2476         result = newResult;
2477     }
2478     return result;
2479 }
2480
2481 uint32_t CodeBlock::exitCountThresholdForReoptimization()
2482 {
2483     return adjustedExitCountThreshold(Options::osrExitCountForReoptimization() * codeTypeThresholdMultiplier());
2484 }
2485
2486 uint32_t CodeBlock::exitCountThresholdForReoptimizationFromLoop()
2487 {
2488     return adjustedExitCountThreshold(Options::osrExitCountForReoptimizationFromLoop() * codeTypeThresholdMultiplier());
2489 }
2490
2491 bool CodeBlock::shouldReoptimizeNow()
2492 {
2493     return osrExitCounter() >= exitCountThresholdForReoptimization();
2494 }
2495
2496 bool CodeBlock::shouldReoptimizeFromLoopNow()
2497 {
2498     return osrExitCounter() >= exitCountThresholdForReoptimizationFromLoop();
2499 }
2500 #endif
2501
2502 ArrayProfile* CodeBlock::getArrayProfile(const ConcurrentJSLocker&, unsigned bytecodeOffset)
2503 {
2504     for (auto& m_arrayProfile : m_arrayProfiles) {
2505         if (m_arrayProfile.bytecodeOffset() == bytecodeOffset)
2506             return &m_arrayProfile;
2507     }
2508     return 0;
2509 }
2510
2511 ArrayProfile* CodeBlock::getArrayProfile(unsigned bytecodeOffset)
2512 {
2513     ConcurrentJSLocker locker(m_lock);
2514     return getArrayProfile(locker, bytecodeOffset);
2515 }
2516
2517 ArrayProfile* CodeBlock::addArrayProfile(const ConcurrentJSLocker&, unsigned bytecodeOffset)
2518 {
2519     m_arrayProfiles.append(ArrayProfile(bytecodeOffset));
2520     return &m_arrayProfiles.last();
2521 }
2522
2523 ArrayProfile* CodeBlock::addArrayProfile(unsigned bytecodeOffset)
2524 {
2525     ConcurrentJSLocker locker(m_lock);
2526     return addArrayProfile(locker, bytecodeOffset);
2527 }
2528
2529 ArrayProfile* CodeBlock::getOrAddArrayProfile(const ConcurrentJSLocker& locker, unsigned bytecodeOffset)
2530 {
2531     ArrayProfile* result = getArrayProfile(locker, bytecodeOffset);
2532     if (result)
2533         return result;
2534     return addArrayProfile(locker, bytecodeOffset);
2535 }
2536
2537 ArrayProfile* CodeBlock::getOrAddArrayProfile(unsigned bytecodeOffset)
2538 {
2539     ConcurrentJSLocker locker(m_lock);
2540     return getOrAddArrayProfile(locker, bytecodeOffset);
2541 }
2542
2543 #if ENABLE(DFG_JIT)
2544 Vector<CodeOrigin, 0, UnsafeVectorOverflow>& CodeBlock::codeOrigins()
2545 {
2546     return m_jitCode->dfgCommon()->codeOrigins;
2547 }
2548
2549 size_t CodeBlock::numberOfDFGIdentifiers() const
2550 {
2551     if (!JITCode::isOptimizingJIT(jitType()))
2552         return 0;
2553     
2554     return m_jitCode->dfgCommon()->dfgIdentifiers.size();
2555 }
2556
2557 const Identifier& CodeBlock::identifier(int index) const
2558 {
2559     size_t unlinkedIdentifiers = m_unlinkedCode->numberOfIdentifiers();
2560     if (static_cast<unsigned>(index) < unlinkedIdentifiers)
2561         return m_unlinkedCode->identifier(index);
2562     ASSERT(JITCode::isOptimizingJIT(jitType()));
2563     return m_jitCode->dfgCommon()->dfgIdentifiers[index - unlinkedIdentifiers];
2564 }
2565 #endif // ENABLE(DFG_JIT)
2566
2567 void CodeBlock::updateAllPredictionsAndCountLiveness(unsigned& numberOfLiveNonArgumentValueProfiles, unsigned& numberOfSamplesInProfiles)
2568 {
2569     ConcurrentJSLocker locker(m_lock);
2570
2571     numberOfLiveNonArgumentValueProfiles = 0;
2572     numberOfSamplesInProfiles = 0; // If this divided by ValueProfile::numberOfBuckets equals numberOfValueProfiles() then value profiles are full.
2573
2574     for (unsigned i = 0; i < totalNumberOfValueProfiles(); ++i) {
2575         ValueProfile& profile = getFromAllValueProfiles(i);
2576         unsigned numSamples = profile.totalNumberOfSamples();
2577         if (numSamples > ValueProfile::numberOfBuckets)
2578             numSamples = ValueProfile::numberOfBuckets; // We don't want profiles that are extremely hot to be given more weight.
2579         numberOfSamplesInProfiles += numSamples;
2580         if (profile.m_bytecodeOffset < 0) {
2581             profile.computeUpdatedPrediction(locker);
2582             continue;
2583         }
2584         if (profile.numberOfSamples() || profile.m_prediction != SpecNone)
2585             numberOfLiveNonArgumentValueProfiles++;
2586         profile.computeUpdatedPrediction(locker);
2587     }
2588
2589     for (auto& profileBucket : m_catchProfiles) {
2590         profileBucket->forEach([&] (ValueProfileAndOperand& profile) {
2591             profile.m_profile.computeUpdatedPrediction(locker);
2592         });
2593     }
2594     
2595 #if ENABLE(DFG_JIT)
2596     m_lazyOperandValueProfiles.computeUpdatedPredictions(locker);
2597 #endif
2598 }
2599
2600 void CodeBlock::updateAllValueProfilePredictions()
2601 {
2602     unsigned ignoredValue1, ignoredValue2;
2603     updateAllPredictionsAndCountLiveness(ignoredValue1, ignoredValue2);
2604 }
2605
2606 void CodeBlock::updateAllArrayPredictions()
2607 {
2608     ConcurrentJSLocker locker(m_lock);
2609     
2610     for (unsigned i = m_arrayProfiles.size(); i--;)
2611         m_arrayProfiles[i].computeUpdatedPrediction(locker, this);
2612     
2613     // Don't count these either, for similar reasons.
2614     for (unsigned i = m_arrayAllocationProfiles.size(); i--;)
2615         m_arrayAllocationProfiles[i].updateProfile();
2616 }
2617
2618 void CodeBlock::updateAllPredictions()
2619 {
2620     updateAllValueProfilePredictions();
2621     updateAllArrayPredictions();
2622 }
2623
2624 bool CodeBlock::shouldOptimizeNow()
2625 {
2626     if (Options::verboseOSR())
2627         dataLog("Considering optimizing ", *this, "...\n");
2628
2629     if (m_optimizationDelayCounter >= Options::maximumOptimizationDelay())
2630         return true;
2631     
2632     updateAllArrayPredictions();
2633     
2634     unsigned numberOfLiveNonArgumentValueProfiles;
2635     unsigned numberOfSamplesInProfiles;
2636     updateAllPredictionsAndCountLiveness(numberOfLiveNonArgumentValueProfiles, numberOfSamplesInProfiles);
2637
2638     if (Options::verboseOSR()) {
2639         dataLogF(
2640             "Profile hotness: %lf (%u / %u), %lf (%u / %u)\n",
2641             (double)numberOfLiveNonArgumentValueProfiles / numberOfValueProfiles(),
2642             numberOfLiveNonArgumentValueProfiles, numberOfValueProfiles(),
2643             (double)numberOfSamplesInProfiles / ValueProfile::numberOfBuckets / numberOfValueProfiles(),
2644             numberOfSamplesInProfiles, ValueProfile::numberOfBuckets * numberOfValueProfiles());
2645     }
2646
2647     if ((!numberOfValueProfiles() || (double)numberOfLiveNonArgumentValueProfiles / numberOfValueProfiles() >= Options::desiredProfileLivenessRate())
2648         && (!totalNumberOfValueProfiles() || (double)numberOfSamplesInProfiles / ValueProfile::numberOfBuckets / totalNumberOfValueProfiles() >= Options::desiredProfileFullnessRate())
2649         && static_cast<unsigned>(m_optimizationDelayCounter) + 1 >= Options::minimumOptimizationDelay())
2650         return true;
2651     
2652     ASSERT(m_optimizationDelayCounter < std::numeric_limits<uint8_t>::max());
2653     m_optimizationDelayCounter++;
2654     optimizeAfterWarmUp();
2655     return false;
2656 }
2657
2658 #if ENABLE(DFG_JIT)
2659 void CodeBlock::tallyFrequentExitSites()
2660 {
2661     ASSERT(JITCode::isOptimizingJIT(jitType()));
2662     ASSERT(alternative()->jitType() == JITCode::BaselineJIT);
2663     
2664     CodeBlock* profiledBlock = alternative();
2665     
2666     switch (jitType()) {
2667     case JITCode::DFGJIT: {
2668         DFG::JITCode* jitCode = m_jitCode->dfg();
2669         for (auto& exit : jitCode->osrExit)
2670             exit.considerAddingAsFrequentExitSite(profiledBlock);
2671         break;
2672     }
2673
2674 #if ENABLE(FTL_JIT)
2675     case JITCode::FTLJIT: {
2676         // There is no easy way to avoid duplicating this code since the FTL::JITCode::osrExit
2677         // vector contains a totally different type, that just so happens to behave like
2678         // DFG::JITCode::osrExit.
2679         FTL::JITCode* jitCode = m_jitCode->ftl();
2680         for (unsigned i = 0; i < jitCode->osrExit.size(); ++i) {
2681             FTL::OSRExit& exit = jitCode->osrExit[i];
2682             exit.considerAddingAsFrequentExitSite(profiledBlock);
2683         }
2684         break;
2685     }
2686 #endif
2687         
2688     default:
2689         RELEASE_ASSERT_NOT_REACHED();
2690         break;
2691     }
2692 }
2693 #endif // ENABLE(DFG_JIT)
2694
2695 #if ENABLE(VERBOSE_VALUE_PROFILE)
2696 void CodeBlock::dumpValueProfiles()
2697 {
2698     dataLog("ValueProfile for ", *this, ":\n");
2699     for (unsigned i = 0; i < totalNumberOfValueProfiles(); ++i) {
2700         ValueProfile& profile = getFromAllValueProfiles(i);
2701         if (profile.m_bytecodeOffset < 0) {
2702             ASSERT(profile.m_bytecodeOffset == -1);
2703             dataLogF("   arg = %u: ", i);
2704         } else
2705             dataLogF("   bc = %d: ", profile.m_bytecodeOffset);
2706         if (!profile.numberOfSamples() && profile.m_prediction == SpecNone) {
2707             dataLogF("<empty>\n");
2708             continue;
2709         }
2710         profile.dump(WTF::dataFile());
2711         dataLogF("\n");
2712     }
2713     dataLog("RareCaseProfile for ", *this, ":\n");
2714     for (unsigned i = 0; i < numberOfRareCaseProfiles(); ++i) {
2715         RareCaseProfile* profile = rareCaseProfile(i);
2716         dataLogF("   bc = %d: %u\n", profile->m_bytecodeOffset, profile->m_counter);
2717     }
2718 }
2719 #endif // ENABLE(VERBOSE_VALUE_PROFILE)
2720
2721 unsigned CodeBlock::frameRegisterCount()
2722 {
2723     switch (jitType()) {
2724     case JITCode::InterpreterThunk:
2725         return LLInt::frameRegisterCountFor(this);
2726
2727 #if ENABLE(JIT)
2728     case JITCode::BaselineJIT:
2729         return JIT::frameRegisterCountFor(this);
2730 #endif // ENABLE(JIT)
2731
2732 #if ENABLE(DFG_JIT)
2733     case JITCode::DFGJIT:
2734     case JITCode::FTLJIT:
2735         return jitCode()->dfgCommon()->frameRegisterCount;
2736 #endif // ENABLE(DFG_JIT)
2737         
2738     default:
2739         RELEASE_ASSERT_NOT_REACHED();
2740         return 0;
2741     }
2742 }
2743
2744 int CodeBlock::stackPointerOffset()
2745 {
2746     return virtualRegisterForLocal(frameRegisterCount() - 1).offset();
2747 }
2748
2749 size_t CodeBlock::predictedMachineCodeSize()
2750 {
2751     VM* vm = m_poisonedVM.unpoisoned();
2752     // This will be called from CodeBlock::CodeBlock before either m_poisonedVM or the
2753     // instructions have been initialized. It's OK to return 0 because what will really
2754     // matter is the recomputation of this value when the slow path is triggered.
2755     if (!vm)
2756         return 0;
2757     
2758     if (!*vm->machineCodeBytesPerBytecodeWordForBaselineJIT)
2759         return 0; // It's as good of a prediction as we'll get.
2760     
2761     // Be conservative: return a size that will be an overestimation 84% of the time.
2762     double multiplier = vm->machineCodeBytesPerBytecodeWordForBaselineJIT->mean() +
2763         vm->machineCodeBytesPerBytecodeWordForBaselineJIT->standardDeviation();
2764     
2765     // Be paranoid: silently reject bogus multipiers. Silently doing the "wrong" thing
2766     // here is OK, since this whole method is just a heuristic.
2767     if (multiplier < 0 || multiplier > 1000)
2768         return 0;
2769     
2770     double doubleResult = multiplier * m_instructions.size();
2771     
2772     // Be even more paranoid: silently reject values that won't fit into a size_t. If
2773     // the function is so huge that we can't even fit it into virtual memory then we
2774     // should probably have some other guards in place to prevent us from even getting
2775     // to this point.
2776     if (doubleResult > std::numeric_limits<size_t>::max())
2777         return 0;
2778     
2779     return static_cast<size_t>(doubleResult);
2780 }
2781
2782 String CodeBlock::nameForRegister(VirtualRegister virtualRegister)
2783 {
2784     for (auto& constantRegister : m_constantRegisters) {
2785         if (constantRegister.get().isEmpty())
2786             continue;
2787         if (SymbolTable* symbolTable = jsDynamicCast<SymbolTable*>(*vm(), constantRegister.get())) {
2788             ConcurrentJSLocker locker(symbolTable->m_lock);
2789             auto end = symbolTable->end(locker);
2790             for (auto ptr = symbolTable->begin(locker); ptr != end; ++ptr) {
2791                 if (ptr->value.varOffset() == VarOffset(virtualRegister)) {
2792                     // FIXME: This won't work from the compilation thread.
2793                     // https://bugs.webkit.org/show_bug.cgi?id=115300
2794                     return ptr->key.get();
2795                 }
2796             }
2797         }
2798     }
2799     if (virtualRegister == thisRegister())
2800         return "this"_s;
2801     if (virtualRegister.isArgument())
2802         return String::format("arguments[%3d]", virtualRegister.toArgument());
2803
2804     return "";
2805 }
2806
2807 ValueProfile* CodeBlock::tryGetValueProfileForBytecodeOffset(int bytecodeOffset)
2808 {
2809     return tryBinarySearch<ValueProfile, int>(
2810         m_valueProfiles, m_valueProfiles.size(), bytecodeOffset,
2811         getValueProfileBytecodeOffset<ValueProfile>);
2812 }
2813
2814 ValueProfile& CodeBlock::valueProfileForBytecodeOffset(int bytecodeOffset)
2815 {
2816     OpcodeID opcodeID = Interpreter::getOpcodeID(instructions()[bytecodeOffset]);
2817     unsigned length = opcodeLength(opcodeID);
2818     ASSERT(!!tryGetValueProfileForBytecodeOffset(bytecodeOffset));
2819     return *instructions()[bytecodeOffset + length - 1].u.profile;
2820 }
2821
2822 void CodeBlock::validate()
2823 {
2824     BytecodeLivenessAnalysis liveness(this); // Compute directly from scratch so it doesn't effect CodeBlock footprint.
2825     
2826     FastBitVector liveAtHead = liveness.getLivenessInfoAtBytecodeOffset(this, 0);
2827     
2828     if (liveAtHead.numBits() != static_cast<size_t>(m_numCalleeLocals)) {
2829         beginValidationDidFail();
2830         dataLog("    Wrong number of bits in result!\n");
2831         dataLog("    Result: ", liveAtHead, "\n");
2832         dataLog("    Bit count: ", liveAtHead.numBits(), "\n");
2833         endValidationDidFail();
2834     }
2835     
2836     for (unsigned i = m_numCalleeLocals; i--;) {
2837         VirtualRegister reg = virtualRegisterForLocal(i);
2838         
2839         if (liveAtHead[i]) {
2840             beginValidationDidFail();
2841             dataLog("    Variable ", reg, " is expected to be dead.\n");
2842             dataLog("    Result: ", liveAtHead, "\n");
2843             endValidationDidFail();
2844         }
2845     }
2846
2847     for (unsigned i = 0; i + 1 < numberOfValueProfiles(); ++i) {
2848         if (valueProfile(i).m_bytecodeOffset > valueProfile(i + 1).m_bytecodeOffset) {
2849             beginValidationDidFail();
2850             dataLog("    Value profiles are not sorted.\n");
2851             endValidationDidFail();
2852         }
2853     }
2854      
2855     for (unsigned bytecodeOffset = 0; bytecodeOffset < m_instructions.size(); ) {
2856         OpcodeID opcode = Interpreter::getOpcodeID(m_instructions[bytecodeOffset]);
2857         if (!!baselineAlternative()->handlerForBytecodeOffset(bytecodeOffset)) {
2858             if (opcode == op_catch || opcode == op_enter) {
2859                 // op_catch/op_enter logically represent an entrypoint. Entrypoints are not allowed to be
2860                 // inside of a try block because they are responsible for bootstrapping state. And they
2861                 // are never allowed throw an exception because of this. We rely on this when compiling
2862                 // in the DFG. Because an entrypoint never throws, the bytecode generator will never
2863                 // allow once inside a try block.
2864                 beginValidationDidFail();
2865                 dataLog("    entrypoint not allowed inside a try block.");
2866                 endValidationDidFail();
2867             }
2868         }
2869         bytecodeOffset += opcodeLength(opcode);
2870     }
2871 }
2872
2873 void CodeBlock::beginValidationDidFail()
2874 {
2875     dataLog("Validation failure in ", *this, ":\n");
2876     dataLog("\n");
2877 }
2878
2879 void CodeBlock::endValidationDidFail()
2880 {
2881     dataLog("\n");
2882     dumpBytecode();
2883     dataLog("\n");
2884     dataLog("Validation failure.\n");
2885     RELEASE_ASSERT_NOT_REACHED();
2886 }
2887
2888 void CodeBlock::addBreakpoint(unsigned numBreakpoints)
2889 {
2890     m_numBreakpoints += numBreakpoints;
2891     ASSERT(m_numBreakpoints);
2892     if (JITCode::isOptimizingJIT(jitType()))
2893         jettison(Profiler::JettisonDueToDebuggerBreakpoint);
2894 }
2895
2896 void CodeBlock::setSteppingMode(CodeBlock::SteppingMode mode)
2897 {
2898     m_steppingMode = mode;
2899     if (mode == SteppingModeEnabled && JITCode::isOptimizingJIT(jitType()))
2900         jettison(Profiler::JettisonDueToDebuggerStepping);
2901 }
2902
2903 RareCaseProfile* CodeBlock::addRareCaseProfile(int bytecodeOffset)
2904 {
2905     m_rareCaseProfiles.append(RareCaseProfile(bytecodeOffset));
2906     return &m_rareCaseProfiles.last();
2907 }
2908
2909 RareCaseProfile* CodeBlock::rareCaseProfileForBytecodeOffset(int bytecodeOffset)
2910 {
2911     return tryBinarySearch<RareCaseProfile, int>(
2912         m_rareCaseProfiles, m_rareCaseProfiles.size(), bytecodeOffset,
2913         getRareCaseProfileBytecodeOffset);
2914 }
2915
2916 unsigned CodeBlock::rareCaseProfileCountForBytecodeOffset(int bytecodeOffset)
2917 {
2918     RareCaseProfile* profile = rareCaseProfileForBytecodeOffset(bytecodeOffset);
2919     if (profile)
2920         return profile->m_counter;
2921     return 0;
2922 }
2923
2924 ArithProfile* CodeBlock::arithProfileForBytecodeOffset(int bytecodeOffset)
2925 {
2926     return arithProfileForPC(&instructions()[bytecodeOffset]);
2927 }
2928
2929 ArithProfile* CodeBlock::arithProfileForPC(Instruction* pc)
2930 {
2931     auto opcodeID = Interpreter::getOpcodeID(pc[0]);
2932     switch (opcodeID) {
2933     case op_negate:
2934         return bitwise_cast<ArithProfile*>(&pc[3].u.operand);
2935     case op_bitor:
2936     case op_bitand:
2937     case op_bitxor:
2938     case op_add:
2939     case op_mul:
2940     case op_sub:
2941     case op_div:
2942         return bitwise_cast<ArithProfile*>(&pc[4].u.operand);
2943     default:
2944         break;
2945     }
2946
2947     return nullptr;
2948 }
2949
2950 bool CodeBlock::couldTakeSpecialFastCase(int bytecodeOffset)
2951 {
2952     if (!hasBaselineJITProfiling())
2953         return false;
2954     ArithProfile* profile = arithProfileForBytecodeOffset(bytecodeOffset);
2955     if (!profile)
2956         return false;
2957     return profile->tookSpecialFastPath();
2958 }
2959
2960 #if ENABLE(JIT)
2961 DFG::CapabilityLevel CodeBlock::capabilityLevel()
2962 {
2963     DFG::CapabilityLevel result = computeCapabilityLevel();
2964     m_capabilityLevelState = result;
2965     return result;
2966 }
2967 #endif
2968
2969 void CodeBlock::insertBasicBlockBoundariesForControlFlowProfiler(RefCountedArray<Instruction>& instructions)
2970 {
2971     if (!unlinkedCodeBlock()->hasOpProfileControlFlowBytecodeOffsets())
2972         return;
2973     const Vector<size_t>& bytecodeOffsets = unlinkedCodeBlock()->opProfileControlFlowBytecodeOffsets();
2974     for (size_t i = 0, offsetsLength = bytecodeOffsets.size(); i < offsetsLength; i++) {
2975         // Because op_profile_control_flow is emitted at the beginning of every basic block, finding 
2976         // the next op_profile_control_flow will give us the text range of a single basic block.
2977         size_t startIdx = bytecodeOffsets[i];
2978         RELEASE_ASSERT(Interpreter::getOpcodeID(instructions[startIdx]) == op_profile_control_flow);
2979         int basicBlockStartOffset = instructions[startIdx + 1].u.operand;
2980         int basicBlockEndOffset;
2981         if (i + 1 < offsetsLength) {
2982             size_t endIdx = bytecodeOffsets[i + 1];
2983             RELEASE_ASSERT(Interpreter::getOpcodeID(instructions[endIdx]) == op_profile_control_flow);
2984             basicBlockEndOffset = instructions[endIdx + 1].u.operand - 1;
2985         } else {
2986             basicBlockEndOffset = m_sourceOffset + ownerScriptExecutable()->source().length() - 1; // Offset before the closing brace.
2987             basicBlockStartOffset = std::min(basicBlockStartOffset, basicBlockEndOffset); // Some start offsets may be at the closing brace, ensure it is the offset before.
2988         }
2989
2990         // The following check allows for the same textual JavaScript basic block to have its bytecode emitted more
2991         // than once and still play nice with the control flow profiler. When basicBlockStartOffset is larger than 
2992         // basicBlockEndOffset, it indicates that the bytecode generator has emitted code for the same AST node 
2993         // more than once (for example: ForInNode, Finally blocks in TryNode, etc). Though these are different 
2994         // basic blocks at the bytecode level, they are generated from the same textual basic block in the JavaScript 
2995         // program. The condition: 
2996         // (basicBlockEndOffset < basicBlockStartOffset) 
2997         // is encountered when op_profile_control_flow lies across the boundary of these duplicated bytecode basic 
2998         // blocks and the textual offset goes from the end of the duplicated block back to the beginning. These 
2999         // ranges are dummy ranges and are ignored. The duplicated bytecode basic blocks point to the same 
3000         // internal data structure, so if any of them execute, it will record the same textual basic block in the 
3001         // JavaScript program as executing.
3002         // At the bytecode level, this situation looks like:
3003         // j: op_profile_control_flow (from j->k, we have basicBlockEndOffset < basicBlockStartOffset)
3004         // ...
3005         // k: op_profile_control_flow (we want to skip over the j->k block and start fresh at offset k as the start of a new basic block k->m).
3006         // ...
3007         // m: op_profile_control_flow
3008         if (basicBlockEndOffset < basicBlockStartOffset) {
3009             RELEASE_ASSERT(i + 1 < offsetsLength); // We should never encounter dummy blocks at the end of a CodeBlock.
3010             instructions[startIdx + 1].u.basicBlockLocation = vm()->controlFlowProfiler()->dummyBasicBlock();
3011             continue;
3012         }
3013
3014         BasicBlockLocation* basicBlockLocation = vm()->controlFlowProfiler()->getBasicBlockLocation(ownerScriptExecutable()->sourceID(), basicBlockStartOffset, basicBlockEndOffset);
3015
3016         // Find all functions that are enclosed within the range: [basicBlockStartOffset, basicBlockEndOffset]
3017         // and insert these functions' start/end offsets as gaps in the current BasicBlockLocation.
3018         // This is necessary because in the original source text of a JavaScript program, 
3019         // function literals form new basic blocks boundaries, but they aren't represented 
3020         // inside the CodeBlock's instruction stream.
3021         auto insertFunctionGaps = [basicBlockLocation, basicBlockStartOffset, basicBlockEndOffset] (const WriteBarrier<FunctionExecutable>& functionExecutable) {
3022             const UnlinkedFunctionExecutable* executable = functionExecutable->unlinkedExecutable();
3023             int functionStart = executable->typeProfilingStartOffset();
3024             int functionEnd = executable->typeProfilingEndOffset();
3025             if (functionStart >= basicBlockStartOffset && functionEnd <= basicBlockEndOffset)
3026                 basicBlockLocation->insertGap(functionStart, functionEnd);
3027         };
3028
3029         for (const WriteBarrier<FunctionExecutable>& executable : m_functionDecls)
3030             insertFunctionGaps(executable);
3031         for (const WriteBarrier<FunctionExecutable>& executable : m_functionExprs)
3032             insertFunctionGaps(executable);
3033
3034         instructions[startIdx + 1].u.basicBlockLocation = basicBlockLocation;
3035     }
3036 }
3037
3038 #if ENABLE(JIT)
3039 void CodeBlock::setPCToCodeOriginMap(std::unique_ptr<PCToCodeOriginMap>&& map) 
3040
3041     m_pcToCodeOriginMap = WTFMove(map);
3042 }
3043
3044 std::optional<CodeOrigin> CodeBlock::findPC(void* pc)
3045 {
3046     if (m_pcToCodeOriginMap) {
3047         if (std::optional<CodeOrigin> codeOrigin = m_pcToCodeOriginMap->findPC(pc))
3048             return codeOrigin;
3049     }
3050
3051     for (auto iter = m_stubInfos.begin(); !!iter; ++iter) {
3052         StructureStubInfo* stub = *iter;
3053         if (stub->containsPC(pc))
3054             return std::optional<CodeOrigin>(stub->codeOrigin);
3055     }
3056
3057     if (std::optional<CodeOrigin> codeOrigin = m_jitCode->findPC(this, pc))
3058         return codeOrigin;
3059
3060     return std::nullopt;
3061 }
3062 #endif // ENABLE(JIT)
3063
3064 std::optional<unsigned> CodeBlock::bytecodeOffsetFromCallSiteIndex(CallSiteIndex callSiteIndex)
3065 {
3066     std::optional<unsigned> bytecodeOffset;
3067     JITCode::JITType jitType = this->jitType();
3068     if (jitType == JITCode::InterpreterThunk || jitType == JITCode::BaselineJIT) {
3069 #if USE(JSVALUE64)
3070         bytecodeOffset = callSiteIndex.bits();
3071 #else
3072         Instruction* instruction = bitwise_cast<Instruction*>(callSiteIndex.bits());
3073         bytecodeOffset = this->bytecodeOffset(instruction);
3074 #endif
3075     } else if (jitType == JITCode::DFGJIT || jitType == JITCode::FTLJIT) {
3076 #if ENABLE(DFG_JIT)
3077         RELEASE_ASSERT(canGetCodeOrigin(callSiteIndex));
3078         CodeOrigin origin = codeOrigin(callSiteIndex);
3079         bytecodeOffset = origin.bytecodeIndex;
3080 #else
3081         RELEASE_ASSERT_NOT_REACHED();
3082 #endif
3083     }
3084
3085     return bytecodeOffset;
3086 }
3087
3088 int32_t CodeBlock::thresholdForJIT(int32_t threshold)
3089 {
3090     switch (unlinkedCodeBlock()->didOptimize()) {
3091     case MixedTriState:
3092         return threshold;
3093     case FalseTriState:
3094         return threshold * 4;
3095     case TrueTriState:
3096         return threshold / 2;
3097     }
3098     ASSERT_NOT_REACHED();
3099     return threshold;
3100 }
3101
3102 void CodeBlock::jitAfterWarmUp()
3103 {
3104     m_llintExecuteCounter.setNewThreshold(thresholdForJIT(Options::thresholdForJITAfterWarmUp()), this);
3105 }
3106
3107 void CodeBlock::jitSoon()
3108 {
3109     m_llintExecuteCounter.setNewThreshold(thresholdForJIT(Options::thresholdForJITSoon()), this);
3110 }
3111
3112 bool CodeBlock::hasInstalledVMTrapBreakpoints() const
3113 {
3114 #if ENABLE(SIGNAL_BASED_VM_TRAPS)
3115     // This function may be called from a signal handler. We need to be
3116     // careful to not call anything that is not signal handler safe, e.g.
3117     // we should not perturb the refCount of m_jitCode.
3118     if (!JITCode::isOptimizingJIT(jitType()))
3119         return false;
3120     return m_jitCode->dfgCommon()->hasInstalledVMTrapsBreakpoints();
3121 #else
3122     return false;
3123 #endif
3124 }
3125
3126 bool CodeBlock::installVMTrapBreakpoints()
3127 {
3128 #if ENABLE(SIGNAL_BASED_VM_TRAPS)
3129     // This function may be called from a signal handler. We need to be
3130     // careful to not call anything that is not signal handler safe, e.g.
3131     // we should not perturb the refCount of m_jitCode.
3132     if (!JITCode::isOptimizingJIT(jitType()))
3133         return false;
3134     auto& commonData = *m_jitCode->dfgCommon();
3135     commonData.installVMTrapBreakpoints(this);
3136     return true;
3137 #else
3138     UNREACHABLE_FOR_PLATFORM();
3139     return false;
3140 #endif
3141 }
3142
3143 void CodeBlock::dumpMathICStats()
3144 {
3145 #if ENABLE(MATH_IC_STATS)
3146     double numAdds = 0.0;
3147     double totalAddSize = 0.0;
3148     double numMuls = 0.0;
3149     double totalMulSize = 0.0;
3150     double numNegs = 0.0;
3151     double totalNegSize = 0.0;
3152     double numSubs = 0.0;
3153     double totalSubSize = 0.0;
3154
3155     auto countICs = [&] (CodeBlock* codeBlock) {
3156         for (JITAddIC* addIC : codeBlock->m_addICs) {
3157             numAdds++;
3158             totalAddSize += addIC->codeSize();
3159         }
3160
3161         for (JITMulIC* mulIC : codeBlock->m_mulICs) {
3162             numMuls++;
3163             totalMulSize += mulIC->codeSize();
3164         }
3165
3166         for (JITNegIC* negIC : codeBlock->m_negICs) {
3167             numNegs++;
3168             totalNegSize += negIC->codeSize();
3169         }
3170
3171         for (JITSubIC* subIC : codeBlock->m_subICs) {
3172             numSubs++;
3173             totalSubSize += subIC->codeSize();
3174         }
3175     };
3176     heap()->forEachCodeBlock(countICs);
3177
3178     dataLog("Num Adds: ", numAdds, "\n");
3179     dataLog("Total Add size in bytes: ", totalAddSize, "\n");
3180     dataLog("Average Add size: ", totalAddSize / numAdds, "\n");
3181     dataLog("\n");
3182     dataLog("Num Muls: ", numMuls, "\n");
3183     dataLog("Total Mul size in bytes: ", totalMulSize, "\n");
3184     dataLog("Average Mul size: ", totalMulSize / numMuls, "\n");
3185     dataLog("\n");
3186     dataLog("Num Negs: ", numNegs, "\n");
3187     dataLog("Total Neg size in bytes: ", totalNegSize, "\n");
3188     dataLog("Average Neg size: ", totalNegSize / numNegs, "\n");
3189     dataLog("\n");
3190     dataLog("Num Subs: ", numSubs, "\n");
3191     dataLog("Total Sub size in bytes: ", totalSubSize, "\n");
3192     dataLog("Average Sub size: ", totalSubSize / numSubs, "\n");
3193
3194     dataLog("-----------------------\n");
3195 #endif
3196 }
3197
3198 void setPrinter(Printer::PrintRecord& record, CodeBlock* codeBlock)
3199 {
3200     Printer::setPrinter(record, toCString(codeBlock));
3201 }
3202
3203 } // namespace JSC
3204
3205 namespace WTF {
3206     
3207 void printInternal(PrintStream& out, JSC::CodeBlock* codeBlock)
3208 {
3209     if (UNLIKELY(!codeBlock)) {
3210         out.print("<null codeBlock>");
3211         return;
3212     }
3213     out.print(*codeBlock);
3214 }
3215     
3216 } // namespace WTF