CodeBlock::baselineVersion() should account for executables with purged codeBlocks.
[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     JITCode::JITType selfJITType = jitType();
1641     if (JITCode::isBaselineCode(selfJITType))
1642         return this;
1643     CodeBlock* result = replacement();
1644     if (!result) {
1645         if (JITCode::isOptimizingJIT(selfJITType)) {
1646             // The replacement can be null if we've had a memory clean up and the executable
1647             // has been purged of its codeBlocks (see ExecutableBase::clearCode()). Regardless,
1648             // the current codeBlock is still live on the stack, and as an optimizing JIT
1649             // codeBlock, it will keep its baselineAlternative() alive for us to fetch below.
1650             result = this;
1651         } else {
1652             // This can happen if we're creating the original CodeBlock for an executable.
1653             // Assume that we're the baseline CodeBlock.
1654             RELEASE_ASSERT(selfJITType == JITCode::None);
1655             return this;
1656         }
1657     }
1658     result = result->baselineAlternative();
1659     ASSERT(result);
1660     return result;
1661 #else
1662     return this;
1663 #endif
1664 }
1665
1666 #if ENABLE(JIT)
1667 bool CodeBlock::hasOptimizedReplacement(JITCode::JITType typeToReplace)
1668 {
1669     CodeBlock* replacement = this->replacement();
1670     return replacement && JITCode::isHigherTier(replacement->jitType(), typeToReplace);
1671 }
1672
1673 bool CodeBlock::hasOptimizedReplacement()
1674 {
1675     return hasOptimizedReplacement(jitType());
1676 }
1677 #endif
1678
1679 HandlerInfo* CodeBlock::handlerForBytecodeOffset(unsigned bytecodeOffset, RequiredHandler requiredHandler)
1680 {
1681     RELEASE_ASSERT(bytecodeOffset < instructions().size());
1682     return handlerForIndex(bytecodeOffset, requiredHandler);
1683 }
1684
1685 HandlerInfo* CodeBlock::handlerForIndex(unsigned index, RequiredHandler requiredHandler)
1686 {
1687     if (!m_rareData)
1688         return 0;
1689     return HandlerInfo::handlerForIndex(m_rareData->m_exceptionHandlers, index, requiredHandler);
1690 }
1691
1692 CallSiteIndex CodeBlock::newExceptionHandlingCallSiteIndex(CallSiteIndex originalCallSite)
1693 {
1694 #if ENABLE(DFG_JIT)
1695     RELEASE_ASSERT(JITCode::isOptimizingJIT(jitType()));
1696     RELEASE_ASSERT(canGetCodeOrigin(originalCallSite));
1697     ASSERT(!!handlerForIndex(originalCallSite.bits()));
1698     CodeOrigin originalOrigin = codeOrigin(originalCallSite);
1699     return m_jitCode->dfgCommon()->addUniqueCallSiteIndex(originalOrigin);
1700 #else
1701     // We never create new on-the-fly exception handling
1702     // call sites outside the DFG/FTL inline caches.
1703     UNUSED_PARAM(originalCallSite);
1704     RELEASE_ASSERT_NOT_REACHED();
1705     return CallSiteIndex(0u);
1706 #endif
1707 }
1708
1709 void CodeBlock::ensureCatchLivenessIsComputedForBytecodeOffsetSlow(unsigned bytecodeOffset)
1710 {
1711     ASSERT(Interpreter::getOpcodeID(m_instructions[bytecodeOffset]) == op_catch);
1712     BytecodeLivenessAnalysis& bytecodeLiveness = livenessAnalysis();
1713
1714     // We get the live-out set of variables at op_catch, not the live-in. This
1715     // is because the variables that the op_catch defines might be dead, and
1716     // we can avoid profiling them and extracting them when doing OSR entry
1717     // into the DFG.
1718     FastBitVector liveLocals = bytecodeLiveness.getLivenessInfoAtBytecodeOffset(this, bytecodeOffset + OPCODE_LENGTH(op_catch));
1719     Vector<VirtualRegister> liveOperands;
1720     liveOperands.reserveInitialCapacity(liveLocals.bitCount());
1721     liveLocals.forEachSetBit([&] (unsigned liveLocal) {
1722         liveOperands.append(virtualRegisterForLocal(liveLocal));
1723     });
1724
1725     for (int i = 0; i < numParameters(); ++i)
1726         liveOperands.append(virtualRegisterForArgument(i));
1727
1728     auto profiles = std::make_unique<ValueProfileAndOperandBuffer>(liveOperands.size());
1729     RELEASE_ASSERT(profiles->m_size == liveOperands.size());
1730     for (unsigned i = 0; i < profiles->m_size; ++i)
1731         profiles->m_buffer.get()[i].m_operand = liveOperands[i].offset();
1732
1733     // The compiler thread will read this pointer value and then proceed to dereference it
1734     // if it is not null. We need to make sure all above stores happen before this store so
1735     // the compiler thread reads fully initialized data.
1736     WTF::storeStoreFence(); 
1737
1738     m_instructions[bytecodeOffset + 3].u.pointer = profiles.get();
1739
1740     {
1741         ConcurrentJSLocker locker(m_lock);
1742         m_catchProfiles.append(WTFMove(profiles));
1743     }
1744 }
1745
1746 void CodeBlock::removeExceptionHandlerForCallSite(CallSiteIndex callSiteIndex)
1747 {
1748     RELEASE_ASSERT(m_rareData);
1749     Vector<HandlerInfo>& exceptionHandlers = m_rareData->m_exceptionHandlers;
1750     unsigned index = callSiteIndex.bits();
1751     for (size_t i = 0; i < exceptionHandlers.size(); ++i) {
1752         HandlerInfo& handler = exceptionHandlers[i];
1753         if (handler.start <= index && handler.end > index) {
1754             exceptionHandlers.remove(i);
1755             return;
1756         }
1757     }
1758
1759     RELEASE_ASSERT_NOT_REACHED();
1760 }
1761
1762 unsigned CodeBlock::lineNumberForBytecodeOffset(unsigned bytecodeOffset)
1763 {
1764     RELEASE_ASSERT(bytecodeOffset < instructions().size());
1765     return ownerScriptExecutable()->firstLine() + m_unlinkedCode->lineNumberForBytecodeOffset(bytecodeOffset);
1766 }
1767
1768 unsigned CodeBlock::columnNumberForBytecodeOffset(unsigned bytecodeOffset)
1769 {
1770     int divot;
1771     int startOffset;
1772     int endOffset;
1773     unsigned line;
1774     unsigned column;
1775     expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
1776     return column;
1777 }
1778
1779 void CodeBlock::expressionRangeForBytecodeOffset(unsigned bytecodeOffset, int& divot, int& startOffset, int& endOffset, unsigned& line, unsigned& column) const
1780 {
1781     m_unlinkedCode->expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
1782     divot += m_sourceOffset;
1783     column += line ? 1 : firstLineColumnOffset();
1784     line += ownerScriptExecutable()->firstLine();
1785 }
1786
1787 bool CodeBlock::hasOpDebugForLineAndColumn(unsigned line, unsigned column)
1788 {
1789     const Instruction* begin = instructions().begin();
1790     const Instruction* end = instructions().end();
1791     for (const Instruction* it = begin; it != end;) {
1792         OpcodeID opcodeID = Interpreter::getOpcodeID(*it);
1793         if (opcodeID == op_debug) {
1794             unsigned bytecodeOffset = it - begin;
1795             int unused;
1796             unsigned opDebugLine;
1797             unsigned opDebugColumn;
1798             expressionRangeForBytecodeOffset(bytecodeOffset, unused, unused, unused, opDebugLine, opDebugColumn);
1799             if (line == opDebugLine && (column == Breakpoint::unspecifiedColumn || column == opDebugColumn))
1800                 return true;
1801         }
1802         it += opcodeLengths[opcodeID];
1803     }
1804     return false;
1805 }
1806
1807 void CodeBlock::shrinkToFit(ShrinkMode shrinkMode)
1808 {
1809     ConcurrentJSLocker locker(m_lock);
1810
1811     m_rareCaseProfiles.shrinkToFit();
1812     
1813     if (shrinkMode == EarlyShrink) {
1814         m_constantRegisters.shrinkToFit();
1815         m_constantsSourceCodeRepresentation.shrinkToFit();
1816         
1817         if (m_rareData) {
1818             m_rareData->m_switchJumpTables.shrinkToFit();
1819             m_rareData->m_stringSwitchJumpTables.shrinkToFit();
1820         }
1821     } // else don't shrink these, because we would have already pointed pointers into these tables.
1822 }
1823
1824 #if ENABLE(JIT)
1825 void CodeBlock::linkIncomingCall(ExecState* callerFrame, CallLinkInfo* incoming)
1826 {
1827     noticeIncomingCall(callerFrame);
1828     m_incomingCalls.push(incoming);
1829 }
1830
1831 void CodeBlock::linkIncomingPolymorphicCall(ExecState* callerFrame, PolymorphicCallNode* incoming)
1832 {
1833     noticeIncomingCall(callerFrame);
1834     m_incomingPolymorphicCalls.push(incoming);
1835 }
1836 #endif // ENABLE(JIT)
1837
1838 void CodeBlock::unlinkIncomingCalls()
1839 {
1840     while (m_incomingLLIntCalls.begin() != m_incomingLLIntCalls.end())
1841         m_incomingLLIntCalls.begin()->unlink();
1842 #if ENABLE(JIT)
1843     while (m_incomingCalls.begin() != m_incomingCalls.end())
1844         m_incomingCalls.begin()->unlink(*vm());
1845     while (m_incomingPolymorphicCalls.begin() != m_incomingPolymorphicCalls.end())
1846         m_incomingPolymorphicCalls.begin()->unlink(*vm());
1847 #endif // ENABLE(JIT)
1848 }
1849
1850 void CodeBlock::linkIncomingCall(ExecState* callerFrame, LLIntCallLinkInfo* incoming)
1851 {
1852     noticeIncomingCall(callerFrame);
1853     m_incomingLLIntCalls.push(incoming);
1854 }
1855
1856 CodeBlock* CodeBlock::newReplacement()
1857 {
1858     return ownerScriptExecutable()->newReplacementCodeBlockFor(specializationKind());
1859 }
1860
1861 #if ENABLE(JIT)
1862 CodeBlock* CodeBlock::replacement()
1863 {
1864     const ClassInfo* classInfo = this->classInfo(*vm());
1865
1866     if (classInfo == FunctionCodeBlock::info())
1867         return jsCast<FunctionExecutable*>(ownerExecutable())->codeBlockFor(m_isConstructor ? CodeForConstruct : CodeForCall);
1868
1869     if (classInfo == EvalCodeBlock::info())
1870         return jsCast<EvalExecutable*>(ownerExecutable())->codeBlock();
1871
1872     if (classInfo == ProgramCodeBlock::info())
1873         return jsCast<ProgramExecutable*>(ownerExecutable())->codeBlock();
1874
1875     if (classInfo == ModuleProgramCodeBlock::info())
1876         return jsCast<ModuleProgramExecutable*>(ownerExecutable())->codeBlock();
1877
1878     RELEASE_ASSERT_NOT_REACHED();
1879     return nullptr;
1880 }
1881
1882 DFG::CapabilityLevel CodeBlock::computeCapabilityLevel()
1883 {
1884     const ClassInfo* classInfo = this->classInfo(*vm());
1885
1886     if (classInfo == FunctionCodeBlock::info()) {
1887         if (m_isConstructor)
1888             return DFG::functionForConstructCapabilityLevel(this);
1889         return DFG::functionForCallCapabilityLevel(this);
1890     }
1891
1892     if (classInfo == EvalCodeBlock::info())
1893         return DFG::evalCapabilityLevel(this);
1894
1895     if (classInfo == ProgramCodeBlock::info())
1896         return DFG::programCapabilityLevel(this);
1897
1898     if (classInfo == ModuleProgramCodeBlock::info())
1899         return DFG::programCapabilityLevel(this);
1900
1901     RELEASE_ASSERT_NOT_REACHED();
1902     return DFG::CannotCompile;
1903 }
1904
1905 #endif // ENABLE(JIT)
1906
1907 void CodeBlock::jettison(Profiler::JettisonReason reason, ReoptimizationMode mode, const FireDetail* detail)
1908 {
1909 #if !ENABLE(DFG_JIT)
1910     UNUSED_PARAM(mode);
1911     UNUSED_PARAM(detail);
1912 #endif
1913     
1914     CODEBLOCK_LOG_EVENT(this, "jettison", ("due to ", reason, ", counting = ", mode == CountReoptimization, ", detail = ", pointerDump(detail)));
1915
1916     RELEASE_ASSERT(reason != Profiler::NotJettisoned);
1917     
1918 #if ENABLE(DFG_JIT)
1919     if (DFG::shouldDumpDisassembly()) {
1920         dataLog("Jettisoning ", *this);
1921         if (mode == CountReoptimization)
1922             dataLog(" and counting reoptimization");
1923         dataLog(" due to ", reason);
1924         if (detail)
1925             dataLog(", ", *detail);
1926         dataLog(".\n");
1927     }
1928     
1929     if (reason == Profiler::JettisonDueToWeakReference) {
1930         if (DFG::shouldDumpDisassembly()) {
1931             dataLog(*this, " will be jettisoned because of the following dead references:\n");
1932             DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
1933             for (auto& transition : dfgCommon->transitions) {
1934                 JSCell* origin = transition.m_codeOrigin.get();
1935                 JSCell* from = transition.m_from.get();
1936                 JSCell* to = transition.m_to.get();
1937                 if ((!origin || Heap::isMarked(origin)) && Heap::isMarked(from))
1938                     continue;
1939                 dataLog("    Transition under ", RawPointer(origin), ", ", RawPointer(from), " -> ", RawPointer(to), ".\n");
1940             }
1941             for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
1942                 JSCell* weak = dfgCommon->weakReferences[i].get();
1943                 if (Heap::isMarked(weak))
1944                     continue;
1945                 dataLog("    Weak reference ", RawPointer(weak), ".\n");
1946             }
1947         }
1948     }
1949 #endif // ENABLE(DFG_JIT)
1950
1951     VM& vm = *m_poisonedVM;
1952     DeferGCForAWhile deferGC(*heap());
1953     
1954     // We want to accomplish two things here:
1955     // 1) Make sure that if this CodeBlock is on the stack right now, then if we return to it
1956     //    we should OSR exit at the top of the next bytecode instruction after the return.
1957     // 2) Make sure that if we call the owner executable, then we shouldn't call this CodeBlock.
1958
1959 #if ENABLE(DFG_JIT)
1960     if (reason != Profiler::JettisonDueToOldAge) {
1961         Profiler::Compilation* compilation = jitCode()->dfgCommon()->compilation.get();
1962         if (UNLIKELY(compilation))
1963             compilation->setJettisonReason(reason, detail);
1964         
1965         // This accomplishes (1), and does its own book-keeping about whether it has already happened.
1966         if (!jitCode()->dfgCommon()->invalidate()) {
1967             // We've already been invalidated.
1968             RELEASE_ASSERT(this != replacement() || (vm.heap.isCurrentThreadBusy() && !Heap::isMarked(ownerScriptExecutable())));
1969             return;
1970         }
1971     }
1972     
1973     if (DFG::shouldDumpDisassembly())
1974         dataLog("    Did invalidate ", *this, "\n");
1975     
1976     // Count the reoptimization if that's what the user wanted.
1977     if (mode == CountReoptimization) {
1978         // FIXME: Maybe this should call alternative().
1979         // https://bugs.webkit.org/show_bug.cgi?id=123677
1980         baselineAlternative()->countReoptimization();
1981         if (DFG::shouldDumpDisassembly())
1982             dataLog("    Did count reoptimization for ", *this, "\n");
1983     }
1984     
1985     if (this != replacement()) {
1986         // This means that we were never the entrypoint. This can happen for OSR entry code
1987         // blocks.
1988         return;
1989     }
1990
1991     if (alternative())
1992         alternative()->optimizeAfterWarmUp();
1993
1994     if (reason != Profiler::JettisonDueToOldAge && reason != Profiler::JettisonDueToVMTraps)
1995         tallyFrequentExitSites();
1996 #endif // ENABLE(DFG_JIT)
1997
1998     // Jettison can happen during GC. We don't want to install code to a dead executable
1999     // because that would add a dead object to the remembered set.
2000     if (vm.heap.isCurrentThreadBusy() && !Heap::isMarked(ownerScriptExecutable()))
2001         return;
2002
2003     // This accomplishes (2).
2004     ownerScriptExecutable()->installCode(vm, alternative(), codeType(), specializationKind());
2005
2006 #if ENABLE(DFG_JIT)
2007     if (DFG::shouldDumpDisassembly())
2008         dataLog("    Did install baseline version of ", *this, "\n");
2009 #endif // ENABLE(DFG_JIT)
2010 }
2011
2012 JSGlobalObject* CodeBlock::globalObjectFor(CodeOrigin codeOrigin)
2013 {
2014     if (!codeOrigin.inlineCallFrame)
2015         return globalObject();
2016     return codeOrigin.inlineCallFrame->baselineCodeBlock->globalObject();
2017 }
2018
2019 class RecursionCheckFunctor {
2020 public:
2021     RecursionCheckFunctor(CallFrame* startCallFrame, CodeBlock* codeBlock, unsigned depthToCheck)
2022         : m_startCallFrame(startCallFrame)
2023         , m_codeBlock(codeBlock)
2024         , m_depthToCheck(depthToCheck)
2025         , m_foundStartCallFrame(false)
2026         , m_didRecurse(false)
2027     { }
2028
2029     StackVisitor::Status operator()(StackVisitor& visitor) const
2030     {
2031         CallFrame* currentCallFrame = visitor->callFrame();
2032
2033         if (currentCallFrame == m_startCallFrame)
2034             m_foundStartCallFrame = true;
2035
2036         if (m_foundStartCallFrame) {
2037             if (visitor->callFrame()->codeBlock() == m_codeBlock) {
2038                 m_didRecurse = true;
2039                 return StackVisitor::Done;
2040             }
2041
2042             if (!m_depthToCheck--)
2043                 return StackVisitor::Done;
2044         }
2045
2046         return StackVisitor::Continue;
2047     }
2048
2049     bool didRecurse() const { return m_didRecurse; }
2050
2051 private:
2052     CallFrame* m_startCallFrame;
2053     CodeBlock* m_codeBlock;
2054     mutable unsigned m_depthToCheck;
2055     mutable bool m_foundStartCallFrame;
2056     mutable bool m_didRecurse;
2057 };
2058
2059 void CodeBlock::noticeIncomingCall(ExecState* callerFrame)
2060 {
2061     CodeBlock* callerCodeBlock = callerFrame->codeBlock();
2062     
2063     if (Options::verboseCallLink())
2064         dataLog("Noticing call link from ", pointerDump(callerCodeBlock), " to ", *this, "\n");
2065     
2066 #if ENABLE(DFG_JIT)
2067     if (!m_shouldAlwaysBeInlined)
2068         return;
2069     
2070     if (!callerCodeBlock) {
2071         m_shouldAlwaysBeInlined = false;
2072         if (Options::verboseCallLink())
2073             dataLog("    Clearing SABI because caller is native.\n");
2074         return;
2075     }
2076
2077     if (!hasBaselineJITProfiling())
2078         return;
2079
2080     if (!DFG::mightInlineFunction(this))
2081         return;
2082
2083     if (!canInline(capabilityLevelState()))
2084         return;
2085     
2086     if (!DFG::isSmallEnoughToInlineCodeInto(callerCodeBlock)) {
2087         m_shouldAlwaysBeInlined = false;
2088         if (Options::verboseCallLink())
2089             dataLog("    Clearing SABI because caller is too large.\n");
2090         return;
2091     }
2092
2093     if (callerCodeBlock->jitType() == JITCode::InterpreterThunk) {
2094         // If the caller is still in the interpreter, then we can't expect inlining to
2095         // happen anytime soon. Assume it's profitable to optimize it separately. This
2096         // ensures that a function is SABI only if it is called no more frequently than
2097         // any of its callers.
2098         m_shouldAlwaysBeInlined = false;
2099         if (Options::verboseCallLink())
2100             dataLog("    Clearing SABI because caller is in LLInt.\n");
2101         return;
2102     }
2103     
2104     if (JITCode::isOptimizingJIT(callerCodeBlock->jitType())) {
2105         m_shouldAlwaysBeInlined = false;
2106         if (Options::verboseCallLink())
2107             dataLog("    Clearing SABI bcause caller was already optimized.\n");
2108         return;
2109     }
2110     
2111     if (callerCodeBlock->codeType() != FunctionCode) {
2112         // If the caller is either eval or global code, assume that that won't be
2113         // optimized anytime soon. For eval code this is particularly true since we
2114         // delay eval optimization by a *lot*.
2115         m_shouldAlwaysBeInlined = false;
2116         if (Options::verboseCallLink())
2117             dataLog("    Clearing SABI because caller is not a function.\n");
2118         return;
2119     }
2120
2121     // Recursive calls won't be inlined.
2122     RecursionCheckFunctor functor(callerFrame, this, Options::maximumInliningDepth());
2123     vm()->topCallFrame->iterate(functor);
2124
2125     if (functor.didRecurse()) {
2126         if (Options::verboseCallLink())
2127             dataLog("    Clearing SABI because recursion was detected.\n");
2128         m_shouldAlwaysBeInlined = false;
2129         return;
2130     }
2131     
2132     if (callerCodeBlock->capabilityLevelState() == DFG::CapabilityLevelNotSet) {
2133         dataLog("In call from ", FullCodeOrigin(callerCodeBlock, callerFrame->codeOrigin()), " to ", *this, ": caller's DFG capability level is not set.\n");
2134         CRASH();
2135     }
2136     
2137     if (canCompile(callerCodeBlock->capabilityLevelState()))
2138         return;
2139     
2140     if (Options::verboseCallLink())
2141         dataLog("    Clearing SABI because the caller is not a DFG candidate.\n");
2142     
2143     m_shouldAlwaysBeInlined = false;
2144 #endif
2145 }
2146
2147 unsigned CodeBlock::reoptimizationRetryCounter() const
2148 {
2149 #if ENABLE(JIT)
2150     ASSERT(m_reoptimizationRetryCounter <= Options::reoptimizationRetryCounterMax());
2151     return m_reoptimizationRetryCounter;
2152 #else
2153     return 0;
2154 #endif // ENABLE(JIT)
2155 }
2156
2157 #if ENABLE(JIT)
2158 void CodeBlock::setCalleeSaveRegisters(RegisterSet calleeSaveRegisters)
2159 {
2160     m_calleeSaveRegisters = std::make_unique<RegisterAtOffsetList>(calleeSaveRegisters);
2161 }
2162
2163 void CodeBlock::setCalleeSaveRegisters(std::unique_ptr<RegisterAtOffsetList> registerAtOffsetList)
2164 {
2165     m_calleeSaveRegisters = WTFMove(registerAtOffsetList);
2166 }
2167     
2168 static size_t roundCalleeSaveSpaceAsVirtualRegisters(size_t calleeSaveRegisters)
2169 {
2170     static const unsigned cpuRegisterSize = sizeof(void*);
2171     return (WTF::roundUpToMultipleOf(sizeof(Register), calleeSaveRegisters * cpuRegisterSize) / sizeof(Register));
2172
2173 }
2174
2175 size_t CodeBlock::llintBaselineCalleeSaveSpaceAsVirtualRegisters()
2176 {
2177     return roundCalleeSaveSpaceAsVirtualRegisters(numberOfLLIntBaselineCalleeSaveRegisters());
2178 }
2179
2180 size_t CodeBlock::calleeSaveSpaceAsVirtualRegisters()
2181 {
2182     return roundCalleeSaveSpaceAsVirtualRegisters(m_calleeSaveRegisters->size());
2183 }
2184
2185 void CodeBlock::countReoptimization()
2186 {
2187     m_reoptimizationRetryCounter++;
2188     if (m_reoptimizationRetryCounter > Options::reoptimizationRetryCounterMax())
2189         m_reoptimizationRetryCounter = Options::reoptimizationRetryCounterMax();
2190 }
2191
2192 unsigned CodeBlock::numberOfDFGCompiles()
2193 {
2194     ASSERT(JITCode::isBaselineCode(jitType()));
2195     if (Options::testTheFTL()) {
2196         if (m_didFailFTLCompilation)
2197             return 1000000;
2198         return (m_hasBeenCompiledWithFTL ? 1 : 0) + m_reoptimizationRetryCounter;
2199     }
2200     CodeBlock* replacement = this->replacement();
2201     return ((replacement && JITCode::isOptimizingJIT(replacement->jitType())) ? 1 : 0) + m_reoptimizationRetryCounter;
2202 }
2203
2204 int32_t CodeBlock::codeTypeThresholdMultiplier() const
2205 {
2206     if (codeType() == EvalCode)
2207         return Options::evalThresholdMultiplier();
2208     
2209     return 1;
2210 }
2211
2212 double CodeBlock::optimizationThresholdScalingFactor()
2213 {
2214     // This expression arises from doing a least-squares fit of
2215     //
2216     // F[x_] =: a * Sqrt[x + b] + Abs[c * x] + d
2217     //
2218     // against the data points:
2219     //
2220     //    x       F[x_]
2221     //    10       0.9          (smallest reasonable code block)
2222     //   200       1.0          (typical small-ish code block)
2223     //   320       1.2          (something I saw in 3d-cube that I wanted to optimize)
2224     //  1268       5.0          (something I saw in 3d-cube that I didn't want to optimize)
2225     //  4000       5.5          (random large size, used to cause the function to converge to a shallow curve of some sort)
2226     // 10000       6.0          (similar to above)
2227     //
2228     // I achieve the minimization using the following Mathematica code:
2229     //
2230     // MyFunctionTemplate[x_, a_, b_, c_, d_] := a*Sqrt[x + b] + Abs[c*x] + d
2231     //
2232     // samples = {{10, 0.9}, {200, 1}, {320, 1.2}, {1268, 5}, {4000, 5.5}, {10000, 6}}
2233     //
2234     // solution = 
2235     //     Minimize[Plus @@ ((MyFunctionTemplate[#[[1]], a, b, c, d] - #[[2]])^2 & /@ samples),
2236     //         {a, b, c, d}][[2]]
2237     //
2238     // And the code below (to initialize a, b, c, d) is generated by:
2239     //
2240     // Print["const double " <> ToString[#[[1]]] <> " = " <>
2241     //     If[#[[2]] < 0.00001, "0.0", ToString[#[[2]]]] <> ";"] & /@ solution
2242     //
2243     // We've long known the following to be true:
2244     // - Small code blocks are cheap to optimize and so we should do it sooner rather
2245     //   than later.
2246     // - Large code blocks are expensive to optimize and so we should postpone doing so,
2247     //   and sometimes have a large enough threshold that we never optimize them.
2248     // - The difference in cost is not totally linear because (a) just invoking the
2249     //   DFG incurs some base cost and (b) for large code blocks there is enough slop
2250     //   in the correlation between instruction count and the actual compilation cost
2251     //   that for those large blocks, the instruction count should not have a strong
2252     //   influence on our threshold.
2253     //
2254     // I knew the goals but I didn't know how to achieve them; so I picked an interesting
2255     // example where the heuristics were right (code block in 3d-cube with instruction
2256     // count 320, which got compiled early as it should have been) and one where they were
2257     // totally wrong (code block in 3d-cube with instruction count 1268, which was expensive
2258     // to compile and didn't run often enough to warrant compilation in my opinion), and
2259     // then threw in additional data points that represented my own guess of what our
2260     // heuristics should do for some round-numbered examples.
2261     //
2262     // The expression to which I decided to fit the data arose because I started with an
2263     // affine function, and then did two things: put the linear part in an Abs to ensure
2264     // that the fit didn't end up choosing a negative value of c (which would result in
2265     // the function turning over and going negative for large x) and I threw in a Sqrt
2266     // term because Sqrt represents my intution that the function should be more sensitive
2267     // to small changes in small values of x, but less sensitive when x gets large.
2268     
2269     // Note that the current fit essentially eliminates the linear portion of the
2270     // expression (c == 0.0).
2271     const double a = 0.061504;
2272     const double b = 1.02406;
2273     const double c = 0.0;
2274     const double d = 0.825914;
2275     
2276     double instructionCount = this->instructionCount();
2277     
2278     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.
2279     
2280     double result = d + a * sqrt(instructionCount + b) + c * instructionCount;
2281     
2282     result *= codeTypeThresholdMultiplier();
2283     
2284     if (Options::verboseOSR()) {
2285         dataLog(
2286             *this, ": instruction count is ", instructionCount,
2287             ", scaling execution counter by ", result, " * ", codeTypeThresholdMultiplier(),
2288             "\n");
2289     }
2290     return result;
2291 }
2292
2293 static int32_t clipThreshold(double threshold)
2294 {
2295     if (threshold < 1.0)
2296         return 1;
2297     
2298     if (threshold > static_cast<double>(std::numeric_limits<int32_t>::max()))
2299         return std::numeric_limits<int32_t>::max();
2300     
2301     return static_cast<int32_t>(threshold);
2302 }
2303
2304 int32_t CodeBlock::adjustedCounterValue(int32_t desiredThreshold)
2305 {
2306     return clipThreshold(
2307         static_cast<double>(desiredThreshold) *
2308         optimizationThresholdScalingFactor() *
2309         (1 << reoptimizationRetryCounter()));
2310 }
2311
2312 bool CodeBlock::checkIfOptimizationThresholdReached()
2313 {
2314 #if ENABLE(DFG_JIT)
2315     if (DFG::Worklist* worklist = DFG::existingGlobalDFGWorklistOrNull()) {
2316         if (worklist->compilationState(DFG::CompilationKey(this, DFG::DFGMode))
2317             == DFG::Worklist::Compiled) {
2318             optimizeNextInvocation();
2319             return true;
2320         }
2321     }
2322 #endif
2323     
2324     return m_jitExecuteCounter.checkIfThresholdCrossedAndSet(this);
2325 }
2326
2327 #if ENABLE(DFG_JIT)
2328 auto CodeBlock::updateOSRExitCounterAndCheckIfNeedToReoptimize(DFG::OSRExitState& exitState) -> OptimizeAction
2329 {
2330     DFG::OSRExitBase& exit = exitState.exit;
2331     if (!exitKindMayJettison(exit.m_kind)) {
2332         // FIXME: We may want to notice that we're frequently exiting
2333         // at an op_catch that we didn't compile an entrypoint for, and
2334         // then trigger a reoptimization of this CodeBlock:
2335         // https://bugs.webkit.org/show_bug.cgi?id=175842
2336         return OptimizeAction::None;
2337     }
2338
2339     exit.m_count++;
2340     m_osrExitCounter++;
2341
2342     CodeBlock* baselineCodeBlock = exitState.baselineCodeBlock;
2343     ASSERT(baselineCodeBlock == baselineAlternative());
2344     if (UNLIKELY(baselineCodeBlock->jitExecuteCounter().hasCrossedThreshold()))
2345         return OptimizeAction::ReoptimizeNow;
2346
2347     // We want to figure out if there's a possibility that we're in a loop. For the outermost
2348     // code block in the inline stack, we handle this appropriately by having the loop OSR trigger
2349     // check the exit count of the replacement of the CodeBlock from which we are OSRing. The
2350     // problem is the inlined functions, which might also have loops, but whose baseline versions
2351     // don't know where to look for the exit count. Figure out if those loops are severe enough
2352     // that we had tried to OSR enter. If so, then we should use the loop reoptimization trigger.
2353     // Otherwise, we should use the normal reoptimization trigger.
2354
2355     bool didTryToEnterInLoop = false;
2356     for (InlineCallFrame* inlineCallFrame = exit.m_codeOrigin.inlineCallFrame; inlineCallFrame; inlineCallFrame = inlineCallFrame->directCaller.inlineCallFrame) {
2357         if (inlineCallFrame->baselineCodeBlock->ownerScriptExecutable()->didTryToEnterInLoop()) {
2358             didTryToEnterInLoop = true;
2359             break;
2360         }
2361     }
2362
2363     uint32_t exitCountThreshold = didTryToEnterInLoop
2364         ? exitCountThresholdForReoptimizationFromLoop()
2365         : exitCountThresholdForReoptimization();
2366
2367     if (m_osrExitCounter > exitCountThreshold)
2368         return OptimizeAction::ReoptimizeNow;
2369
2370     // Too few fails. Adjust the execution counter such that the target is to only optimize after a while.
2371     baselineCodeBlock->m_jitExecuteCounter.setNewThresholdForOSRExit(exitState.activeThreshold, exitState.memoryUsageAdjustedThreshold);
2372     return OptimizeAction::None;
2373 }
2374 #endif
2375
2376 void CodeBlock::optimizeNextInvocation()
2377 {
2378     if (Options::verboseOSR())
2379         dataLog(*this, ": Optimizing next invocation.\n");
2380     m_jitExecuteCounter.setNewThreshold(0, this);
2381 }
2382
2383 void CodeBlock::dontOptimizeAnytimeSoon()
2384 {
2385     if (Options::verboseOSR())
2386         dataLog(*this, ": Not optimizing anytime soon.\n");
2387     m_jitExecuteCounter.deferIndefinitely();
2388 }
2389
2390 void CodeBlock::optimizeAfterWarmUp()
2391 {
2392     if (Options::verboseOSR())
2393         dataLog(*this, ": Optimizing after warm-up.\n");
2394 #if ENABLE(DFG_JIT)
2395     m_jitExecuteCounter.setNewThreshold(
2396         adjustedCounterValue(Options::thresholdForOptimizeAfterWarmUp()), this);
2397 #endif
2398 }
2399
2400 void CodeBlock::optimizeAfterLongWarmUp()
2401 {
2402     if (Options::verboseOSR())
2403         dataLog(*this, ": Optimizing after long warm-up.\n");
2404 #if ENABLE(DFG_JIT)
2405     m_jitExecuteCounter.setNewThreshold(
2406         adjustedCounterValue(Options::thresholdForOptimizeAfterLongWarmUp()), this);
2407 #endif
2408 }
2409
2410 void CodeBlock::optimizeSoon()
2411 {
2412     if (Options::verboseOSR())
2413         dataLog(*this, ": Optimizing soon.\n");
2414 #if ENABLE(DFG_JIT)
2415     m_jitExecuteCounter.setNewThreshold(
2416         adjustedCounterValue(Options::thresholdForOptimizeSoon()), this);
2417 #endif
2418 }
2419
2420 void CodeBlock::forceOptimizationSlowPathConcurrently()
2421 {
2422     if (Options::verboseOSR())
2423         dataLog(*this, ": Forcing slow path concurrently.\n");
2424     m_jitExecuteCounter.forceSlowPathConcurrently();
2425 }
2426
2427 #if ENABLE(DFG_JIT)
2428 void CodeBlock::setOptimizationThresholdBasedOnCompilationResult(CompilationResult result)
2429 {
2430     JITCode::JITType type = jitType();
2431     if (type != JITCode::BaselineJIT) {
2432         dataLog(*this, ": expected to have baseline code but have ", type, "\n");
2433         RELEASE_ASSERT_NOT_REACHED();
2434     }
2435     
2436     CodeBlock* replacement = this->replacement();
2437     bool hasReplacement = (replacement && replacement != this);
2438     if ((result == CompilationSuccessful) != hasReplacement) {
2439         dataLog(*this, ": we have result = ", result, " but ");
2440         if (replacement == this)
2441             dataLog("we are our own replacement.\n");
2442         else
2443             dataLog("our replacement is ", pointerDump(replacement), "\n");
2444         RELEASE_ASSERT_NOT_REACHED();
2445     }
2446     
2447     switch (result) {
2448     case CompilationSuccessful:
2449         RELEASE_ASSERT(replacement && JITCode::isOptimizingJIT(replacement->jitType()));
2450         optimizeNextInvocation();
2451         return;
2452     case CompilationFailed:
2453         dontOptimizeAnytimeSoon();
2454         return;
2455     case CompilationDeferred:
2456         // We'd like to do dontOptimizeAnytimeSoon() but we cannot because
2457         // forceOptimizationSlowPathConcurrently() is inherently racy. It won't
2458         // necessarily guarantee anything. So, we make sure that even if that
2459         // function ends up being a no-op, we still eventually retry and realize
2460         // that we have optimized code ready.
2461         optimizeAfterWarmUp();
2462         return;
2463     case CompilationInvalidated:
2464         // Retry with exponential backoff.
2465         countReoptimization();
2466         optimizeAfterWarmUp();
2467         return;
2468     }
2469     
2470     dataLog("Unrecognized result: ", static_cast<int>(result), "\n");
2471     RELEASE_ASSERT_NOT_REACHED();
2472 }
2473
2474 #endif
2475     
2476 uint32_t CodeBlock::adjustedExitCountThreshold(uint32_t desiredThreshold)
2477 {
2478     ASSERT(JITCode::isOptimizingJIT(jitType()));
2479     // Compute this the lame way so we don't saturate. This is called infrequently
2480     // enough that this loop won't hurt us.
2481     unsigned result = desiredThreshold;
2482     for (unsigned n = baselineVersion()->reoptimizationRetryCounter(); n--;) {
2483         unsigned newResult = result << 1;
2484         if (newResult < result)
2485             return std::numeric_limits<uint32_t>::max();
2486         result = newResult;
2487     }
2488     return result;
2489 }
2490
2491 uint32_t CodeBlock::exitCountThresholdForReoptimization()
2492 {
2493     return adjustedExitCountThreshold(Options::osrExitCountForReoptimization() * codeTypeThresholdMultiplier());
2494 }
2495
2496 uint32_t CodeBlock::exitCountThresholdForReoptimizationFromLoop()
2497 {
2498     return adjustedExitCountThreshold(Options::osrExitCountForReoptimizationFromLoop() * codeTypeThresholdMultiplier());
2499 }
2500
2501 bool CodeBlock::shouldReoptimizeNow()
2502 {
2503     return osrExitCounter() >= exitCountThresholdForReoptimization();
2504 }
2505
2506 bool CodeBlock::shouldReoptimizeFromLoopNow()
2507 {
2508     return osrExitCounter() >= exitCountThresholdForReoptimizationFromLoop();
2509 }
2510 #endif
2511
2512 ArrayProfile* CodeBlock::getArrayProfile(const ConcurrentJSLocker&, unsigned bytecodeOffset)
2513 {
2514     for (auto& m_arrayProfile : m_arrayProfiles) {
2515         if (m_arrayProfile.bytecodeOffset() == bytecodeOffset)
2516             return &m_arrayProfile;
2517     }
2518     return 0;
2519 }
2520
2521 ArrayProfile* CodeBlock::getArrayProfile(unsigned bytecodeOffset)
2522 {
2523     ConcurrentJSLocker locker(m_lock);
2524     return getArrayProfile(locker, bytecodeOffset);
2525 }
2526
2527 ArrayProfile* CodeBlock::addArrayProfile(const ConcurrentJSLocker&, unsigned bytecodeOffset)
2528 {
2529     m_arrayProfiles.append(ArrayProfile(bytecodeOffset));
2530     return &m_arrayProfiles.last();
2531 }
2532
2533 ArrayProfile* CodeBlock::addArrayProfile(unsigned bytecodeOffset)
2534 {
2535     ConcurrentJSLocker locker(m_lock);
2536     return addArrayProfile(locker, bytecodeOffset);
2537 }
2538
2539 ArrayProfile* CodeBlock::getOrAddArrayProfile(const ConcurrentJSLocker& locker, unsigned bytecodeOffset)
2540 {
2541     ArrayProfile* result = getArrayProfile(locker, bytecodeOffset);
2542     if (result)
2543         return result;
2544     return addArrayProfile(locker, bytecodeOffset);
2545 }
2546
2547 ArrayProfile* CodeBlock::getOrAddArrayProfile(unsigned bytecodeOffset)
2548 {
2549     ConcurrentJSLocker locker(m_lock);
2550     return getOrAddArrayProfile(locker, bytecodeOffset);
2551 }
2552
2553 #if ENABLE(DFG_JIT)
2554 Vector<CodeOrigin, 0, UnsafeVectorOverflow>& CodeBlock::codeOrigins()
2555 {
2556     return m_jitCode->dfgCommon()->codeOrigins;
2557 }
2558
2559 size_t CodeBlock::numberOfDFGIdentifiers() const
2560 {
2561     if (!JITCode::isOptimizingJIT(jitType()))
2562         return 0;
2563     
2564     return m_jitCode->dfgCommon()->dfgIdentifiers.size();
2565 }
2566
2567 const Identifier& CodeBlock::identifier(int index) const
2568 {
2569     size_t unlinkedIdentifiers = m_unlinkedCode->numberOfIdentifiers();
2570     if (static_cast<unsigned>(index) < unlinkedIdentifiers)
2571         return m_unlinkedCode->identifier(index);
2572     ASSERT(JITCode::isOptimizingJIT(jitType()));
2573     return m_jitCode->dfgCommon()->dfgIdentifiers[index - unlinkedIdentifiers];
2574 }
2575 #endif // ENABLE(DFG_JIT)
2576
2577 void CodeBlock::updateAllPredictionsAndCountLiveness(unsigned& numberOfLiveNonArgumentValueProfiles, unsigned& numberOfSamplesInProfiles)
2578 {
2579     ConcurrentJSLocker locker(m_lock);
2580
2581     numberOfLiveNonArgumentValueProfiles = 0;
2582     numberOfSamplesInProfiles = 0; // If this divided by ValueProfile::numberOfBuckets equals numberOfValueProfiles() then value profiles are full.
2583
2584     for (unsigned i = 0; i < totalNumberOfValueProfiles(); ++i) {
2585         ValueProfile& profile = getFromAllValueProfiles(i);
2586         unsigned numSamples = profile.totalNumberOfSamples();
2587         if (numSamples > ValueProfile::numberOfBuckets)
2588             numSamples = ValueProfile::numberOfBuckets; // We don't want profiles that are extremely hot to be given more weight.
2589         numberOfSamplesInProfiles += numSamples;
2590         if (profile.m_bytecodeOffset < 0) {
2591             profile.computeUpdatedPrediction(locker);
2592             continue;
2593         }
2594         if (profile.numberOfSamples() || profile.m_prediction != SpecNone)
2595             numberOfLiveNonArgumentValueProfiles++;
2596         profile.computeUpdatedPrediction(locker);
2597     }
2598
2599     for (auto& profileBucket : m_catchProfiles) {
2600         profileBucket->forEach([&] (ValueProfileAndOperand& profile) {
2601             profile.m_profile.computeUpdatedPrediction(locker);
2602         });
2603     }
2604     
2605 #if ENABLE(DFG_JIT)
2606     m_lazyOperandValueProfiles.computeUpdatedPredictions(locker);
2607 #endif
2608 }
2609
2610 void CodeBlock::updateAllValueProfilePredictions()
2611 {
2612     unsigned ignoredValue1, ignoredValue2;
2613     updateAllPredictionsAndCountLiveness(ignoredValue1, ignoredValue2);
2614 }
2615
2616 void CodeBlock::updateAllArrayPredictions()
2617 {
2618     ConcurrentJSLocker locker(m_lock);
2619     
2620     for (unsigned i = m_arrayProfiles.size(); i--;)
2621         m_arrayProfiles[i].computeUpdatedPrediction(locker, this);
2622     
2623     // Don't count these either, for similar reasons.
2624     for (unsigned i = m_arrayAllocationProfiles.size(); i--;)
2625         m_arrayAllocationProfiles[i].updateProfile();
2626 }
2627
2628 void CodeBlock::updateAllPredictions()
2629 {
2630     updateAllValueProfilePredictions();
2631     updateAllArrayPredictions();
2632 }
2633
2634 bool CodeBlock::shouldOptimizeNow()
2635 {
2636     if (Options::verboseOSR())
2637         dataLog("Considering optimizing ", *this, "...\n");
2638
2639     if (m_optimizationDelayCounter >= Options::maximumOptimizationDelay())
2640         return true;
2641     
2642     updateAllArrayPredictions();
2643     
2644     unsigned numberOfLiveNonArgumentValueProfiles;
2645     unsigned numberOfSamplesInProfiles;
2646     updateAllPredictionsAndCountLiveness(numberOfLiveNonArgumentValueProfiles, numberOfSamplesInProfiles);
2647
2648     if (Options::verboseOSR()) {
2649         dataLogF(
2650             "Profile hotness: %lf (%u / %u), %lf (%u / %u)\n",
2651             (double)numberOfLiveNonArgumentValueProfiles / numberOfValueProfiles(),
2652             numberOfLiveNonArgumentValueProfiles, numberOfValueProfiles(),
2653             (double)numberOfSamplesInProfiles / ValueProfile::numberOfBuckets / numberOfValueProfiles(),
2654             numberOfSamplesInProfiles, ValueProfile::numberOfBuckets * numberOfValueProfiles());
2655     }
2656
2657     if ((!numberOfValueProfiles() || (double)numberOfLiveNonArgumentValueProfiles / numberOfValueProfiles() >= Options::desiredProfileLivenessRate())
2658         && (!totalNumberOfValueProfiles() || (double)numberOfSamplesInProfiles / ValueProfile::numberOfBuckets / totalNumberOfValueProfiles() >= Options::desiredProfileFullnessRate())
2659         && static_cast<unsigned>(m_optimizationDelayCounter) + 1 >= Options::minimumOptimizationDelay())
2660         return true;
2661     
2662     ASSERT(m_optimizationDelayCounter < std::numeric_limits<uint8_t>::max());
2663     m_optimizationDelayCounter++;
2664     optimizeAfterWarmUp();
2665     return false;
2666 }
2667
2668 #if ENABLE(DFG_JIT)
2669 void CodeBlock::tallyFrequentExitSites()
2670 {
2671     ASSERT(JITCode::isOptimizingJIT(jitType()));
2672     ASSERT(alternative()->jitType() == JITCode::BaselineJIT);
2673     
2674     CodeBlock* profiledBlock = alternative();
2675     
2676     switch (jitType()) {
2677     case JITCode::DFGJIT: {
2678         DFG::JITCode* jitCode = m_jitCode->dfg();
2679         for (auto& exit : jitCode->osrExit)
2680             exit.considerAddingAsFrequentExitSite(profiledBlock);
2681         break;
2682     }
2683
2684 #if ENABLE(FTL_JIT)
2685     case JITCode::FTLJIT: {
2686         // There is no easy way to avoid duplicating this code since the FTL::JITCode::osrExit
2687         // vector contains a totally different type, that just so happens to behave like
2688         // DFG::JITCode::osrExit.
2689         FTL::JITCode* jitCode = m_jitCode->ftl();
2690         for (unsigned i = 0; i < jitCode->osrExit.size(); ++i) {
2691             FTL::OSRExit& exit = jitCode->osrExit[i];
2692             exit.considerAddingAsFrequentExitSite(profiledBlock);
2693         }
2694         break;
2695     }
2696 #endif
2697         
2698     default:
2699         RELEASE_ASSERT_NOT_REACHED();
2700         break;
2701     }
2702 }
2703 #endif // ENABLE(DFG_JIT)
2704
2705 #if ENABLE(VERBOSE_VALUE_PROFILE)
2706 void CodeBlock::dumpValueProfiles()
2707 {
2708     dataLog("ValueProfile for ", *this, ":\n");
2709     for (unsigned i = 0; i < totalNumberOfValueProfiles(); ++i) {
2710         ValueProfile& profile = getFromAllValueProfiles(i);
2711         if (profile.m_bytecodeOffset < 0) {
2712             ASSERT(profile.m_bytecodeOffset == -1);
2713             dataLogF("   arg = %u: ", i);
2714         } else
2715             dataLogF("   bc = %d: ", profile.m_bytecodeOffset);
2716         if (!profile.numberOfSamples() && profile.m_prediction == SpecNone) {
2717             dataLogF("<empty>\n");
2718             continue;
2719         }
2720         profile.dump(WTF::dataFile());
2721         dataLogF("\n");
2722     }
2723     dataLog("RareCaseProfile for ", *this, ":\n");
2724     for (unsigned i = 0; i < numberOfRareCaseProfiles(); ++i) {
2725         RareCaseProfile* profile = rareCaseProfile(i);
2726         dataLogF("   bc = %d: %u\n", profile->m_bytecodeOffset, profile->m_counter);
2727     }
2728 }
2729 #endif // ENABLE(VERBOSE_VALUE_PROFILE)
2730
2731 unsigned CodeBlock::frameRegisterCount()
2732 {
2733     switch (jitType()) {
2734     case JITCode::InterpreterThunk:
2735         return LLInt::frameRegisterCountFor(this);
2736
2737 #if ENABLE(JIT)
2738     case JITCode::BaselineJIT:
2739         return JIT::frameRegisterCountFor(this);
2740 #endif // ENABLE(JIT)
2741
2742 #if ENABLE(DFG_JIT)
2743     case JITCode::DFGJIT:
2744     case JITCode::FTLJIT:
2745         return jitCode()->dfgCommon()->frameRegisterCount;
2746 #endif // ENABLE(DFG_JIT)
2747         
2748     default:
2749         RELEASE_ASSERT_NOT_REACHED();
2750         return 0;
2751     }
2752 }
2753
2754 int CodeBlock::stackPointerOffset()
2755 {
2756     return virtualRegisterForLocal(frameRegisterCount() - 1).offset();
2757 }
2758
2759 size_t CodeBlock::predictedMachineCodeSize()
2760 {
2761     VM* vm = m_poisonedVM.unpoisoned();
2762     // This will be called from CodeBlock::CodeBlock before either m_poisonedVM or the
2763     // instructions have been initialized. It's OK to return 0 because what will really
2764     // matter is the recomputation of this value when the slow path is triggered.
2765     if (!vm)
2766         return 0;
2767     
2768     if (!*vm->machineCodeBytesPerBytecodeWordForBaselineJIT)
2769         return 0; // It's as good of a prediction as we'll get.
2770     
2771     // Be conservative: return a size that will be an overestimation 84% of the time.
2772     double multiplier = vm->machineCodeBytesPerBytecodeWordForBaselineJIT->mean() +
2773         vm->machineCodeBytesPerBytecodeWordForBaselineJIT->standardDeviation();
2774     
2775     // Be paranoid: silently reject bogus multipiers. Silently doing the "wrong" thing
2776     // here is OK, since this whole method is just a heuristic.
2777     if (multiplier < 0 || multiplier > 1000)
2778         return 0;
2779     
2780     double doubleResult = multiplier * m_instructions.size();
2781     
2782     // Be even more paranoid: silently reject values that won't fit into a size_t. If
2783     // the function is so huge that we can't even fit it into virtual memory then we
2784     // should probably have some other guards in place to prevent us from even getting
2785     // to this point.
2786     if (doubleResult > std::numeric_limits<size_t>::max())
2787         return 0;
2788     
2789     return static_cast<size_t>(doubleResult);
2790 }
2791
2792 String CodeBlock::nameForRegister(VirtualRegister virtualRegister)
2793 {
2794     for (auto& constantRegister : m_constantRegisters) {
2795         if (constantRegister.get().isEmpty())
2796             continue;
2797         if (SymbolTable* symbolTable = jsDynamicCast<SymbolTable*>(*vm(), constantRegister.get())) {
2798             ConcurrentJSLocker locker(symbolTable->m_lock);
2799             auto end = symbolTable->end(locker);
2800             for (auto ptr = symbolTable->begin(locker); ptr != end; ++ptr) {
2801                 if (ptr->value.varOffset() == VarOffset(virtualRegister)) {
2802                     // FIXME: This won't work from the compilation thread.
2803                     // https://bugs.webkit.org/show_bug.cgi?id=115300
2804                     return ptr->key.get();
2805                 }
2806             }
2807         }
2808     }
2809     if (virtualRegister == thisRegister())
2810         return "this"_s;
2811     if (virtualRegister.isArgument())
2812         return String::format("arguments[%3d]", virtualRegister.toArgument());
2813
2814     return "";
2815 }
2816
2817 ValueProfile* CodeBlock::tryGetValueProfileForBytecodeOffset(int bytecodeOffset)
2818 {
2819     return tryBinarySearch<ValueProfile, int>(
2820         m_valueProfiles, m_valueProfiles.size(), bytecodeOffset,
2821         getValueProfileBytecodeOffset<ValueProfile>);
2822 }
2823
2824 ValueProfile& CodeBlock::valueProfileForBytecodeOffset(int bytecodeOffset)
2825 {
2826     OpcodeID opcodeID = Interpreter::getOpcodeID(instructions()[bytecodeOffset]);
2827     unsigned length = opcodeLength(opcodeID);
2828     ASSERT(!!tryGetValueProfileForBytecodeOffset(bytecodeOffset));
2829     return *instructions()[bytecodeOffset + length - 1].u.profile;
2830 }
2831
2832 void CodeBlock::validate()
2833 {
2834     BytecodeLivenessAnalysis liveness(this); // Compute directly from scratch so it doesn't effect CodeBlock footprint.
2835     
2836     FastBitVector liveAtHead = liveness.getLivenessInfoAtBytecodeOffset(this, 0);
2837     
2838     if (liveAtHead.numBits() != static_cast<size_t>(m_numCalleeLocals)) {
2839         beginValidationDidFail();
2840         dataLog("    Wrong number of bits in result!\n");
2841         dataLog("    Result: ", liveAtHead, "\n");
2842         dataLog("    Bit count: ", liveAtHead.numBits(), "\n");
2843         endValidationDidFail();
2844     }
2845     
2846     for (unsigned i = m_numCalleeLocals; i--;) {
2847         VirtualRegister reg = virtualRegisterForLocal(i);
2848         
2849         if (liveAtHead[i]) {
2850             beginValidationDidFail();
2851             dataLog("    Variable ", reg, " is expected to be dead.\n");
2852             dataLog("    Result: ", liveAtHead, "\n");
2853             endValidationDidFail();
2854         }
2855     }
2856
2857     for (unsigned i = 0; i + 1 < numberOfValueProfiles(); ++i) {
2858         if (valueProfile(i).m_bytecodeOffset > valueProfile(i + 1).m_bytecodeOffset) {
2859             beginValidationDidFail();
2860             dataLog("    Value profiles are not sorted.\n");
2861             endValidationDidFail();
2862         }
2863     }
2864      
2865     for (unsigned bytecodeOffset = 0; bytecodeOffset < m_instructions.size(); ) {
2866         OpcodeID opcode = Interpreter::getOpcodeID(m_instructions[bytecodeOffset]);
2867         if (!!baselineAlternative()->handlerForBytecodeOffset(bytecodeOffset)) {
2868             if (opcode == op_catch || opcode == op_enter) {
2869                 // op_catch/op_enter logically represent an entrypoint. Entrypoints are not allowed to be
2870                 // inside of a try block because they are responsible for bootstrapping state. And they
2871                 // are never allowed throw an exception because of this. We rely on this when compiling
2872                 // in the DFG. Because an entrypoint never throws, the bytecode generator will never
2873                 // allow once inside a try block.
2874                 beginValidationDidFail();
2875                 dataLog("    entrypoint not allowed inside a try block.");
2876                 endValidationDidFail();
2877             }
2878         }
2879         bytecodeOffset += opcodeLength(opcode);
2880     }
2881 }
2882
2883 void CodeBlock::beginValidationDidFail()
2884 {
2885     dataLog("Validation failure in ", *this, ":\n");
2886     dataLog("\n");
2887 }
2888
2889 void CodeBlock::endValidationDidFail()
2890 {
2891     dataLog("\n");
2892     dumpBytecode();
2893     dataLog("\n");
2894     dataLog("Validation failure.\n");
2895     RELEASE_ASSERT_NOT_REACHED();
2896 }
2897
2898 void CodeBlock::addBreakpoint(unsigned numBreakpoints)
2899 {
2900     m_numBreakpoints += numBreakpoints;
2901     ASSERT(m_numBreakpoints);
2902     if (JITCode::isOptimizingJIT(jitType()))
2903         jettison(Profiler::JettisonDueToDebuggerBreakpoint);
2904 }
2905
2906 void CodeBlock::setSteppingMode(CodeBlock::SteppingMode mode)
2907 {
2908     m_steppingMode = mode;
2909     if (mode == SteppingModeEnabled && JITCode::isOptimizingJIT(jitType()))
2910         jettison(Profiler::JettisonDueToDebuggerStepping);
2911 }
2912
2913 RareCaseProfile* CodeBlock::addRareCaseProfile(int bytecodeOffset)
2914 {
2915     m_rareCaseProfiles.append(RareCaseProfile(bytecodeOffset));
2916     return &m_rareCaseProfiles.last();
2917 }
2918
2919 RareCaseProfile* CodeBlock::rareCaseProfileForBytecodeOffset(int bytecodeOffset)
2920 {
2921     return tryBinarySearch<RareCaseProfile, int>(
2922         m_rareCaseProfiles, m_rareCaseProfiles.size(), bytecodeOffset,
2923         getRareCaseProfileBytecodeOffset);
2924 }
2925
2926 unsigned CodeBlock::rareCaseProfileCountForBytecodeOffset(int bytecodeOffset)
2927 {
2928     RareCaseProfile* profile = rareCaseProfileForBytecodeOffset(bytecodeOffset);
2929     if (profile)
2930         return profile->m_counter;
2931     return 0;
2932 }
2933
2934 ArithProfile* CodeBlock::arithProfileForBytecodeOffset(int bytecodeOffset)
2935 {
2936     return arithProfileForPC(&instructions()[bytecodeOffset]);
2937 }
2938
2939 ArithProfile* CodeBlock::arithProfileForPC(Instruction* pc)
2940 {
2941     auto opcodeID = Interpreter::getOpcodeID(pc[0]);
2942     switch (opcodeID) {
2943     case op_negate:
2944         return bitwise_cast<ArithProfile*>(&pc[3].u.operand);
2945     case op_bitor:
2946     case op_bitand:
2947     case op_bitxor:
2948     case op_add:
2949     case op_mul:
2950     case op_sub:
2951     case op_div:
2952         return bitwise_cast<ArithProfile*>(&pc[4].u.operand);
2953     default:
2954         break;
2955     }
2956
2957     return nullptr;
2958 }
2959
2960 bool CodeBlock::couldTakeSpecialFastCase(int bytecodeOffset)
2961 {
2962     if (!hasBaselineJITProfiling())
2963         return false;
2964     ArithProfile* profile = arithProfileForBytecodeOffset(bytecodeOffset);
2965     if (!profile)
2966         return false;
2967     return profile->tookSpecialFastPath();
2968 }
2969
2970 #if ENABLE(JIT)
2971 DFG::CapabilityLevel CodeBlock::capabilityLevel()
2972 {
2973     DFG::CapabilityLevel result = computeCapabilityLevel();
2974     m_capabilityLevelState = result;
2975     return result;
2976 }
2977 #endif
2978
2979 void CodeBlock::insertBasicBlockBoundariesForControlFlowProfiler(RefCountedArray<Instruction>& instructions)
2980 {
2981     if (!unlinkedCodeBlock()->hasOpProfileControlFlowBytecodeOffsets())
2982         return;
2983     const Vector<size_t>& bytecodeOffsets = unlinkedCodeBlock()->opProfileControlFlowBytecodeOffsets();
2984     for (size_t i = 0, offsetsLength = bytecodeOffsets.size(); i < offsetsLength; i++) {
2985         // Because op_profile_control_flow is emitted at the beginning of every basic block, finding 
2986         // the next op_profile_control_flow will give us the text range of a single basic block.
2987         size_t startIdx = bytecodeOffsets[i];
2988         RELEASE_ASSERT(Interpreter::getOpcodeID(instructions[startIdx]) == op_profile_control_flow);
2989         int basicBlockStartOffset = instructions[startIdx + 1].u.operand;
2990         int basicBlockEndOffset;
2991         if (i + 1 < offsetsLength) {
2992             size_t endIdx = bytecodeOffsets[i + 1];
2993             RELEASE_ASSERT(Interpreter::getOpcodeID(instructions[endIdx]) == op_profile_control_flow);
2994             basicBlockEndOffset = instructions[endIdx + 1].u.operand - 1;
2995         } else {
2996             basicBlockEndOffset = m_sourceOffset + ownerScriptExecutable()->source().length() - 1; // Offset before the closing brace.
2997             basicBlockStartOffset = std::min(basicBlockStartOffset, basicBlockEndOffset); // Some start offsets may be at the closing brace, ensure it is the offset before.
2998         }
2999
3000         // The following check allows for the same textual JavaScript basic block to have its bytecode emitted more
3001         // than once and still play nice with the control flow profiler. When basicBlockStartOffset is larger than 
3002         // basicBlockEndOffset, it indicates that the bytecode generator has emitted code for the same AST node 
3003         // more than once (for example: ForInNode, Finally blocks in TryNode, etc). Though these are different 
3004         // basic blocks at the bytecode level, they are generated from the same textual basic block in the JavaScript 
3005         // program. The condition: 
3006         // (basicBlockEndOffset < basicBlockStartOffset) 
3007         // is encountered when op_profile_control_flow lies across the boundary of these duplicated bytecode basic 
3008         // blocks and the textual offset goes from the end of the duplicated block back to the beginning. These 
3009         // ranges are dummy ranges and are ignored. The duplicated bytecode basic blocks point to the same 
3010         // internal data structure, so if any of them execute, it will record the same textual basic block in the 
3011         // JavaScript program as executing.
3012         // At the bytecode level, this situation looks like:
3013         // j: op_profile_control_flow (from j->k, we have basicBlockEndOffset < basicBlockStartOffset)
3014         // ...
3015         // 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).
3016         // ...
3017         // m: op_profile_control_flow
3018         if (basicBlockEndOffset < basicBlockStartOffset) {
3019             RELEASE_ASSERT(i + 1 < offsetsLength); // We should never encounter dummy blocks at the end of a CodeBlock.
3020             instructions[startIdx + 1].u.basicBlockLocation = vm()->controlFlowProfiler()->dummyBasicBlock();
3021             continue;
3022         }
3023
3024         BasicBlockLocation* basicBlockLocation = vm()->controlFlowProfiler()->getBasicBlockLocation(ownerScriptExecutable()->sourceID(), basicBlockStartOffset, basicBlockEndOffset);
3025
3026         // Find all functions that are enclosed within the range: [basicBlockStartOffset, basicBlockEndOffset]
3027         // and insert these functions' start/end offsets as gaps in the current BasicBlockLocation.
3028         // This is necessary because in the original source text of a JavaScript program, 
3029         // function literals form new basic blocks boundaries, but they aren't represented 
3030         // inside the CodeBlock's instruction stream.
3031         auto insertFunctionGaps = [basicBlockLocation, basicBlockStartOffset, basicBlockEndOffset] (const WriteBarrier<FunctionExecutable>& functionExecutable) {
3032             const UnlinkedFunctionExecutable* executable = functionExecutable->unlinkedExecutable();
3033             int functionStart = executable->typeProfilingStartOffset();
3034             int functionEnd = executable->typeProfilingEndOffset();
3035             if (functionStart >= basicBlockStartOffset && functionEnd <= basicBlockEndOffset)
3036                 basicBlockLocation->insertGap(functionStart, functionEnd);
3037         };
3038
3039         for (const WriteBarrier<FunctionExecutable>& executable : m_functionDecls)
3040             insertFunctionGaps(executable);
3041         for (const WriteBarrier<FunctionExecutable>& executable : m_functionExprs)
3042             insertFunctionGaps(executable);
3043
3044         instructions[startIdx + 1].u.basicBlockLocation = basicBlockLocation;
3045     }
3046 }
3047
3048 #if ENABLE(JIT)
3049 void CodeBlock::setPCToCodeOriginMap(std::unique_ptr<PCToCodeOriginMap>&& map) 
3050
3051     m_pcToCodeOriginMap = WTFMove(map);
3052 }
3053
3054 std::optional<CodeOrigin> CodeBlock::findPC(void* pc)
3055 {
3056     if (m_pcToCodeOriginMap) {
3057         if (std::optional<CodeOrigin> codeOrigin = m_pcToCodeOriginMap->findPC(pc))
3058             return codeOrigin;
3059     }
3060
3061     for (auto iter = m_stubInfos.begin(); !!iter; ++iter) {
3062         StructureStubInfo* stub = *iter;
3063         if (stub->containsPC(pc))
3064             return std::optional<CodeOrigin>(stub->codeOrigin);
3065     }
3066
3067     if (std::optional<CodeOrigin> codeOrigin = m_jitCode->findPC(this, pc))
3068         return codeOrigin;
3069
3070     return std::nullopt;
3071 }
3072 #endif // ENABLE(JIT)
3073
3074 std::optional<unsigned> CodeBlock::bytecodeOffsetFromCallSiteIndex(CallSiteIndex callSiteIndex)
3075 {
3076     std::optional<unsigned> bytecodeOffset;
3077     JITCode::JITType jitType = this->jitType();
3078     if (jitType == JITCode::InterpreterThunk || jitType == JITCode::BaselineJIT) {
3079 #if USE(JSVALUE64)
3080         bytecodeOffset = callSiteIndex.bits();
3081 #else
3082         Instruction* instruction = bitwise_cast<Instruction*>(callSiteIndex.bits());
3083         bytecodeOffset = this->bytecodeOffset(instruction);
3084 #endif
3085     } else if (jitType == JITCode::DFGJIT || jitType == JITCode::FTLJIT) {
3086 #if ENABLE(DFG_JIT)
3087         RELEASE_ASSERT(canGetCodeOrigin(callSiteIndex));
3088         CodeOrigin origin = codeOrigin(callSiteIndex);
3089         bytecodeOffset = origin.bytecodeIndex;
3090 #else
3091         RELEASE_ASSERT_NOT_REACHED();
3092 #endif
3093     }
3094
3095     return bytecodeOffset;
3096 }
3097
3098 int32_t CodeBlock::thresholdForJIT(int32_t threshold)
3099 {
3100     switch (unlinkedCodeBlock()->didOptimize()) {
3101     case MixedTriState:
3102         return threshold;
3103     case FalseTriState:
3104         return threshold * 4;
3105     case TrueTriState:
3106         return threshold / 2;
3107     }
3108     ASSERT_NOT_REACHED();
3109     return threshold;
3110 }
3111
3112 void CodeBlock::jitAfterWarmUp()
3113 {
3114     m_llintExecuteCounter.setNewThreshold(thresholdForJIT(Options::thresholdForJITAfterWarmUp()), this);
3115 }
3116
3117 void CodeBlock::jitSoon()
3118 {
3119     m_llintExecuteCounter.setNewThreshold(thresholdForJIT(Options::thresholdForJITSoon()), this);
3120 }
3121
3122 bool CodeBlock::hasInstalledVMTrapBreakpoints() const
3123 {
3124 #if ENABLE(SIGNAL_BASED_VM_TRAPS)
3125     // This function may be called from a signal handler. We need to be
3126     // careful to not call anything that is not signal handler safe, e.g.
3127     // we should not perturb the refCount of m_jitCode.
3128     if (!JITCode::isOptimizingJIT(jitType()))
3129         return false;
3130     return m_jitCode->dfgCommon()->hasInstalledVMTrapsBreakpoints();
3131 #else
3132     return false;
3133 #endif
3134 }
3135
3136 bool CodeBlock::installVMTrapBreakpoints()
3137 {
3138 #if ENABLE(SIGNAL_BASED_VM_TRAPS)
3139     // This function may be called from a signal handler. We need to be
3140     // careful to not call anything that is not signal handler safe, e.g.
3141     // we should not perturb the refCount of m_jitCode.
3142     if (!JITCode::isOptimizingJIT(jitType()))
3143         return false;
3144     auto& commonData = *m_jitCode->dfgCommon();
3145     commonData.installVMTrapBreakpoints(this);
3146     return true;
3147 #else
3148     UNREACHABLE_FOR_PLATFORM();
3149     return false;
3150 #endif
3151 }
3152
3153 void CodeBlock::dumpMathICStats()
3154 {
3155 #if ENABLE(MATH_IC_STATS)
3156     double numAdds = 0.0;
3157     double totalAddSize = 0.0;
3158     double numMuls = 0.0;
3159     double totalMulSize = 0.0;
3160     double numNegs = 0.0;
3161     double totalNegSize = 0.0;
3162     double numSubs = 0.0;
3163     double totalSubSize = 0.0;
3164
3165     auto countICs = [&] (CodeBlock* codeBlock) {
3166         for (JITAddIC* addIC : codeBlock->m_addICs) {
3167             numAdds++;
3168             totalAddSize += addIC->codeSize();
3169         }
3170
3171         for (JITMulIC* mulIC : codeBlock->m_mulICs) {
3172             numMuls++;
3173             totalMulSize += mulIC->codeSize();
3174         }
3175
3176         for (JITNegIC* negIC : codeBlock->m_negICs) {
3177             numNegs++;
3178             totalNegSize += negIC->codeSize();
3179         }
3180
3181         for (JITSubIC* subIC : codeBlock->m_subICs) {
3182             numSubs++;
3183             totalSubSize += subIC->codeSize();
3184         }
3185     };
3186     heap()->forEachCodeBlock(countICs);
3187
3188     dataLog("Num Adds: ", numAdds, "\n");
3189     dataLog("Total Add size in bytes: ", totalAddSize, "\n");
3190     dataLog("Average Add size: ", totalAddSize / numAdds, "\n");
3191     dataLog("\n");
3192     dataLog("Num Muls: ", numMuls, "\n");
3193     dataLog("Total Mul size in bytes: ", totalMulSize, "\n");
3194     dataLog("Average Mul size: ", totalMulSize / numMuls, "\n");
3195     dataLog("\n");
3196     dataLog("Num Negs: ", numNegs, "\n");
3197     dataLog("Total Neg size in bytes: ", totalNegSize, "\n");
3198     dataLog("Average Neg size: ", totalNegSize / numNegs, "\n");
3199     dataLog("\n");
3200     dataLog("Num Subs: ", numSubs, "\n");
3201     dataLog("Total Sub size in bytes: ", totalSubSize, "\n");
3202     dataLog("Average Sub size: ", totalSubSize / numSubs, "\n");
3203
3204     dataLog("-----------------------\n");
3205 #endif
3206 }
3207
3208 void setPrinter(Printer::PrintRecord& record, CodeBlock* codeBlock)
3209 {
3210     Printer::setPrinter(record, toCString(codeBlock));
3211 }
3212
3213 } // namespace JSC
3214
3215 namespace WTF {
3216     
3217 void printInternal(PrintStream& out, JSC::CodeBlock* codeBlock)
3218 {
3219     if (UNLIKELY(!codeBlock)) {
3220         out.print("<null codeBlock>");
3221         return;
3222     }
3223     out.print(*codeBlock);
3224 }
3225     
3226 } // namespace WTF