[WTF] Add user-defined literal for ASCIILiteral
[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_numCalleeLocals(other.m_numCalleeLocals)
301     , m_numVars(other.m_numVars)
302     , m_shouldAlwaysBeInlined(true)
303 #if ENABLE(JIT)
304     , m_capabilityLevelState(DFG::CapabilityLevelNotSet)
305 #endif
306     , m_didFailJITCompilation(false)
307     , m_didFailFTLCompilation(false)
308     , m_hasBeenCompiledWithFTL(false)
309     , m_isConstructor(other.m_isConstructor)
310     , m_isStrictMode(other.m_isStrictMode)
311     , m_codeType(other.m_codeType)
312     , m_unlinkedCode(*other.vm(), this, other.m_unlinkedCode.get())
313     , m_numberOfArgumentsToSkip(other.m_numberOfArgumentsToSkip)
314     , m_hasDebuggerStatement(false)
315     , m_steppingMode(SteppingModeDisabled)
316     , m_numBreakpoints(0)
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_numCalleeLocals(unlinkedCodeBlock->m_numCalleeLocals)
365     , m_numVars(unlinkedCodeBlock->m_numVars)
366     , m_shouldAlwaysBeInlined(true)
367 #if ENABLE(JIT)
368     , m_capabilityLevelState(DFG::CapabilityLevelNotSet)
369 #endif
370     , m_didFailJITCompilation(false)
371     , m_didFailFTLCompilation(false)
372     , m_hasBeenCompiledWithFTL(false)
373     , m_isConstructor(unlinkedCodeBlock->isConstructor())
374     , m_isStrictMode(unlinkedCodeBlock->isStrictMode())
375     , m_codeType(unlinkedCodeBlock->codeType())
376     , m_unlinkedCode(*vm, this, unlinkedCodeBlock)
377     , m_hasDebuggerStatement(false)
378     , m_steppingMode(SteppingModeDisabled)
379     , m_numBreakpoints(0)
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)
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) + extraMemoryAllocated;
1009 }
1010
1011 void CodeBlock::visitChildren(JSCell* cell, SlotVisitor& visitor)
1012 {
1013     CodeBlock* thisObject = jsCast<CodeBlock*>(cell);
1014     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
1015     Base::visitChildren(cell, visitor);
1016     visitor.append(thisObject->m_ownerEdge);
1017     thisObject->visitChildren(visitor);
1018 }
1019
1020 void CodeBlock::visitChildren(SlotVisitor& visitor)
1021 {
1022     ConcurrentJSLocker locker(m_lock);
1023     if (CodeBlock* otherBlock = specialOSREntryBlockOrNull())
1024         visitor.appendUnbarriered(otherBlock);
1025
1026     if (m_jitCode)
1027         visitor.reportExtraMemoryVisited(m_jitCode->size());
1028     if (m_instructions.size()) {
1029         unsigned refCount = m_instructions.refCount();
1030         if (!refCount) {
1031             dataLog("CodeBlock: ", RawPointer(this), "\n");
1032             dataLog("m_instructions.data(): ", RawPointer(m_instructions.data()), "\n");
1033             dataLog("refCount: ", refCount, "\n");
1034             RELEASE_ASSERT_NOT_REACHED();
1035         }
1036         visitor.reportExtraMemoryVisited(m_instructions.size() * sizeof(Instruction) / refCount);
1037     }
1038
1039     stronglyVisitStrongReferences(locker, visitor);
1040     stronglyVisitWeakReferences(locker, visitor);
1041     
1042     VM::SpaceAndFinalizerSet::finalizerSetFor(*subspace()).add(this);
1043 }
1044
1045 bool CodeBlock::shouldVisitStrongly(const ConcurrentJSLocker& locker)
1046 {
1047     if (Options::forceCodeBlockLiveness())
1048         return true;
1049
1050     if (shouldJettisonDueToOldAge(locker))
1051         return false;
1052
1053     // Interpreter and Baseline JIT CodeBlocks don't need to be jettisoned when
1054     // their weak references go stale. So if a basline JIT CodeBlock gets
1055     // scanned, we can assume that this means that it's live.
1056     if (!JITCode::isOptimizingJIT(jitType()))
1057         return true;
1058
1059     return false;
1060 }
1061
1062 bool CodeBlock::shouldJettisonDueToWeakReference()
1063 {
1064     if (!JITCode::isOptimizingJIT(jitType()))
1065         return false;
1066     return !Heap::isMarked(this);
1067 }
1068
1069 static Seconds timeToLive(JITCode::JITType jitType)
1070 {
1071     if (UNLIKELY(Options::useEagerCodeBlockJettisonTiming())) {
1072         switch (jitType) {
1073         case JITCode::InterpreterThunk:
1074             return 10_ms;
1075         case JITCode::BaselineJIT:
1076             return 30_ms;
1077         case JITCode::DFGJIT:
1078             return 40_ms;
1079         case JITCode::FTLJIT:
1080             return 120_ms;
1081         default:
1082             return Seconds::infinity();
1083         }
1084     }
1085
1086     switch (jitType) {
1087     case JITCode::InterpreterThunk:
1088         return 5_s;
1089     case JITCode::BaselineJIT:
1090         // Effectively 10 additional seconds, since BaselineJIT and
1091         // InterpreterThunk share a CodeBlock.
1092         return 15_s;
1093     case JITCode::DFGJIT:
1094         return 20_s;
1095     case JITCode::FTLJIT:
1096         return 60_s;
1097     default:
1098         return Seconds::infinity();
1099     }
1100 }
1101
1102 bool CodeBlock::shouldJettisonDueToOldAge(const ConcurrentJSLocker&)
1103 {
1104     if (Heap::isMarked(this))
1105         return false;
1106
1107     if (UNLIKELY(Options::forceCodeBlockToJettisonDueToOldAge()))
1108         return true;
1109     
1110     if (timeSinceCreation() < timeToLive(jitType()))
1111         return false;
1112     
1113     return true;
1114 }
1115
1116 #if ENABLE(DFG_JIT)
1117 static bool shouldMarkTransition(DFG::WeakReferenceTransition& transition)
1118 {
1119     if (transition.m_codeOrigin && !Heap::isMarked(transition.m_codeOrigin.get()))
1120         return false;
1121     
1122     if (!Heap::isMarked(transition.m_from.get()))
1123         return false;
1124     
1125     return true;
1126 }
1127 #endif // ENABLE(DFG_JIT)
1128
1129 void CodeBlock::propagateTransitions(const ConcurrentJSLocker&, SlotVisitor& visitor)
1130 {
1131     UNUSED_PARAM(visitor);
1132
1133     VM& vm = *m_poisonedVM;
1134
1135     if (jitType() == JITCode::InterpreterThunk) {
1136         const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
1137         for (size_t i = 0; i < propertyAccessInstructions.size(); ++i) {
1138             Instruction* instruction = &instructions()[propertyAccessInstructions[i]];
1139             switch (Interpreter::getOpcodeID(instruction[0])) {
1140             case op_put_by_id: {
1141                 StructureID oldStructureID = instruction[4].u.structureID;
1142                 StructureID newStructureID = instruction[6].u.structureID;
1143                 if (!oldStructureID || !newStructureID)
1144                     break;
1145                 Structure* oldStructure =
1146                     vm.heap.structureIDTable().get(oldStructureID);
1147                 Structure* newStructure =
1148                     vm.heap.structureIDTable().get(newStructureID);
1149                 if (Heap::isMarked(oldStructure))
1150                     visitor.appendUnbarriered(newStructure);
1151                 break;
1152             }
1153             default:
1154                 break;
1155             }
1156         }
1157     }
1158
1159 #if ENABLE(JIT)
1160     if (JITCode::isJIT(jitType())) {
1161         for (auto iter = m_stubInfos.begin(); !!iter; ++iter)
1162             (*iter)->propagateTransitions(visitor);
1163     }
1164 #endif // ENABLE(JIT)
1165     
1166 #if ENABLE(DFG_JIT)
1167     if (JITCode::isOptimizingJIT(jitType())) {
1168         DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
1169         for (auto& weakReference : dfgCommon->weakStructureReferences)
1170             weakReference->markIfCheap(visitor);
1171
1172         for (auto& transition : dfgCommon->transitions) {
1173             if (shouldMarkTransition(transition)) {
1174                 // If the following three things are live, then the target of the
1175                 // transition is also live:
1176                 //
1177                 // - This code block. We know it's live already because otherwise
1178                 //   we wouldn't be scanning ourselves.
1179                 //
1180                 // - The code origin of the transition. Transitions may arise from
1181                 //   code that was inlined. They are not relevant if the user's
1182                 //   object that is required for the inlinee to run is no longer
1183                 //   live.
1184                 //
1185                 // - The source of the transition. The transition checks if some
1186                 //   heap location holds the source, and if so, stores the target.
1187                 //   Hence the source must be live for the transition to be live.
1188                 //
1189                 // We also short-circuit the liveness if the structure is harmless
1190                 // to mark (i.e. its global object and prototype are both already
1191                 // live).
1192
1193                 visitor.append(transition.m_to);
1194             }
1195         }
1196     }
1197 #endif // ENABLE(DFG_JIT)
1198 }
1199
1200 void CodeBlock::determineLiveness(const ConcurrentJSLocker&, SlotVisitor& visitor)
1201 {
1202     UNUSED_PARAM(visitor);
1203     
1204 #if ENABLE(DFG_JIT)
1205     if (Heap::isMarked(this))
1206         return;
1207     
1208     // In rare and weird cases, this could be called on a baseline CodeBlock. One that I found was
1209     // that we might decide that the CodeBlock should be jettisoned due to old age, so the
1210     // isMarked check doesn't protect us.
1211     if (!JITCode::isOptimizingJIT(jitType()))
1212         return;
1213     
1214     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
1215     // Now check all of our weak references. If all of them are live, then we
1216     // have proved liveness and so we scan our strong references. If at end of
1217     // GC we still have not proved liveness, then this code block is toast.
1218     bool allAreLiveSoFar = true;
1219     for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
1220         JSCell* reference = dfgCommon->weakReferences[i].get();
1221         ASSERT(!jsDynamicCast<CodeBlock*>(*reference->vm(), reference));
1222         if (!Heap::isMarked(reference)) {
1223             allAreLiveSoFar = false;
1224             break;
1225         }
1226     }
1227     if (allAreLiveSoFar) {
1228         for (unsigned i = 0; i < dfgCommon->weakStructureReferences.size(); ++i) {
1229             if (!Heap::isMarked(dfgCommon->weakStructureReferences[i].get())) {
1230                 allAreLiveSoFar = false;
1231                 break;
1232             }
1233         }
1234     }
1235     
1236     // If some weak references are dead, then this fixpoint iteration was
1237     // unsuccessful.
1238     if (!allAreLiveSoFar)
1239         return;
1240     
1241     // All weak references are live. Record this information so we don't
1242     // come back here again, and scan the strong references.
1243     visitor.appendUnbarriered(this);
1244 #endif // ENABLE(DFG_JIT)
1245 }
1246
1247 void CodeBlock::clearLLIntGetByIdCache(Instruction* instruction)
1248 {
1249     instruction[0].u.opcode = LLInt::getOpcode(op_get_by_id);
1250     instruction[4].u.pointer = nullptr;
1251     instruction[5].u.pointer = nullptr;
1252     instruction[6].u.pointer = nullptr;
1253 }
1254
1255 void CodeBlock::finalizeLLIntInlineCaches()
1256 {
1257     VM& vm = *m_poisonedVM;
1258     const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
1259     for (size_t size = propertyAccessInstructions.size(), i = 0; i < size; ++i) {
1260         Instruction* curInstruction = &instructions()[propertyAccessInstructions[i]];
1261         switch (Interpreter::getOpcodeID(curInstruction[0])) {
1262         case op_get_by_id: {
1263             StructureID oldStructureID = curInstruction[4].u.structureID;
1264             if (!oldStructureID || Heap::isMarked(vm.heap.structureIDTable().get(oldStructureID)))
1265                 break;
1266             if (Options::verboseOSR())
1267                 dataLogF("Clearing LLInt property access.\n");
1268             clearLLIntGetByIdCache(curInstruction);
1269             break;
1270         }
1271         case op_get_by_id_direct: {
1272             StructureID oldStructureID = curInstruction[4].u.structureID;
1273             if (!oldStructureID || Heap::isMarked(vm.heap.structureIDTable().get(oldStructureID)))
1274                 break;
1275             if (Options::verboseOSR())
1276                 dataLogF("Clearing LLInt property access.\n");
1277             curInstruction[4].u.pointer = nullptr;
1278             curInstruction[5].u.pointer = nullptr;
1279             break;
1280         }
1281         case op_put_by_id: {
1282             StructureID oldStructureID = curInstruction[4].u.structureID;
1283             StructureID newStructureID = curInstruction[6].u.structureID;
1284             StructureChain* chain = curInstruction[7].u.structureChain.get();
1285             if ((!oldStructureID || Heap::isMarked(vm.heap.structureIDTable().get(oldStructureID)))
1286                 && (!newStructureID || Heap::isMarked(vm.heap.structureIDTable().get(newStructureID)))
1287                 && (!chain || Heap::isMarked(chain)))
1288                 break;
1289             if (Options::verboseOSR())
1290                 dataLogF("Clearing LLInt put transition.\n");
1291             curInstruction[4].u.structureID = 0;
1292             curInstruction[5].u.operand = 0;
1293             curInstruction[6].u.structureID = 0;
1294             curInstruction[7].u.structureChain.clear();
1295             break;
1296         }
1297         // FIXME: https://bugs.webkit.org/show_bug.cgi?id=166418
1298         // We need to add optimizations for op_resolve_scope_for_hoisting_func_decl_in_eval to do link time scope resolution.
1299         case op_resolve_scope_for_hoisting_func_decl_in_eval:
1300             break;
1301         case op_get_by_id_proto_load:
1302         case op_get_by_id_unset:
1303         case op_get_array_length:
1304             break;
1305         case op_to_this:
1306             if (!curInstruction[2].u.structure || Heap::isMarked(curInstruction[2].u.structure.get()))
1307                 break;
1308             if (Options::verboseOSR())
1309                 dataLogF("Clearing LLInt to_this with structure %p.\n", curInstruction[2].u.structure.get());
1310             curInstruction[2].u.structure.clear();
1311             curInstruction[3].u.toThisStatus = merge(
1312                 curInstruction[3].u.toThisStatus, ToThisClearedByGC);
1313             break;
1314         case op_create_this: {
1315             auto& cacheWriteBarrier = curInstruction[4].u.jsCell;
1316             if (!cacheWriteBarrier || cacheWriteBarrier.unvalidatedGet() == JSCell::seenMultipleCalleeObjects())
1317                 break;
1318             JSCell* cachedFunction = cacheWriteBarrier.get();
1319             if (Heap::isMarked(cachedFunction))
1320                 break;
1321             if (Options::verboseOSR())
1322                 dataLogF("Clearing LLInt create_this with cached callee %p.\n", cachedFunction);
1323             cacheWriteBarrier.clear();
1324             break;
1325         }
1326         case op_resolve_scope: {
1327             // Right now this isn't strictly necessary. Any symbol tables that this will refer to
1328             // are for outer functions, and we refer to those functions strongly, and they refer
1329             // to the symbol table strongly. But it's nice to be on the safe side.
1330             WriteBarrierBase<SymbolTable>& symbolTable = curInstruction[6].u.symbolTable;
1331             if (!symbolTable || Heap::isMarked(symbolTable.get()))
1332                 break;
1333             if (Options::verboseOSR())
1334                 dataLogF("Clearing dead symbolTable %p.\n", symbolTable.get());
1335             symbolTable.clear();
1336             break;
1337         }
1338         case op_get_from_scope:
1339         case op_put_to_scope: {
1340             GetPutInfo getPutInfo = GetPutInfo(curInstruction[4].u.operand);
1341             if (getPutInfo.resolveType() == GlobalVar || getPutInfo.resolveType() == GlobalVarWithVarInjectionChecks 
1342                 || getPutInfo.resolveType() == LocalClosureVar || getPutInfo.resolveType() == GlobalLexicalVar || getPutInfo.resolveType() == GlobalLexicalVarWithVarInjectionChecks)
1343                 continue;
1344             WriteBarrierBase<Structure>& structure = curInstruction[5].u.structure;
1345             if (!structure || Heap::isMarked(structure.get()))
1346                 break;
1347             if (Options::verboseOSR())
1348                 dataLogF("Clearing scope access with structure %p.\n", structure.get());
1349             structure.clear();
1350             break;
1351         }
1352         default:
1353             OpcodeID opcodeID = Interpreter::getOpcodeID(curInstruction[0]);
1354             ASSERT_WITH_MESSAGE_UNUSED(opcodeID, false, "Unhandled opcode in CodeBlock::finalizeUnconditionally, %s(%d) at bc %u", opcodeNames[opcodeID], opcodeID, propertyAccessInstructions[i]);
1355         }
1356     }
1357
1358     // We can't just remove all the sets when we clear the caches since we might have created a watchpoint set
1359     // then cleared the cache without GCing in between.
1360     m_llintGetByIdWatchpointMap.removeIf([&] (const StructureWatchpointMap::KeyValuePairType& pair) -> bool {
1361         auto clear = [&] () {
1362             Instruction* instruction = std::get<1>(pair.key);
1363             OpcodeID opcode = Interpreter::getOpcodeID(*instruction);
1364             if (opcode == op_get_by_id_proto_load || opcode == op_get_by_id_unset) {
1365                 if (Options::verboseOSR())
1366                     dataLogF("Clearing LLInt property access.\n");
1367                 clearLLIntGetByIdCache(instruction);
1368             }
1369             return true;
1370         };
1371
1372         if (!Heap::isMarked(std::get<0>(pair.key)))
1373             return clear();
1374
1375         for (const LLIntPrototypeLoadAdaptiveStructureWatchpoint* watchpoint : pair.value) {
1376             if (!watchpoint->key().isStillLive())
1377                 return clear();
1378         }
1379
1380         return false;
1381     });
1382
1383     for (unsigned i = 0; i < m_llintCallLinkInfos.size(); ++i) {
1384         if (m_llintCallLinkInfos[i].isLinked() && !Heap::isMarked(m_llintCallLinkInfos[i].callee.get())) {
1385             if (Options::verboseOSR())
1386                 dataLog("Clearing LLInt call from ", *this, "\n");
1387             m_llintCallLinkInfos[i].unlink();
1388         }
1389         if (!!m_llintCallLinkInfos[i].lastSeenCallee && !Heap::isMarked(m_llintCallLinkInfos[i].lastSeenCallee.get()))
1390             m_llintCallLinkInfos[i].lastSeenCallee.clear();
1391     }
1392 }
1393
1394 void CodeBlock::finalizeBaselineJITInlineCaches()
1395 {
1396 #if ENABLE(JIT)
1397     for (auto iter = callLinkInfosBegin(); !!iter; ++iter)
1398         (*iter)->visitWeak(*vm());
1399
1400     for (auto iter = m_stubInfos.begin(); !!iter; ++iter) {
1401         StructureStubInfo& stubInfo = **iter;
1402         stubInfo.visitWeakReferences(this);
1403     }
1404 #endif
1405 }
1406
1407 void CodeBlock::finalizeUnconditionally(VM&)
1408 {
1409     updateAllPredictions();
1410     
1411     if (JITCode::couldBeInterpreted(jitType()))
1412         finalizeLLIntInlineCaches();
1413
1414 #if ENABLE(JIT)
1415     if (!!jitCode())
1416         finalizeBaselineJITInlineCaches();
1417 #endif
1418
1419     VM::SpaceAndFinalizerSet::finalizerSetFor(*subspace()).remove(this);
1420 }
1421
1422 void CodeBlock::getStubInfoMap(const ConcurrentJSLocker&, StubInfoMap& result)
1423 {
1424 #if ENABLE(JIT)
1425     if (JITCode::isJIT(jitType()))
1426         toHashMap(m_stubInfos, getStructureStubInfoCodeOrigin, result);
1427 #else
1428     UNUSED_PARAM(result);
1429 #endif
1430 }
1431
1432 void CodeBlock::getStubInfoMap(StubInfoMap& result)
1433 {
1434     ConcurrentJSLocker locker(m_lock);
1435     getStubInfoMap(locker, result);
1436 }
1437
1438 void CodeBlock::getCallLinkInfoMap(const ConcurrentJSLocker&, CallLinkInfoMap& result)
1439 {
1440 #if ENABLE(JIT)
1441     if (JITCode::isJIT(jitType()))
1442         toHashMap(m_callLinkInfos, getCallLinkInfoCodeOrigin, result);
1443 #else
1444     UNUSED_PARAM(result);
1445 #endif
1446 }
1447
1448 void CodeBlock::getCallLinkInfoMap(CallLinkInfoMap& result)
1449 {
1450     ConcurrentJSLocker locker(m_lock);
1451     getCallLinkInfoMap(locker, result);
1452 }
1453
1454 void CodeBlock::getByValInfoMap(const ConcurrentJSLocker&, ByValInfoMap& result)
1455 {
1456 #if ENABLE(JIT)
1457     if (JITCode::isJIT(jitType())) {
1458         for (auto* byValInfo : m_byValInfos)
1459             result.add(CodeOrigin(byValInfo->bytecodeIndex), byValInfo);
1460     }
1461 #else
1462     UNUSED_PARAM(result);
1463 #endif
1464 }
1465
1466 void CodeBlock::getByValInfoMap(ByValInfoMap& result)
1467 {
1468     ConcurrentJSLocker locker(m_lock);
1469     getByValInfoMap(locker, result);
1470 }
1471
1472 #if ENABLE(JIT)
1473 StructureStubInfo* CodeBlock::addStubInfo(AccessType accessType)
1474 {
1475     ConcurrentJSLocker locker(m_lock);
1476     return m_stubInfos.add(accessType);
1477 }
1478
1479 JITAddIC* CodeBlock::addJITAddIC(ArithProfile* arithProfile, Instruction* instruction)
1480 {
1481     return m_addICs.add(arithProfile, instruction);
1482 }
1483
1484 JITMulIC* CodeBlock::addJITMulIC(ArithProfile* arithProfile, Instruction* instruction)
1485 {
1486     return m_mulICs.add(arithProfile, instruction);
1487 }
1488
1489 JITSubIC* CodeBlock::addJITSubIC(ArithProfile* arithProfile, Instruction* instruction)
1490 {
1491     return m_subICs.add(arithProfile, instruction);
1492 }
1493
1494 JITNegIC* CodeBlock::addJITNegIC(ArithProfile* arithProfile, Instruction* instruction)
1495 {
1496     return m_negICs.add(arithProfile, instruction);
1497 }
1498
1499 StructureStubInfo* CodeBlock::findStubInfo(CodeOrigin codeOrigin)
1500 {
1501     for (StructureStubInfo* stubInfo : m_stubInfos) {
1502         if (stubInfo->codeOrigin == codeOrigin)
1503             return stubInfo;
1504     }
1505     return nullptr;
1506 }
1507
1508 ByValInfo* CodeBlock::addByValInfo()
1509 {
1510     ConcurrentJSLocker locker(m_lock);
1511     return m_byValInfos.add();
1512 }
1513
1514 CallLinkInfo* CodeBlock::addCallLinkInfo()
1515 {
1516     ConcurrentJSLocker locker(m_lock);
1517     return m_callLinkInfos.add();
1518 }
1519
1520 CallLinkInfo* CodeBlock::getCallLinkInfoForBytecodeIndex(unsigned index)
1521 {
1522     for (auto iter = m_callLinkInfos.begin(); !!iter; ++iter) {
1523         if ((*iter)->codeOrigin() == CodeOrigin(index))
1524             return *iter;
1525     }
1526     return nullptr;
1527 }
1528
1529 void CodeBlock::resetJITData()
1530 {
1531     RELEASE_ASSERT(!JITCode::isJIT(jitType()));
1532     ConcurrentJSLocker locker(m_lock);
1533     
1534     // We can clear these because no other thread will have references to any stub infos, call
1535     // link infos, or by val infos if we don't have JIT code. Attempts to query these data
1536     // structures using the concurrent API (getStubInfoMap and friends) will return nothing if we
1537     // don't have JIT code.
1538     m_stubInfos.clear();
1539     m_callLinkInfos.clear();
1540     m_byValInfos.clear();
1541     
1542     // We can clear this because the DFG's queries to these data structures are guarded by whether
1543     // there is JIT code.
1544     m_rareCaseProfiles.clear();
1545 }
1546 #endif
1547
1548 void CodeBlock::visitOSRExitTargets(const ConcurrentJSLocker&, SlotVisitor& visitor)
1549 {
1550     // We strongly visit OSR exits targets because we don't want to deal with
1551     // the complexity of generating an exit target CodeBlock on demand and
1552     // guaranteeing that it matches the details of the CodeBlock we compiled
1553     // the OSR exit against.
1554
1555     visitor.append(m_alternative);
1556
1557 #if ENABLE(DFG_JIT)
1558     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
1559     if (dfgCommon->inlineCallFrames) {
1560         for (auto* inlineCallFrame : *dfgCommon->inlineCallFrames) {
1561             ASSERT(inlineCallFrame->baselineCodeBlock);
1562             visitor.append(inlineCallFrame->baselineCodeBlock);
1563         }
1564     }
1565 #endif
1566 }
1567
1568 void CodeBlock::stronglyVisitStrongReferences(const ConcurrentJSLocker& locker, SlotVisitor& visitor)
1569 {
1570     UNUSED_PARAM(locker);
1571     
1572     visitor.append(m_globalObject);
1573     visitor.append(m_ownerExecutable); // This is extra important since it causes the ExecutableToCodeBlockEdge to be marked.
1574     visitor.append(m_unlinkedCode);
1575     if (m_rareData)
1576         m_rareData->m_directEvalCodeCache.visitAggregate(visitor);
1577     visitor.appendValues(m_constantRegisters.data(), m_constantRegisters.size());
1578     for (auto& functionExpr : m_functionExprs)
1579         visitor.append(functionExpr);
1580     for (auto& functionDecl : m_functionDecls)
1581         visitor.append(functionDecl);
1582     for (auto& objectAllocationProfile : m_objectAllocationProfiles)
1583         objectAllocationProfile.visitAggregate(visitor);
1584
1585 #if ENABLE(JIT)
1586     for (ByValInfo* byValInfo : m_byValInfos)
1587         visitor.append(byValInfo->cachedSymbol);
1588 #endif
1589
1590 #if ENABLE(DFG_JIT)
1591     if (JITCode::isOptimizingJIT(jitType()))
1592         visitOSRExitTargets(locker, visitor);
1593 #endif
1594 }
1595
1596 void CodeBlock::stronglyVisitWeakReferences(const ConcurrentJSLocker&, SlotVisitor& visitor)
1597 {
1598     UNUSED_PARAM(visitor);
1599
1600 #if ENABLE(DFG_JIT)
1601     if (!JITCode::isOptimizingJIT(jitType()))
1602         return;
1603     
1604     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
1605
1606     for (auto& transition : dfgCommon->transitions) {
1607         if (!!transition.m_codeOrigin)
1608             visitor.append(transition.m_codeOrigin); // Almost certainly not necessary, since the code origin should also be a weak reference. Better to be safe, though.
1609         visitor.append(transition.m_from);
1610         visitor.append(transition.m_to);
1611     }
1612
1613     for (auto& weakReference : dfgCommon->weakReferences)
1614         visitor.append(weakReference);
1615
1616     for (auto& weakStructureReference : dfgCommon->weakStructureReferences)
1617         visitor.append(weakStructureReference);
1618
1619     dfgCommon->livenessHasBeenProved = true;
1620 #endif    
1621 }
1622
1623 CodeBlock* CodeBlock::baselineAlternative()
1624 {
1625 #if ENABLE(JIT)
1626     CodeBlock* result = this;
1627     while (result->alternative())
1628         result = result->alternative();
1629     RELEASE_ASSERT(result);
1630     RELEASE_ASSERT(JITCode::isBaselineCode(result->jitType()) || result->jitType() == JITCode::None);
1631     return result;
1632 #else
1633     return this;
1634 #endif
1635 }
1636
1637 CodeBlock* CodeBlock::baselineVersion()
1638 {
1639 #if ENABLE(JIT)
1640     if (JITCode::isBaselineCode(jitType()))
1641         return this;
1642     CodeBlock* result = replacement();
1643     if (!result) {
1644         // This can happen if we're creating the original CodeBlock for an executable.
1645         // Assume that we're the baseline CodeBlock.
1646         RELEASE_ASSERT(jitType() == JITCode::None);
1647         return this;
1648     }
1649     result = result->baselineAlternative();
1650     return result;
1651 #else
1652     return this;
1653 #endif
1654 }
1655
1656 #if ENABLE(JIT)
1657 bool CodeBlock::hasOptimizedReplacement(JITCode::JITType typeToReplace)
1658 {
1659     return JITCode::isHigherTier(replacement()->jitType(), typeToReplace);
1660 }
1661
1662 bool CodeBlock::hasOptimizedReplacement()
1663 {
1664     return hasOptimizedReplacement(jitType());
1665 }
1666 #endif
1667
1668 HandlerInfo* CodeBlock::handlerForBytecodeOffset(unsigned bytecodeOffset, RequiredHandler requiredHandler)
1669 {
1670     RELEASE_ASSERT(bytecodeOffset < instructions().size());
1671     return handlerForIndex(bytecodeOffset, requiredHandler);
1672 }
1673
1674 HandlerInfo* CodeBlock::handlerForIndex(unsigned index, RequiredHandler requiredHandler)
1675 {
1676     if (!m_rareData)
1677         return 0;
1678     return HandlerInfo::handlerForIndex(m_rareData->m_exceptionHandlers, index, requiredHandler);
1679 }
1680
1681 CallSiteIndex CodeBlock::newExceptionHandlingCallSiteIndex(CallSiteIndex originalCallSite)
1682 {
1683 #if ENABLE(DFG_JIT)
1684     RELEASE_ASSERT(JITCode::isOptimizingJIT(jitType()));
1685     RELEASE_ASSERT(canGetCodeOrigin(originalCallSite));
1686     ASSERT(!!handlerForIndex(originalCallSite.bits()));
1687     CodeOrigin originalOrigin = codeOrigin(originalCallSite);
1688     return m_jitCode->dfgCommon()->addUniqueCallSiteIndex(originalOrigin);
1689 #else
1690     // We never create new on-the-fly exception handling
1691     // call sites outside the DFG/FTL inline caches.
1692     UNUSED_PARAM(originalCallSite);
1693     RELEASE_ASSERT_NOT_REACHED();
1694     return CallSiteIndex(0u);
1695 #endif
1696 }
1697
1698 void CodeBlock::ensureCatchLivenessIsComputedForBytecodeOffsetSlow(unsigned bytecodeOffset)
1699 {
1700     ASSERT(Interpreter::getOpcodeID(m_instructions[bytecodeOffset]) == op_catch);
1701     BytecodeLivenessAnalysis& bytecodeLiveness = livenessAnalysis();
1702
1703     // We get the live-out set of variables at op_catch, not the live-in. This
1704     // is because the variables that the op_catch defines might be dead, and
1705     // we can avoid profiling them and extracting them when doing OSR entry
1706     // into the DFG.
1707     FastBitVector liveLocals = bytecodeLiveness.getLivenessInfoAtBytecodeOffset(this, bytecodeOffset + OPCODE_LENGTH(op_catch));
1708     Vector<VirtualRegister> liveOperands;
1709     liveOperands.reserveInitialCapacity(liveLocals.bitCount());
1710     liveLocals.forEachSetBit([&] (unsigned liveLocal) {
1711         liveOperands.append(virtualRegisterForLocal(liveLocal));
1712     });
1713
1714     for (int i = 0; i < numParameters(); ++i)
1715         liveOperands.append(virtualRegisterForArgument(i));
1716
1717     auto profiles = std::make_unique<ValueProfileAndOperandBuffer>(liveOperands.size());
1718     RELEASE_ASSERT(profiles->m_size == liveOperands.size());
1719     for (unsigned i = 0; i < profiles->m_size; ++i)
1720         profiles->m_buffer.get()[i].m_operand = liveOperands[i].offset();
1721
1722     // The compiler thread will read this pointer value and then proceed to dereference it
1723     // if it is not null. We need to make sure all above stores happen before this store so
1724     // the compiler thread reads fully initialized data.
1725     WTF::storeStoreFence(); 
1726
1727     m_instructions[bytecodeOffset + 3].u.pointer = profiles.get();
1728
1729     {
1730         ConcurrentJSLocker locker(m_lock);
1731         m_catchProfiles.append(WTFMove(profiles));
1732     }
1733 }
1734
1735 void CodeBlock::removeExceptionHandlerForCallSite(CallSiteIndex callSiteIndex)
1736 {
1737     RELEASE_ASSERT(m_rareData);
1738     Vector<HandlerInfo>& exceptionHandlers = m_rareData->m_exceptionHandlers;
1739     unsigned index = callSiteIndex.bits();
1740     for (size_t i = 0; i < exceptionHandlers.size(); ++i) {
1741         HandlerInfo& handler = exceptionHandlers[i];
1742         if (handler.start <= index && handler.end > index) {
1743             exceptionHandlers.remove(i);
1744             return;
1745         }
1746     }
1747
1748     RELEASE_ASSERT_NOT_REACHED();
1749 }
1750
1751 unsigned CodeBlock::lineNumberForBytecodeOffset(unsigned bytecodeOffset)
1752 {
1753     RELEASE_ASSERT(bytecodeOffset < instructions().size());
1754     return ownerScriptExecutable()->firstLine() + m_unlinkedCode->lineNumberForBytecodeOffset(bytecodeOffset);
1755 }
1756
1757 unsigned CodeBlock::columnNumberForBytecodeOffset(unsigned bytecodeOffset)
1758 {
1759     int divot;
1760     int startOffset;
1761     int endOffset;
1762     unsigned line;
1763     unsigned column;
1764     expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
1765     return column;
1766 }
1767
1768 void CodeBlock::expressionRangeForBytecodeOffset(unsigned bytecodeOffset, int& divot, int& startOffset, int& endOffset, unsigned& line, unsigned& column) const
1769 {
1770     m_unlinkedCode->expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
1771     divot += m_sourceOffset;
1772     column += line ? 1 : firstLineColumnOffset();
1773     line += ownerScriptExecutable()->firstLine();
1774 }
1775
1776 bool CodeBlock::hasOpDebugForLineAndColumn(unsigned line, unsigned column)
1777 {
1778     const Instruction* begin = instructions().begin();
1779     const Instruction* end = instructions().end();
1780     for (const Instruction* it = begin; it != end;) {
1781         OpcodeID opcodeID = Interpreter::getOpcodeID(*it);
1782         if (opcodeID == op_debug) {
1783             unsigned bytecodeOffset = it - begin;
1784             int unused;
1785             unsigned opDebugLine;
1786             unsigned opDebugColumn;
1787             expressionRangeForBytecodeOffset(bytecodeOffset, unused, unused, unused, opDebugLine, opDebugColumn);
1788             if (line == opDebugLine && (column == Breakpoint::unspecifiedColumn || column == opDebugColumn))
1789                 return true;
1790         }
1791         it += opcodeLengths[opcodeID];
1792     }
1793     return false;
1794 }
1795
1796 void CodeBlock::shrinkToFit(ShrinkMode shrinkMode)
1797 {
1798     ConcurrentJSLocker locker(m_lock);
1799
1800     m_rareCaseProfiles.shrinkToFit();
1801     
1802     if (shrinkMode == EarlyShrink) {
1803         m_constantRegisters.shrinkToFit();
1804         m_constantsSourceCodeRepresentation.shrinkToFit();
1805         
1806         if (m_rareData) {
1807             m_rareData->m_switchJumpTables.shrinkToFit();
1808             m_rareData->m_stringSwitchJumpTables.shrinkToFit();
1809         }
1810     } // else don't shrink these, because we would have already pointed pointers into these tables.
1811 }
1812
1813 #if ENABLE(JIT)
1814 void CodeBlock::linkIncomingCall(ExecState* callerFrame, CallLinkInfo* incoming)
1815 {
1816     noticeIncomingCall(callerFrame);
1817     m_incomingCalls.push(incoming);
1818 }
1819
1820 void CodeBlock::linkIncomingPolymorphicCall(ExecState* callerFrame, PolymorphicCallNode* incoming)
1821 {
1822     noticeIncomingCall(callerFrame);
1823     m_incomingPolymorphicCalls.push(incoming);
1824 }
1825 #endif // ENABLE(JIT)
1826
1827 void CodeBlock::unlinkIncomingCalls()
1828 {
1829     while (m_incomingLLIntCalls.begin() != m_incomingLLIntCalls.end())
1830         m_incomingLLIntCalls.begin()->unlink();
1831 #if ENABLE(JIT)
1832     while (m_incomingCalls.begin() != m_incomingCalls.end())
1833         m_incomingCalls.begin()->unlink(*vm());
1834     while (m_incomingPolymorphicCalls.begin() != m_incomingPolymorphicCalls.end())
1835         m_incomingPolymorphicCalls.begin()->unlink(*vm());
1836 #endif // ENABLE(JIT)
1837 }
1838
1839 void CodeBlock::linkIncomingCall(ExecState* callerFrame, LLIntCallLinkInfo* incoming)
1840 {
1841     noticeIncomingCall(callerFrame);
1842     m_incomingLLIntCalls.push(incoming);
1843 }
1844
1845 CodeBlock* CodeBlock::newReplacement()
1846 {
1847     return ownerScriptExecutable()->newReplacementCodeBlockFor(specializationKind());
1848 }
1849
1850 #if ENABLE(JIT)
1851 CodeBlock* CodeBlock::replacement()
1852 {
1853     const ClassInfo* classInfo = this->classInfo(*vm());
1854
1855     if (classInfo == FunctionCodeBlock::info())
1856         return jsCast<FunctionExecutable*>(ownerExecutable())->codeBlockFor(m_isConstructor ? CodeForConstruct : CodeForCall);
1857
1858     if (classInfo == EvalCodeBlock::info())
1859         return jsCast<EvalExecutable*>(ownerExecutable())->codeBlock();
1860
1861     if (classInfo == ProgramCodeBlock::info())
1862         return jsCast<ProgramExecutable*>(ownerExecutable())->codeBlock();
1863
1864     if (classInfo == ModuleProgramCodeBlock::info())
1865         return jsCast<ModuleProgramExecutable*>(ownerExecutable())->codeBlock();
1866
1867     RELEASE_ASSERT_NOT_REACHED();
1868     return nullptr;
1869 }
1870
1871 DFG::CapabilityLevel CodeBlock::computeCapabilityLevel()
1872 {
1873     const ClassInfo* classInfo = this->classInfo(*vm());
1874
1875     if (classInfo == FunctionCodeBlock::info()) {
1876         if (m_isConstructor)
1877             return DFG::functionForConstructCapabilityLevel(this);
1878         return DFG::functionForCallCapabilityLevel(this);
1879     }
1880
1881     if (classInfo == EvalCodeBlock::info())
1882         return DFG::evalCapabilityLevel(this);
1883
1884     if (classInfo == ProgramCodeBlock::info())
1885         return DFG::programCapabilityLevel(this);
1886
1887     if (classInfo == ModuleProgramCodeBlock::info())
1888         return DFG::programCapabilityLevel(this);
1889
1890     RELEASE_ASSERT_NOT_REACHED();
1891     return DFG::CannotCompile;
1892 }
1893
1894 #endif // ENABLE(JIT)
1895
1896 void CodeBlock::jettison(Profiler::JettisonReason reason, ReoptimizationMode mode, const FireDetail* detail)
1897 {
1898 #if !ENABLE(DFG_JIT)
1899     UNUSED_PARAM(mode);
1900     UNUSED_PARAM(detail);
1901 #endif
1902     
1903     CODEBLOCK_LOG_EVENT(this, "jettison", ("due to ", reason, ", counting = ", mode == CountReoptimization, ", detail = ", pointerDump(detail)));
1904
1905     RELEASE_ASSERT(reason != Profiler::NotJettisoned);
1906     
1907 #if ENABLE(DFG_JIT)
1908     if (DFG::shouldDumpDisassembly()) {
1909         dataLog("Jettisoning ", *this);
1910         if (mode == CountReoptimization)
1911             dataLog(" and counting reoptimization");
1912         dataLog(" due to ", reason);
1913         if (detail)
1914             dataLog(", ", *detail);
1915         dataLog(".\n");
1916     }
1917     
1918     if (reason == Profiler::JettisonDueToWeakReference) {
1919         if (DFG::shouldDumpDisassembly()) {
1920             dataLog(*this, " will be jettisoned because of the following dead references:\n");
1921             DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
1922             for (auto& transition : dfgCommon->transitions) {
1923                 JSCell* origin = transition.m_codeOrigin.get();
1924                 JSCell* from = transition.m_from.get();
1925                 JSCell* to = transition.m_to.get();
1926                 if ((!origin || Heap::isMarked(origin)) && Heap::isMarked(from))
1927                     continue;
1928                 dataLog("    Transition under ", RawPointer(origin), ", ", RawPointer(from), " -> ", RawPointer(to), ".\n");
1929             }
1930             for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
1931                 JSCell* weak = dfgCommon->weakReferences[i].get();
1932                 if (Heap::isMarked(weak))
1933                     continue;
1934                 dataLog("    Weak reference ", RawPointer(weak), ".\n");
1935             }
1936         }
1937     }
1938 #endif // ENABLE(DFG_JIT)
1939
1940     VM& vm = *m_poisonedVM;
1941     DeferGCForAWhile deferGC(*heap());
1942     
1943     // We want to accomplish two things here:
1944     // 1) Make sure that if this CodeBlock is on the stack right now, then if we return to it
1945     //    we should OSR exit at the top of the next bytecode instruction after the return.
1946     // 2) Make sure that if we call the owner executable, then we shouldn't call this CodeBlock.
1947
1948 #if ENABLE(DFG_JIT)
1949     if (reason != Profiler::JettisonDueToOldAge) {
1950         Profiler::Compilation* compilation = jitCode()->dfgCommon()->compilation.get();
1951         if (UNLIKELY(compilation))
1952             compilation->setJettisonReason(reason, detail);
1953         
1954         // This accomplishes (1), and does its own book-keeping about whether it has already happened.
1955         if (!jitCode()->dfgCommon()->invalidate()) {
1956             // We've already been invalidated.
1957             RELEASE_ASSERT(this != replacement() || (vm.heap.isCurrentThreadBusy() && !Heap::isMarked(ownerScriptExecutable())));
1958             return;
1959         }
1960     }
1961     
1962     if (DFG::shouldDumpDisassembly())
1963         dataLog("    Did invalidate ", *this, "\n");
1964     
1965     // Count the reoptimization if that's what the user wanted.
1966     if (mode == CountReoptimization) {
1967         // FIXME: Maybe this should call alternative().
1968         // https://bugs.webkit.org/show_bug.cgi?id=123677
1969         baselineAlternative()->countReoptimization();
1970         if (DFG::shouldDumpDisassembly())
1971             dataLog("    Did count reoptimization for ", *this, "\n");
1972     }
1973     
1974     if (this != replacement()) {
1975         // This means that we were never the entrypoint. This can happen for OSR entry code
1976         // blocks.
1977         return;
1978     }
1979
1980     if (alternative())
1981         alternative()->optimizeAfterWarmUp();
1982
1983     if (reason != Profiler::JettisonDueToOldAge && reason != Profiler::JettisonDueToVMTraps)
1984         tallyFrequentExitSites();
1985 #endif // ENABLE(DFG_JIT)
1986
1987     // Jettison can happen during GC. We don't want to install code to a dead executable
1988     // because that would add a dead object to the remembered set.
1989     if (vm.heap.isCurrentThreadBusy() && !Heap::isMarked(ownerScriptExecutable()))
1990         return;
1991
1992     // This accomplishes (2).
1993     ownerScriptExecutable()->installCode(vm, alternative(), codeType(), specializationKind());
1994
1995 #if ENABLE(DFG_JIT)
1996     if (DFG::shouldDumpDisassembly())
1997         dataLog("    Did install baseline version of ", *this, "\n");
1998 #endif // ENABLE(DFG_JIT)
1999 }
2000
2001 JSGlobalObject* CodeBlock::globalObjectFor(CodeOrigin codeOrigin)
2002 {
2003     if (!codeOrigin.inlineCallFrame)
2004         return globalObject();
2005     return codeOrigin.inlineCallFrame->baselineCodeBlock->globalObject();
2006 }
2007
2008 class RecursionCheckFunctor {
2009 public:
2010     RecursionCheckFunctor(CallFrame* startCallFrame, CodeBlock* codeBlock, unsigned depthToCheck)
2011         : m_startCallFrame(startCallFrame)
2012         , m_codeBlock(codeBlock)
2013         , m_depthToCheck(depthToCheck)
2014         , m_foundStartCallFrame(false)
2015         , m_didRecurse(false)
2016     { }
2017
2018     StackVisitor::Status operator()(StackVisitor& visitor) const
2019     {
2020         CallFrame* currentCallFrame = visitor->callFrame();
2021
2022         if (currentCallFrame == m_startCallFrame)
2023             m_foundStartCallFrame = true;
2024
2025         if (m_foundStartCallFrame) {
2026             if (visitor->callFrame()->codeBlock() == m_codeBlock) {
2027                 m_didRecurse = true;
2028                 return StackVisitor::Done;
2029             }
2030
2031             if (!m_depthToCheck--)
2032                 return StackVisitor::Done;
2033         }
2034
2035         return StackVisitor::Continue;
2036     }
2037
2038     bool didRecurse() const { return m_didRecurse; }
2039
2040 private:
2041     CallFrame* m_startCallFrame;
2042     CodeBlock* m_codeBlock;
2043     mutable unsigned m_depthToCheck;
2044     mutable bool m_foundStartCallFrame;
2045     mutable bool m_didRecurse;
2046 };
2047
2048 void CodeBlock::noticeIncomingCall(ExecState* callerFrame)
2049 {
2050     CodeBlock* callerCodeBlock = callerFrame->codeBlock();
2051     
2052     if (Options::verboseCallLink())
2053         dataLog("Noticing call link from ", pointerDump(callerCodeBlock), " to ", *this, "\n");
2054     
2055 #if ENABLE(DFG_JIT)
2056     if (!m_shouldAlwaysBeInlined)
2057         return;
2058     
2059     if (!callerCodeBlock) {
2060         m_shouldAlwaysBeInlined = false;
2061         if (Options::verboseCallLink())
2062             dataLog("    Clearing SABI because caller is native.\n");
2063         return;
2064     }
2065
2066     if (!hasBaselineJITProfiling())
2067         return;
2068
2069     if (!DFG::mightInlineFunction(this))
2070         return;
2071
2072     if (!canInline(capabilityLevelState()))
2073         return;
2074     
2075     if (!DFG::isSmallEnoughToInlineCodeInto(callerCodeBlock)) {
2076         m_shouldAlwaysBeInlined = false;
2077         if (Options::verboseCallLink())
2078             dataLog("    Clearing SABI because caller is too large.\n");
2079         return;
2080     }
2081
2082     if (callerCodeBlock->jitType() == JITCode::InterpreterThunk) {
2083         // If the caller is still in the interpreter, then we can't expect inlining to
2084         // happen anytime soon. Assume it's profitable to optimize it separately. This
2085         // ensures that a function is SABI only if it is called no more frequently than
2086         // any of its callers.
2087         m_shouldAlwaysBeInlined = false;
2088         if (Options::verboseCallLink())
2089             dataLog("    Clearing SABI because caller is in LLInt.\n");
2090         return;
2091     }
2092     
2093     if (JITCode::isOptimizingJIT(callerCodeBlock->jitType())) {
2094         m_shouldAlwaysBeInlined = false;
2095         if (Options::verboseCallLink())
2096             dataLog("    Clearing SABI bcause caller was already optimized.\n");
2097         return;
2098     }
2099     
2100     if (callerCodeBlock->codeType() != FunctionCode) {
2101         // If the caller is either eval or global code, assume that that won't be
2102         // optimized anytime soon. For eval code this is particularly true since we
2103         // delay eval optimization by a *lot*.
2104         m_shouldAlwaysBeInlined = false;
2105         if (Options::verboseCallLink())
2106             dataLog("    Clearing SABI because caller is not a function.\n");
2107         return;
2108     }
2109
2110     // Recursive calls won't be inlined.
2111     RecursionCheckFunctor functor(callerFrame, this, Options::maximumInliningDepth());
2112     vm()->topCallFrame->iterate(functor);
2113
2114     if (functor.didRecurse()) {
2115         if (Options::verboseCallLink())
2116             dataLog("    Clearing SABI because recursion was detected.\n");
2117         m_shouldAlwaysBeInlined = false;
2118         return;
2119     }
2120     
2121     if (callerCodeBlock->capabilityLevelState() == DFG::CapabilityLevelNotSet) {
2122         dataLog("In call from ", FullCodeOrigin(callerCodeBlock, callerFrame->codeOrigin()), " to ", *this, ": caller's DFG capability level is not set.\n");
2123         CRASH();
2124     }
2125     
2126     if (canCompile(callerCodeBlock->capabilityLevelState()))
2127         return;
2128     
2129     if (Options::verboseCallLink())
2130         dataLog("    Clearing SABI because the caller is not a DFG candidate.\n");
2131     
2132     m_shouldAlwaysBeInlined = false;
2133 #endif
2134 }
2135
2136 unsigned CodeBlock::reoptimizationRetryCounter() const
2137 {
2138 #if ENABLE(JIT)
2139     ASSERT(m_reoptimizationRetryCounter <= Options::reoptimizationRetryCounterMax());
2140     return m_reoptimizationRetryCounter;
2141 #else
2142     return 0;
2143 #endif // ENABLE(JIT)
2144 }
2145
2146 #if ENABLE(JIT)
2147 void CodeBlock::setCalleeSaveRegisters(RegisterSet calleeSaveRegisters)
2148 {
2149     m_calleeSaveRegisters = std::make_unique<RegisterAtOffsetList>(calleeSaveRegisters);
2150 }
2151
2152 void CodeBlock::setCalleeSaveRegisters(std::unique_ptr<RegisterAtOffsetList> registerAtOffsetList)
2153 {
2154     m_calleeSaveRegisters = WTFMove(registerAtOffsetList);
2155 }
2156     
2157 static size_t roundCalleeSaveSpaceAsVirtualRegisters(size_t calleeSaveRegisters)
2158 {
2159     static const unsigned cpuRegisterSize = sizeof(void*);
2160     return (WTF::roundUpToMultipleOf(sizeof(Register), calleeSaveRegisters * cpuRegisterSize) / sizeof(Register));
2161
2162 }
2163
2164 size_t CodeBlock::llintBaselineCalleeSaveSpaceAsVirtualRegisters()
2165 {
2166     return roundCalleeSaveSpaceAsVirtualRegisters(numberOfLLIntBaselineCalleeSaveRegisters());
2167 }
2168
2169 size_t CodeBlock::calleeSaveSpaceAsVirtualRegisters()
2170 {
2171     return roundCalleeSaveSpaceAsVirtualRegisters(m_calleeSaveRegisters->size());
2172 }
2173
2174 void CodeBlock::countReoptimization()
2175 {
2176     m_reoptimizationRetryCounter++;
2177     if (m_reoptimizationRetryCounter > Options::reoptimizationRetryCounterMax())
2178         m_reoptimizationRetryCounter = Options::reoptimizationRetryCounterMax();
2179 }
2180
2181 unsigned CodeBlock::numberOfDFGCompiles()
2182 {
2183     ASSERT(JITCode::isBaselineCode(jitType()));
2184     if (Options::testTheFTL()) {
2185         if (m_didFailFTLCompilation)
2186             return 1000000;
2187         return (m_hasBeenCompiledWithFTL ? 1 : 0) + m_reoptimizationRetryCounter;
2188     }
2189     return (JITCode::isOptimizingJIT(replacement()->jitType()) ? 1 : 0) + m_reoptimizationRetryCounter;
2190 }
2191
2192 int32_t CodeBlock::codeTypeThresholdMultiplier() const
2193 {
2194     if (codeType() == EvalCode)
2195         return Options::evalThresholdMultiplier();
2196     
2197     return 1;
2198 }
2199
2200 double CodeBlock::optimizationThresholdScalingFactor()
2201 {
2202     // This expression arises from doing a least-squares fit of
2203     //
2204     // F[x_] =: a * Sqrt[x + b] + Abs[c * x] + d
2205     //
2206     // against the data points:
2207     //
2208     //    x       F[x_]
2209     //    10       0.9          (smallest reasonable code block)
2210     //   200       1.0          (typical small-ish code block)
2211     //   320       1.2          (something I saw in 3d-cube that I wanted to optimize)
2212     //  1268       5.0          (something I saw in 3d-cube that I didn't want to optimize)
2213     //  4000       5.5          (random large size, used to cause the function to converge to a shallow curve of some sort)
2214     // 10000       6.0          (similar to above)
2215     //
2216     // I achieve the minimization using the following Mathematica code:
2217     //
2218     // MyFunctionTemplate[x_, a_, b_, c_, d_] := a*Sqrt[x + b] + Abs[c*x] + d
2219     //
2220     // samples = {{10, 0.9}, {200, 1}, {320, 1.2}, {1268, 5}, {4000, 5.5}, {10000, 6}}
2221     //
2222     // solution = 
2223     //     Minimize[Plus @@ ((MyFunctionTemplate[#[[1]], a, b, c, d] - #[[2]])^2 & /@ samples),
2224     //         {a, b, c, d}][[2]]
2225     //
2226     // And the code below (to initialize a, b, c, d) is generated by:
2227     //
2228     // Print["const double " <> ToString[#[[1]]] <> " = " <>
2229     //     If[#[[2]] < 0.00001, "0.0", ToString[#[[2]]]] <> ";"] & /@ solution
2230     //
2231     // We've long known the following to be true:
2232     // - Small code blocks are cheap to optimize and so we should do it sooner rather
2233     //   than later.
2234     // - Large code blocks are expensive to optimize and so we should postpone doing so,
2235     //   and sometimes have a large enough threshold that we never optimize them.
2236     // - The difference in cost is not totally linear because (a) just invoking the
2237     //   DFG incurs some base cost and (b) for large code blocks there is enough slop
2238     //   in the correlation between instruction count and the actual compilation cost
2239     //   that for those large blocks, the instruction count should not have a strong
2240     //   influence on our threshold.
2241     //
2242     // I knew the goals but I didn't know how to achieve them; so I picked an interesting
2243     // example where the heuristics were right (code block in 3d-cube with instruction
2244     // count 320, which got compiled early as it should have been) and one where they were
2245     // totally wrong (code block in 3d-cube with instruction count 1268, which was expensive
2246     // to compile and didn't run often enough to warrant compilation in my opinion), and
2247     // then threw in additional data points that represented my own guess of what our
2248     // heuristics should do for some round-numbered examples.
2249     //
2250     // The expression to which I decided to fit the data arose because I started with an
2251     // affine function, and then did two things: put the linear part in an Abs to ensure
2252     // that the fit didn't end up choosing a negative value of c (which would result in
2253     // the function turning over and going negative for large x) and I threw in a Sqrt
2254     // term because Sqrt represents my intution that the function should be more sensitive
2255     // to small changes in small values of x, but less sensitive when x gets large.
2256     
2257     // Note that the current fit essentially eliminates the linear portion of the
2258     // expression (c == 0.0).
2259     const double a = 0.061504;
2260     const double b = 1.02406;
2261     const double c = 0.0;
2262     const double d = 0.825914;
2263     
2264     double instructionCount = this->instructionCount();
2265     
2266     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.
2267     
2268     double result = d + a * sqrt(instructionCount + b) + c * instructionCount;
2269     
2270     result *= codeTypeThresholdMultiplier();
2271     
2272     if (Options::verboseOSR()) {
2273         dataLog(
2274             *this, ": instruction count is ", instructionCount,
2275             ", scaling execution counter by ", result, " * ", codeTypeThresholdMultiplier(),
2276             "\n");
2277     }
2278     return result;
2279 }
2280
2281 static int32_t clipThreshold(double threshold)
2282 {
2283     if (threshold < 1.0)
2284         return 1;
2285     
2286     if (threshold > static_cast<double>(std::numeric_limits<int32_t>::max()))
2287         return std::numeric_limits<int32_t>::max();
2288     
2289     return static_cast<int32_t>(threshold);
2290 }
2291
2292 int32_t CodeBlock::adjustedCounterValue(int32_t desiredThreshold)
2293 {
2294     return clipThreshold(
2295         static_cast<double>(desiredThreshold) *
2296         optimizationThresholdScalingFactor() *
2297         (1 << reoptimizationRetryCounter()));
2298 }
2299
2300 bool CodeBlock::checkIfOptimizationThresholdReached()
2301 {
2302 #if ENABLE(DFG_JIT)
2303     if (DFG::Worklist* worklist = DFG::existingGlobalDFGWorklistOrNull()) {
2304         if (worklist->compilationState(DFG::CompilationKey(this, DFG::DFGMode))
2305             == DFG::Worklist::Compiled) {
2306             optimizeNextInvocation();
2307             return true;
2308         }
2309     }
2310 #endif
2311     
2312     return m_jitExecuteCounter.checkIfThresholdCrossedAndSet(this);
2313 }
2314
2315 #if ENABLE(DFG_JIT)
2316 auto CodeBlock::updateOSRExitCounterAndCheckIfNeedToReoptimize(DFG::OSRExitState& exitState) -> OptimizeAction
2317 {
2318     DFG::OSRExitBase& exit = exitState.exit;
2319     if (!exitKindMayJettison(exit.m_kind)) {
2320         // FIXME: We may want to notice that we're frequently exiting
2321         // at an op_catch that we didn't compile an entrypoint for, and
2322         // then trigger a reoptimization of this CodeBlock:
2323         // https://bugs.webkit.org/show_bug.cgi?id=175842
2324         return OptimizeAction::None;
2325     }
2326
2327     exit.m_count++;
2328     m_osrExitCounter++;
2329
2330     CodeBlock* baselineCodeBlock = exitState.baselineCodeBlock;
2331     ASSERT(baselineCodeBlock == baselineAlternative());
2332     if (UNLIKELY(baselineCodeBlock->jitExecuteCounter().hasCrossedThreshold()))
2333         return OptimizeAction::ReoptimizeNow;
2334
2335     // We want to figure out if there's a possibility that we're in a loop. For the outermost
2336     // code block in the inline stack, we handle this appropriately by having the loop OSR trigger
2337     // check the exit count of the replacement of the CodeBlock from which we are OSRing. The
2338     // problem is the inlined functions, which might also have loops, but whose baseline versions
2339     // don't know where to look for the exit count. Figure out if those loops are severe enough
2340     // that we had tried to OSR enter. If so, then we should use the loop reoptimization trigger.
2341     // Otherwise, we should use the normal reoptimization trigger.
2342
2343     bool didTryToEnterInLoop = false;
2344     for (InlineCallFrame* inlineCallFrame = exit.m_codeOrigin.inlineCallFrame; inlineCallFrame; inlineCallFrame = inlineCallFrame->directCaller.inlineCallFrame) {
2345         if (inlineCallFrame->baselineCodeBlock->ownerScriptExecutable()->didTryToEnterInLoop()) {
2346             didTryToEnterInLoop = true;
2347             break;
2348         }
2349     }
2350
2351     uint32_t exitCountThreshold = didTryToEnterInLoop
2352         ? exitCountThresholdForReoptimizationFromLoop()
2353         : exitCountThresholdForReoptimization();
2354
2355     if (m_osrExitCounter > exitCountThreshold)
2356         return OptimizeAction::ReoptimizeNow;
2357
2358     // Too few fails. Adjust the execution counter such that the target is to only optimize after a while.
2359     baselineCodeBlock->m_jitExecuteCounter.setNewThresholdForOSRExit(exitState.activeThreshold, exitState.memoryUsageAdjustedThreshold);
2360     return OptimizeAction::None;
2361 }
2362 #endif
2363
2364 void CodeBlock::optimizeNextInvocation()
2365 {
2366     if (Options::verboseOSR())
2367         dataLog(*this, ": Optimizing next invocation.\n");
2368     m_jitExecuteCounter.setNewThreshold(0, this);
2369 }
2370
2371 void CodeBlock::dontOptimizeAnytimeSoon()
2372 {
2373     if (Options::verboseOSR())
2374         dataLog(*this, ": Not optimizing anytime soon.\n");
2375     m_jitExecuteCounter.deferIndefinitely();
2376 }
2377
2378 void CodeBlock::optimizeAfterWarmUp()
2379 {
2380     if (Options::verboseOSR())
2381         dataLog(*this, ": Optimizing after warm-up.\n");
2382 #if ENABLE(DFG_JIT)
2383     m_jitExecuteCounter.setNewThreshold(
2384         adjustedCounterValue(Options::thresholdForOptimizeAfterWarmUp()), this);
2385 #endif
2386 }
2387
2388 void CodeBlock::optimizeAfterLongWarmUp()
2389 {
2390     if (Options::verboseOSR())
2391         dataLog(*this, ": Optimizing after long warm-up.\n");
2392 #if ENABLE(DFG_JIT)
2393     m_jitExecuteCounter.setNewThreshold(
2394         adjustedCounterValue(Options::thresholdForOptimizeAfterLongWarmUp()), this);
2395 #endif
2396 }
2397
2398 void CodeBlock::optimizeSoon()
2399 {
2400     if (Options::verboseOSR())
2401         dataLog(*this, ": Optimizing soon.\n");
2402 #if ENABLE(DFG_JIT)
2403     m_jitExecuteCounter.setNewThreshold(
2404         adjustedCounterValue(Options::thresholdForOptimizeSoon()), this);
2405 #endif
2406 }
2407
2408 void CodeBlock::forceOptimizationSlowPathConcurrently()
2409 {
2410     if (Options::verboseOSR())
2411         dataLog(*this, ": Forcing slow path concurrently.\n");
2412     m_jitExecuteCounter.forceSlowPathConcurrently();
2413 }
2414
2415 #if ENABLE(DFG_JIT)
2416 void CodeBlock::setOptimizationThresholdBasedOnCompilationResult(CompilationResult result)
2417 {
2418     JITCode::JITType type = jitType();
2419     if (type != JITCode::BaselineJIT) {
2420         dataLog(*this, ": expected to have baseline code but have ", type, "\n");
2421         RELEASE_ASSERT_NOT_REACHED();
2422     }
2423     
2424     CodeBlock* theReplacement = replacement();
2425     if ((result == CompilationSuccessful) != (theReplacement != this)) {
2426         dataLog(*this, ": we have result = ", result, " but ");
2427         if (theReplacement == this)
2428             dataLog("we are our own replacement.\n");
2429         else
2430             dataLog("our replacement is ", pointerDump(theReplacement), "\n");
2431         RELEASE_ASSERT_NOT_REACHED();
2432     }
2433     
2434     switch (result) {
2435     case CompilationSuccessful:
2436         RELEASE_ASSERT(JITCode::isOptimizingJIT(replacement()->jitType()));
2437         optimizeNextInvocation();
2438         return;
2439     case CompilationFailed:
2440         dontOptimizeAnytimeSoon();
2441         return;
2442     case CompilationDeferred:
2443         // We'd like to do dontOptimizeAnytimeSoon() but we cannot because
2444         // forceOptimizationSlowPathConcurrently() is inherently racy. It won't
2445         // necessarily guarantee anything. So, we make sure that even if that
2446         // function ends up being a no-op, we still eventually retry and realize
2447         // that we have optimized code ready.
2448         optimizeAfterWarmUp();
2449         return;
2450     case CompilationInvalidated:
2451         // Retry with exponential backoff.
2452         countReoptimization();
2453         optimizeAfterWarmUp();
2454         return;
2455     }
2456     
2457     dataLog("Unrecognized result: ", static_cast<int>(result), "\n");
2458     RELEASE_ASSERT_NOT_REACHED();
2459 }
2460
2461 #endif
2462     
2463 uint32_t CodeBlock::adjustedExitCountThreshold(uint32_t desiredThreshold)
2464 {
2465     ASSERT(JITCode::isOptimizingJIT(jitType()));
2466     // Compute this the lame way so we don't saturate. This is called infrequently
2467     // enough that this loop won't hurt us.
2468     unsigned result = desiredThreshold;
2469     for (unsigned n = baselineVersion()->reoptimizationRetryCounter(); n--;) {
2470         unsigned newResult = result << 1;
2471         if (newResult < result)
2472             return std::numeric_limits<uint32_t>::max();
2473         result = newResult;
2474     }
2475     return result;
2476 }
2477
2478 uint32_t CodeBlock::exitCountThresholdForReoptimization()
2479 {
2480     return adjustedExitCountThreshold(Options::osrExitCountForReoptimization() * codeTypeThresholdMultiplier());
2481 }
2482
2483 uint32_t CodeBlock::exitCountThresholdForReoptimizationFromLoop()
2484 {
2485     return adjustedExitCountThreshold(Options::osrExitCountForReoptimizationFromLoop() * codeTypeThresholdMultiplier());
2486 }
2487
2488 bool CodeBlock::shouldReoptimizeNow()
2489 {
2490     return osrExitCounter() >= exitCountThresholdForReoptimization();
2491 }
2492
2493 bool CodeBlock::shouldReoptimizeFromLoopNow()
2494 {
2495     return osrExitCounter() >= exitCountThresholdForReoptimizationFromLoop();
2496 }
2497 #endif
2498
2499 ArrayProfile* CodeBlock::getArrayProfile(const ConcurrentJSLocker&, unsigned bytecodeOffset)
2500 {
2501     for (auto& m_arrayProfile : m_arrayProfiles) {
2502         if (m_arrayProfile.bytecodeOffset() == bytecodeOffset)
2503             return &m_arrayProfile;
2504     }
2505     return 0;
2506 }
2507
2508 ArrayProfile* CodeBlock::getArrayProfile(unsigned bytecodeOffset)
2509 {
2510     ConcurrentJSLocker locker(m_lock);
2511     return getArrayProfile(locker, bytecodeOffset);
2512 }
2513
2514 ArrayProfile* CodeBlock::addArrayProfile(const ConcurrentJSLocker&, unsigned bytecodeOffset)
2515 {
2516     m_arrayProfiles.append(ArrayProfile(bytecodeOffset));
2517     return &m_arrayProfiles.last();
2518 }
2519
2520 ArrayProfile* CodeBlock::addArrayProfile(unsigned bytecodeOffset)
2521 {
2522     ConcurrentJSLocker locker(m_lock);
2523     return addArrayProfile(locker, bytecodeOffset);
2524 }
2525
2526 ArrayProfile* CodeBlock::getOrAddArrayProfile(const ConcurrentJSLocker& locker, unsigned bytecodeOffset)
2527 {
2528     ArrayProfile* result = getArrayProfile(locker, bytecodeOffset);
2529     if (result)
2530         return result;
2531     return addArrayProfile(locker, bytecodeOffset);
2532 }
2533
2534 ArrayProfile* CodeBlock::getOrAddArrayProfile(unsigned bytecodeOffset)
2535 {
2536     ConcurrentJSLocker locker(m_lock);
2537     return getOrAddArrayProfile(locker, bytecodeOffset);
2538 }
2539
2540 #if ENABLE(DFG_JIT)
2541 Vector<CodeOrigin, 0, UnsafeVectorOverflow>& CodeBlock::codeOrigins()
2542 {
2543     return m_jitCode->dfgCommon()->codeOrigins;
2544 }
2545
2546 size_t CodeBlock::numberOfDFGIdentifiers() const
2547 {
2548     if (!JITCode::isOptimizingJIT(jitType()))
2549         return 0;
2550     
2551     return m_jitCode->dfgCommon()->dfgIdentifiers.size();
2552 }
2553
2554 const Identifier& CodeBlock::identifier(int index) const
2555 {
2556     size_t unlinkedIdentifiers = m_unlinkedCode->numberOfIdentifiers();
2557     if (static_cast<unsigned>(index) < unlinkedIdentifiers)
2558         return m_unlinkedCode->identifier(index);
2559     ASSERT(JITCode::isOptimizingJIT(jitType()));
2560     return m_jitCode->dfgCommon()->dfgIdentifiers[index - unlinkedIdentifiers];
2561 }
2562 #endif // ENABLE(DFG_JIT)
2563
2564 void CodeBlock::updateAllPredictionsAndCountLiveness(unsigned& numberOfLiveNonArgumentValueProfiles, unsigned& numberOfSamplesInProfiles)
2565 {
2566     ConcurrentJSLocker locker(m_lock);
2567
2568     numberOfLiveNonArgumentValueProfiles = 0;
2569     numberOfSamplesInProfiles = 0; // If this divided by ValueProfile::numberOfBuckets equals numberOfValueProfiles() then value profiles are full.
2570
2571     for (unsigned i = 0; i < totalNumberOfValueProfiles(); ++i) {
2572         ValueProfile& profile = getFromAllValueProfiles(i);
2573         unsigned numSamples = profile.totalNumberOfSamples();
2574         if (numSamples > ValueProfile::numberOfBuckets)
2575             numSamples = ValueProfile::numberOfBuckets; // We don't want profiles that are extremely hot to be given more weight.
2576         numberOfSamplesInProfiles += numSamples;
2577         if (profile.m_bytecodeOffset < 0) {
2578             profile.computeUpdatedPrediction(locker);
2579             continue;
2580         }
2581         if (profile.numberOfSamples() || profile.m_prediction != SpecNone)
2582             numberOfLiveNonArgumentValueProfiles++;
2583         profile.computeUpdatedPrediction(locker);
2584     }
2585
2586     for (auto& profileBucket : m_catchProfiles) {
2587         profileBucket->forEach([&] (ValueProfileAndOperand& profile) {
2588             profile.m_profile.computeUpdatedPrediction(locker);
2589         });
2590     }
2591     
2592 #if ENABLE(DFG_JIT)
2593     m_lazyOperandValueProfiles.computeUpdatedPredictions(locker);
2594 #endif
2595 }
2596
2597 void CodeBlock::updateAllValueProfilePredictions()
2598 {
2599     unsigned ignoredValue1, ignoredValue2;
2600     updateAllPredictionsAndCountLiveness(ignoredValue1, ignoredValue2);
2601 }
2602
2603 void CodeBlock::updateAllArrayPredictions()
2604 {
2605     ConcurrentJSLocker locker(m_lock);
2606     
2607     for (unsigned i = m_arrayProfiles.size(); i--;)
2608         m_arrayProfiles[i].computeUpdatedPrediction(locker, this);
2609     
2610     // Don't count these either, for similar reasons.
2611     for (unsigned i = m_arrayAllocationProfiles.size(); i--;)
2612         m_arrayAllocationProfiles[i].updateProfile();
2613 }
2614
2615 void CodeBlock::updateAllPredictions()
2616 {
2617     updateAllValueProfilePredictions();
2618     updateAllArrayPredictions();
2619 }
2620
2621 bool CodeBlock::shouldOptimizeNow()
2622 {
2623     if (Options::verboseOSR())
2624         dataLog("Considering optimizing ", *this, "...\n");
2625
2626     if (m_optimizationDelayCounter >= Options::maximumOptimizationDelay())
2627         return true;
2628     
2629     updateAllArrayPredictions();
2630     
2631     unsigned numberOfLiveNonArgumentValueProfiles;
2632     unsigned numberOfSamplesInProfiles;
2633     updateAllPredictionsAndCountLiveness(numberOfLiveNonArgumentValueProfiles, numberOfSamplesInProfiles);
2634
2635     if (Options::verboseOSR()) {
2636         dataLogF(
2637             "Profile hotness: %lf (%u / %u), %lf (%u / %u)\n",
2638             (double)numberOfLiveNonArgumentValueProfiles / numberOfValueProfiles(),
2639             numberOfLiveNonArgumentValueProfiles, numberOfValueProfiles(),
2640             (double)numberOfSamplesInProfiles / ValueProfile::numberOfBuckets / numberOfValueProfiles(),
2641             numberOfSamplesInProfiles, ValueProfile::numberOfBuckets * numberOfValueProfiles());
2642     }
2643
2644     if ((!numberOfValueProfiles() || (double)numberOfLiveNonArgumentValueProfiles / numberOfValueProfiles() >= Options::desiredProfileLivenessRate())
2645         && (!totalNumberOfValueProfiles() || (double)numberOfSamplesInProfiles / ValueProfile::numberOfBuckets / totalNumberOfValueProfiles() >= Options::desiredProfileFullnessRate())
2646         && static_cast<unsigned>(m_optimizationDelayCounter) + 1 >= Options::minimumOptimizationDelay())
2647         return true;
2648     
2649     ASSERT(m_optimizationDelayCounter < std::numeric_limits<uint8_t>::max());
2650     m_optimizationDelayCounter++;
2651     optimizeAfterWarmUp();
2652     return false;
2653 }
2654
2655 #if ENABLE(DFG_JIT)
2656 void CodeBlock::tallyFrequentExitSites()
2657 {
2658     ASSERT(JITCode::isOptimizingJIT(jitType()));
2659     ASSERT(alternative()->jitType() == JITCode::BaselineJIT);
2660     
2661     CodeBlock* profiledBlock = alternative();
2662     
2663     switch (jitType()) {
2664     case JITCode::DFGJIT: {
2665         DFG::JITCode* jitCode = m_jitCode->dfg();
2666         for (auto& exit : jitCode->osrExit)
2667             exit.considerAddingAsFrequentExitSite(profiledBlock);
2668         break;
2669     }
2670
2671 #if ENABLE(FTL_JIT)
2672     case JITCode::FTLJIT: {
2673         // There is no easy way to avoid duplicating this code since the FTL::JITCode::osrExit
2674         // vector contains a totally different type, that just so happens to behave like
2675         // DFG::JITCode::osrExit.
2676         FTL::JITCode* jitCode = m_jitCode->ftl();
2677         for (unsigned i = 0; i < jitCode->osrExit.size(); ++i) {
2678             FTL::OSRExit& exit = jitCode->osrExit[i];
2679             exit.considerAddingAsFrequentExitSite(profiledBlock);
2680         }
2681         break;
2682     }
2683 #endif
2684         
2685     default:
2686         RELEASE_ASSERT_NOT_REACHED();
2687         break;
2688     }
2689 }
2690 #endif // ENABLE(DFG_JIT)
2691
2692 #if ENABLE(VERBOSE_VALUE_PROFILE)
2693 void CodeBlock::dumpValueProfiles()
2694 {
2695     dataLog("ValueProfile for ", *this, ":\n");
2696     for (unsigned i = 0; i < totalNumberOfValueProfiles(); ++i) {
2697         ValueProfile& profile = getFromAllValueProfiles(i);
2698         if (profile.m_bytecodeOffset < 0) {
2699             ASSERT(profile.m_bytecodeOffset == -1);
2700             dataLogF("   arg = %u: ", i);
2701         } else
2702             dataLogF("   bc = %d: ", profile.m_bytecodeOffset);
2703         if (!profile.numberOfSamples() && profile.m_prediction == SpecNone) {
2704             dataLogF("<empty>\n");
2705             continue;
2706         }
2707         profile.dump(WTF::dataFile());
2708         dataLogF("\n");
2709     }
2710     dataLog("RareCaseProfile for ", *this, ":\n");
2711     for (unsigned i = 0; i < numberOfRareCaseProfiles(); ++i) {
2712         RareCaseProfile* profile = rareCaseProfile(i);
2713         dataLogF("   bc = %d: %u\n", profile->m_bytecodeOffset, profile->m_counter);
2714     }
2715 }
2716 #endif // ENABLE(VERBOSE_VALUE_PROFILE)
2717
2718 unsigned CodeBlock::frameRegisterCount()
2719 {
2720     switch (jitType()) {
2721     case JITCode::InterpreterThunk:
2722         return LLInt::frameRegisterCountFor(this);
2723
2724 #if ENABLE(JIT)
2725     case JITCode::BaselineJIT:
2726         return JIT::frameRegisterCountFor(this);
2727 #endif // ENABLE(JIT)
2728
2729 #if ENABLE(DFG_JIT)
2730     case JITCode::DFGJIT:
2731     case JITCode::FTLJIT:
2732         return jitCode()->dfgCommon()->frameRegisterCount;
2733 #endif // ENABLE(DFG_JIT)
2734         
2735     default:
2736         RELEASE_ASSERT_NOT_REACHED();
2737         return 0;
2738     }
2739 }
2740
2741 int CodeBlock::stackPointerOffset()
2742 {
2743     return virtualRegisterForLocal(frameRegisterCount() - 1).offset();
2744 }
2745
2746 size_t CodeBlock::predictedMachineCodeSize()
2747 {
2748     VM* vm = m_poisonedVM.unpoisoned();
2749     // This will be called from CodeBlock::CodeBlock before either m_poisonedVM or the
2750     // instructions have been initialized. It's OK to return 0 because what will really
2751     // matter is the recomputation of this value when the slow path is triggered.
2752     if (!vm)
2753         return 0;
2754     
2755     if (!*vm->machineCodeBytesPerBytecodeWordForBaselineJIT)
2756         return 0; // It's as good of a prediction as we'll get.
2757     
2758     // Be conservative: return a size that will be an overestimation 84% of the time.
2759     double multiplier = vm->machineCodeBytesPerBytecodeWordForBaselineJIT->mean() +
2760         vm->machineCodeBytesPerBytecodeWordForBaselineJIT->standardDeviation();
2761     
2762     // Be paranoid: silently reject bogus multipiers. Silently doing the "wrong" thing
2763     // here is OK, since this whole method is just a heuristic.
2764     if (multiplier < 0 || multiplier > 1000)
2765         return 0;
2766     
2767     double doubleResult = multiplier * m_instructions.size();
2768     
2769     // Be even more paranoid: silently reject values that won't fit into a size_t. If
2770     // the function is so huge that we can't even fit it into virtual memory then we
2771     // should probably have some other guards in place to prevent us from even getting
2772     // to this point.
2773     if (doubleResult > std::numeric_limits<size_t>::max())
2774         return 0;
2775     
2776     return static_cast<size_t>(doubleResult);
2777 }
2778
2779 String CodeBlock::nameForRegister(VirtualRegister virtualRegister)
2780 {
2781     for (auto& constantRegister : m_constantRegisters) {
2782         if (constantRegister.get().isEmpty())
2783             continue;
2784         if (SymbolTable* symbolTable = jsDynamicCast<SymbolTable*>(*vm(), constantRegister.get())) {
2785             ConcurrentJSLocker locker(symbolTable->m_lock);
2786             auto end = symbolTable->end(locker);
2787             for (auto ptr = symbolTable->begin(locker); ptr != end; ++ptr) {
2788                 if (ptr->value.varOffset() == VarOffset(virtualRegister)) {
2789                     // FIXME: This won't work from the compilation thread.
2790                     // https://bugs.webkit.org/show_bug.cgi?id=115300
2791                     return ptr->key.get();
2792                 }
2793             }
2794         }
2795     }
2796     if (virtualRegister == thisRegister())
2797         return "this"_s;
2798     if (virtualRegister.isArgument())
2799         return String::format("arguments[%3d]", virtualRegister.toArgument());
2800
2801     return "";
2802 }
2803
2804 ValueProfile* CodeBlock::tryGetValueProfileForBytecodeOffset(int bytecodeOffset)
2805 {
2806     return tryBinarySearch<ValueProfile, int>(
2807         m_valueProfiles, m_valueProfiles.size(), bytecodeOffset,
2808         getValueProfileBytecodeOffset<ValueProfile>);
2809 }
2810
2811 ValueProfile& CodeBlock::valueProfileForBytecodeOffset(int bytecodeOffset)
2812 {
2813     OpcodeID opcodeID = Interpreter::getOpcodeID(instructions()[bytecodeOffset]);
2814     unsigned length = opcodeLength(opcodeID);
2815     ASSERT(!!tryGetValueProfileForBytecodeOffset(bytecodeOffset));
2816     return *instructions()[bytecodeOffset + length - 1].u.profile;
2817 }
2818
2819 void CodeBlock::validate()
2820 {
2821     BytecodeLivenessAnalysis liveness(this); // Compute directly from scratch so it doesn't effect CodeBlock footprint.
2822     
2823     FastBitVector liveAtHead = liveness.getLivenessInfoAtBytecodeOffset(this, 0);
2824     
2825     if (liveAtHead.numBits() != static_cast<size_t>(m_numCalleeLocals)) {
2826         beginValidationDidFail();
2827         dataLog("    Wrong number of bits in result!\n");
2828         dataLog("    Result: ", liveAtHead, "\n");
2829         dataLog("    Bit count: ", liveAtHead.numBits(), "\n");
2830         endValidationDidFail();
2831     }
2832     
2833     for (unsigned i = m_numCalleeLocals; i--;) {
2834         VirtualRegister reg = virtualRegisterForLocal(i);
2835         
2836         if (liveAtHead[i]) {
2837             beginValidationDidFail();
2838             dataLog("    Variable ", reg, " is expected to be dead.\n");
2839             dataLog("    Result: ", liveAtHead, "\n");
2840             endValidationDidFail();
2841         }
2842     }
2843
2844     for (unsigned i = 0; i + 1 < numberOfValueProfiles(); ++i) {
2845         if (valueProfile(i).m_bytecodeOffset > valueProfile(i + 1).m_bytecodeOffset) {
2846             beginValidationDidFail();
2847             dataLog("    Value profiles are not sorted.\n");
2848             endValidationDidFail();
2849         }
2850     }
2851      
2852     for (unsigned bytecodeOffset = 0; bytecodeOffset < m_instructions.size(); ) {
2853         OpcodeID opcode = Interpreter::getOpcodeID(m_instructions[bytecodeOffset]);
2854         if (!!baselineAlternative()->handlerForBytecodeOffset(bytecodeOffset)) {
2855             if (opcode == op_catch || opcode == op_enter) {
2856                 // op_catch/op_enter logically represent an entrypoint. Entrypoints are not allowed to be
2857                 // inside of a try block because they are responsible for bootstrapping state. And they
2858                 // are never allowed throw an exception because of this. We rely on this when compiling
2859                 // in the DFG. Because an entrypoint never throws, the bytecode generator will never
2860                 // allow once inside a try block.
2861                 beginValidationDidFail();
2862                 dataLog("    entrypoint not allowed inside a try block.");
2863                 endValidationDidFail();
2864             }
2865         }
2866         bytecodeOffset += opcodeLength(opcode);
2867     }
2868 }
2869
2870 void CodeBlock::beginValidationDidFail()
2871 {
2872     dataLog("Validation failure in ", *this, ":\n");
2873     dataLog("\n");
2874 }
2875
2876 void CodeBlock::endValidationDidFail()
2877 {
2878     dataLog("\n");
2879     dumpBytecode();
2880     dataLog("\n");
2881     dataLog("Validation failure.\n");
2882     RELEASE_ASSERT_NOT_REACHED();
2883 }
2884
2885 void CodeBlock::addBreakpoint(unsigned numBreakpoints)
2886 {
2887     m_numBreakpoints += numBreakpoints;
2888     ASSERT(m_numBreakpoints);
2889     if (JITCode::isOptimizingJIT(jitType()))
2890         jettison(Profiler::JettisonDueToDebuggerBreakpoint);
2891 }
2892
2893 void CodeBlock::setSteppingMode(CodeBlock::SteppingMode mode)
2894 {
2895     m_steppingMode = mode;
2896     if (mode == SteppingModeEnabled && JITCode::isOptimizingJIT(jitType()))
2897         jettison(Profiler::JettisonDueToDebuggerStepping);
2898 }
2899
2900 RareCaseProfile* CodeBlock::addRareCaseProfile(int bytecodeOffset)
2901 {
2902     m_rareCaseProfiles.append(RareCaseProfile(bytecodeOffset));
2903     return &m_rareCaseProfiles.last();
2904 }
2905
2906 RareCaseProfile* CodeBlock::rareCaseProfileForBytecodeOffset(int bytecodeOffset)
2907 {
2908     return tryBinarySearch<RareCaseProfile, int>(
2909         m_rareCaseProfiles, m_rareCaseProfiles.size(), bytecodeOffset,
2910         getRareCaseProfileBytecodeOffset);
2911 }
2912
2913 unsigned CodeBlock::rareCaseProfileCountForBytecodeOffset(int bytecodeOffset)
2914 {
2915     RareCaseProfile* profile = rareCaseProfileForBytecodeOffset(bytecodeOffset);
2916     if (profile)
2917         return profile->m_counter;
2918     return 0;
2919 }
2920
2921 ArithProfile* CodeBlock::arithProfileForBytecodeOffset(int bytecodeOffset)
2922 {
2923     return arithProfileForPC(&instructions()[bytecodeOffset]);
2924 }
2925
2926 ArithProfile* CodeBlock::arithProfileForPC(Instruction* pc)
2927 {
2928     auto opcodeID = Interpreter::getOpcodeID(pc[0]);
2929     switch (opcodeID) {
2930     case op_negate:
2931         return bitwise_cast<ArithProfile*>(&pc[3].u.operand);
2932     case op_bitor:
2933     case op_bitand:
2934     case op_bitxor:
2935     case op_add:
2936     case op_mul:
2937     case op_sub:
2938     case op_div:
2939         return bitwise_cast<ArithProfile*>(&pc[4].u.operand);
2940     default:
2941         break;
2942     }
2943
2944     return nullptr;
2945 }
2946
2947 bool CodeBlock::couldTakeSpecialFastCase(int bytecodeOffset)
2948 {
2949     if (!hasBaselineJITProfiling())
2950         return false;
2951     ArithProfile* profile = arithProfileForBytecodeOffset(bytecodeOffset);
2952     if (!profile)
2953         return false;
2954     return profile->tookSpecialFastPath();
2955 }
2956
2957 #if ENABLE(JIT)
2958 DFG::CapabilityLevel CodeBlock::capabilityLevel()
2959 {
2960     DFG::CapabilityLevel result = computeCapabilityLevel();
2961     m_capabilityLevelState = result;
2962     return result;
2963 }
2964 #endif
2965
2966 void CodeBlock::insertBasicBlockBoundariesForControlFlowProfiler(RefCountedArray<Instruction>& instructions)
2967 {
2968     if (!unlinkedCodeBlock()->hasOpProfileControlFlowBytecodeOffsets())
2969         return;
2970     const Vector<size_t>& bytecodeOffsets = unlinkedCodeBlock()->opProfileControlFlowBytecodeOffsets();
2971     for (size_t i = 0, offsetsLength = bytecodeOffsets.size(); i < offsetsLength; i++) {
2972         // Because op_profile_control_flow is emitted at the beginning of every basic block, finding 
2973         // the next op_profile_control_flow will give us the text range of a single basic block.
2974         size_t startIdx = bytecodeOffsets[i];
2975         RELEASE_ASSERT(Interpreter::getOpcodeID(instructions[startIdx]) == op_profile_control_flow);
2976         int basicBlockStartOffset = instructions[startIdx + 1].u.operand;
2977         int basicBlockEndOffset;
2978         if (i + 1 < offsetsLength) {
2979             size_t endIdx = bytecodeOffsets[i + 1];
2980             RELEASE_ASSERT(Interpreter::getOpcodeID(instructions[endIdx]) == op_profile_control_flow);
2981             basicBlockEndOffset = instructions[endIdx + 1].u.operand - 1;
2982         } else {
2983             basicBlockEndOffset = m_sourceOffset + ownerScriptExecutable()->source().length() - 1; // Offset before the closing brace.
2984             basicBlockStartOffset = std::min(basicBlockStartOffset, basicBlockEndOffset); // Some start offsets may be at the closing brace, ensure it is the offset before.
2985         }
2986
2987         // The following check allows for the same textual JavaScript basic block to have its bytecode emitted more
2988         // than once and still play nice with the control flow profiler. When basicBlockStartOffset is larger than 
2989         // basicBlockEndOffset, it indicates that the bytecode generator has emitted code for the same AST node 
2990         // more than once (for example: ForInNode, Finally blocks in TryNode, etc). Though these are different 
2991         // basic blocks at the bytecode level, they are generated from the same textual basic block in the JavaScript 
2992         // program. The condition: 
2993         // (basicBlockEndOffset < basicBlockStartOffset) 
2994         // is encountered when op_profile_control_flow lies across the boundary of these duplicated bytecode basic 
2995         // blocks and the textual offset goes from the end of the duplicated block back to the beginning. These 
2996         // ranges are dummy ranges and are ignored. The duplicated bytecode basic blocks point to the same 
2997         // internal data structure, so if any of them execute, it will record the same textual basic block in the 
2998         // JavaScript program as executing.
2999         // At the bytecode level, this situation looks like:
3000         // j: op_profile_control_flow (from j->k, we have basicBlockEndOffset < basicBlockStartOffset)
3001         // ...
3002         // 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).
3003         // ...
3004         // m: op_profile_control_flow
3005         if (basicBlockEndOffset < basicBlockStartOffset) {
3006             RELEASE_ASSERT(i + 1 < offsetsLength); // We should never encounter dummy blocks at the end of a CodeBlock.
3007             instructions[startIdx + 1].u.basicBlockLocation = vm()->controlFlowProfiler()->dummyBasicBlock();
3008             continue;
3009         }
3010
3011         BasicBlockLocation* basicBlockLocation = vm()->controlFlowProfiler()->getBasicBlockLocation(ownerScriptExecutable()->sourceID(), basicBlockStartOffset, basicBlockEndOffset);
3012
3013         // Find all functions that are enclosed within the range: [basicBlockStartOffset, basicBlockEndOffset]
3014         // and insert these functions' start/end offsets as gaps in the current BasicBlockLocation.
3015         // This is necessary because in the original source text of a JavaScript program, 
3016         // function literals form new basic blocks boundaries, but they aren't represented 
3017         // inside the CodeBlock's instruction stream.
3018         auto insertFunctionGaps = [basicBlockLocation, basicBlockStartOffset, basicBlockEndOffset] (const WriteBarrier<FunctionExecutable>& functionExecutable) {
3019             const UnlinkedFunctionExecutable* executable = functionExecutable->unlinkedExecutable();
3020             int functionStart = executable->typeProfilingStartOffset();
3021             int functionEnd = executable->typeProfilingEndOffset();
3022             if (functionStart >= basicBlockStartOffset && functionEnd <= basicBlockEndOffset)
3023                 basicBlockLocation->insertGap(functionStart, functionEnd);
3024         };
3025
3026         for (const WriteBarrier<FunctionExecutable>& executable : m_functionDecls)
3027             insertFunctionGaps(executable);
3028         for (const WriteBarrier<FunctionExecutable>& executable : m_functionExprs)
3029             insertFunctionGaps(executable);
3030
3031         instructions[startIdx + 1].u.basicBlockLocation = basicBlockLocation;
3032     }
3033 }
3034
3035 #if ENABLE(JIT)
3036 void CodeBlock::setPCToCodeOriginMap(std::unique_ptr<PCToCodeOriginMap>&& map) 
3037
3038     m_pcToCodeOriginMap = WTFMove(map);
3039 }
3040
3041 std::optional<CodeOrigin> CodeBlock::findPC(void* pc)
3042 {
3043     if (m_pcToCodeOriginMap) {
3044         if (std::optional<CodeOrigin> codeOrigin = m_pcToCodeOriginMap->findPC(pc))
3045             return codeOrigin;
3046     }
3047
3048     for (auto iter = m_stubInfos.begin(); !!iter; ++iter) {
3049         StructureStubInfo* stub = *iter;
3050         if (stub->containsPC(pc))
3051             return std::optional<CodeOrigin>(stub->codeOrigin);
3052     }
3053
3054     if (std::optional<CodeOrigin> codeOrigin = m_jitCode->findPC(this, pc))
3055         return codeOrigin;
3056
3057     return std::nullopt;
3058 }
3059 #endif // ENABLE(JIT)
3060
3061 std::optional<unsigned> CodeBlock::bytecodeOffsetFromCallSiteIndex(CallSiteIndex callSiteIndex)
3062 {
3063     std::optional<unsigned> bytecodeOffset;
3064     JITCode::JITType jitType = this->jitType();
3065     if (jitType == JITCode::InterpreterThunk || jitType == JITCode::BaselineJIT) {
3066 #if USE(JSVALUE64)
3067         bytecodeOffset = callSiteIndex.bits();
3068 #else
3069         Instruction* instruction = bitwise_cast<Instruction*>(callSiteIndex.bits());
3070         bytecodeOffset = this->bytecodeOffset(instruction);
3071 #endif
3072     } else if (jitType == JITCode::DFGJIT || jitType == JITCode::FTLJIT) {
3073 #if ENABLE(DFG_JIT)
3074         RELEASE_ASSERT(canGetCodeOrigin(callSiteIndex));
3075         CodeOrigin origin = codeOrigin(callSiteIndex);
3076         bytecodeOffset = origin.bytecodeIndex;
3077 #else
3078         RELEASE_ASSERT_NOT_REACHED();
3079 #endif
3080     }
3081
3082     return bytecodeOffset;
3083 }
3084
3085 int32_t CodeBlock::thresholdForJIT(int32_t threshold)
3086 {
3087     switch (unlinkedCodeBlock()->didOptimize()) {
3088     case MixedTriState:
3089         return threshold;
3090     case FalseTriState:
3091         return threshold * 4;
3092     case TrueTriState:
3093         return threshold / 2;
3094     }
3095     ASSERT_NOT_REACHED();
3096     return threshold;
3097 }
3098
3099 void CodeBlock::jitAfterWarmUp()
3100 {
3101     m_llintExecuteCounter.setNewThreshold(thresholdForJIT(Options::thresholdForJITAfterWarmUp()), this);
3102 }
3103
3104 void CodeBlock::jitSoon()
3105 {
3106     m_llintExecuteCounter.setNewThreshold(thresholdForJIT(Options::thresholdForJITSoon()), this);
3107 }
3108
3109 bool CodeBlock::hasInstalledVMTrapBreakpoints() const
3110 {
3111 #if ENABLE(SIGNAL_BASED_VM_TRAPS)
3112     // This function may be called from a signal handler. We need to be
3113     // careful to not call anything that is not signal handler safe, e.g.
3114     // we should not perturb the refCount of m_jitCode.
3115     if (!JITCode::isOptimizingJIT(jitType()))
3116         return false;
3117     return m_jitCode->dfgCommon()->hasInstalledVMTrapsBreakpoints();
3118 #else
3119     return false;
3120 #endif
3121 }
3122
3123 bool CodeBlock::installVMTrapBreakpoints()
3124 {
3125 #if ENABLE(SIGNAL_BASED_VM_TRAPS)
3126     // This function may be called from a signal handler. We need to be
3127     // careful to not call anything that is not signal handler safe, e.g.
3128     // we should not perturb the refCount of m_jitCode.
3129     if (!JITCode::isOptimizingJIT(jitType()))
3130         return false;
3131     auto& commonData = *m_jitCode->dfgCommon();
3132     commonData.installVMTrapBreakpoints(this);
3133     return true;
3134 #else
3135     UNREACHABLE_FOR_PLATFORM();
3136     return false;
3137 #endif
3138 }
3139
3140 void CodeBlock::dumpMathICStats()
3141 {
3142 #if ENABLE(MATH_IC_STATS)
3143     double numAdds = 0.0;
3144     double totalAddSize = 0.0;
3145     double numMuls = 0.0;
3146     double totalMulSize = 0.0;
3147     double numNegs = 0.0;
3148     double totalNegSize = 0.0;
3149     double numSubs = 0.0;
3150     double totalSubSize = 0.0;
3151
3152     auto countICs = [&] (CodeBlock* codeBlock) {
3153         for (JITAddIC* addIC : codeBlock->m_addICs) {
3154             numAdds++;
3155             totalAddSize += addIC->codeSize();
3156         }
3157
3158         for (JITMulIC* mulIC : codeBlock->m_mulICs) {
3159             numMuls++;
3160             totalMulSize += mulIC->codeSize();
3161         }
3162
3163         for (JITNegIC* negIC : codeBlock->m_negICs) {
3164             numNegs++;
3165             totalNegSize += negIC->codeSize();
3166         }
3167
3168         for (JITSubIC* subIC : codeBlock->m_subICs) {
3169             numSubs++;
3170             totalSubSize += subIC->codeSize();
3171         }
3172     };
3173     heap()->forEachCodeBlock(countICs);
3174
3175     dataLog("Num Adds: ", numAdds, "\n");
3176     dataLog("Total Add size in bytes: ", totalAddSize, "\n");
3177     dataLog("Average Add size: ", totalAddSize / numAdds, "\n");
3178     dataLog("\n");
3179     dataLog("Num Muls: ", numMuls, "\n");
3180     dataLog("Total Mul size in bytes: ", totalMulSize, "\n");
3181     dataLog("Average Mul size: ", totalMulSize / numMuls, "\n");
3182     dataLog("\n");
3183     dataLog("Num Negs: ", numNegs, "\n");
3184     dataLog("Total Neg size in bytes: ", totalNegSize, "\n");
3185     dataLog("Average Neg size: ", totalNegSize / numNegs, "\n");
3186     dataLog("\n");
3187     dataLog("Num Subs: ", numSubs, "\n");
3188     dataLog("Total Sub size in bytes: ", totalSubSize, "\n");
3189     dataLog("Average Sub size: ", totalSubSize / numSubs, "\n");
3190
3191     dataLog("-----------------------\n");
3192 #endif
3193 }
3194
3195 void setPrinter(Printer::PrintRecord& record, CodeBlock* codeBlock)
3196 {
3197     Printer::setPrinter(record, toCString(codeBlock));
3198 }
3199
3200 } // namespace JSC
3201
3202 namespace WTF {
3203     
3204 void printInternal(PrintStream& out, JSC::CodeBlock* codeBlock)
3205 {
3206     if (UNLIKELY(!codeBlock)) {
3207         out.print("<null codeBlock>");
3208         return;
3209     }
3210     out.print(*codeBlock);
3211 }
3212     
3213 } // namespace WTF