We should support CreateThis in the FTL
[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     ICStatusMap statusMap;
242     getICStatusMap(statusMap);
243     BytecodeDumper<CodeBlock>::dumpBlock(this, instructions(), out, statusMap);
244 }
245
246 void CodeBlock::dumpBytecode(PrintStream& out, const Instruction* begin, const Instruction*& it, const ICStatusMap& statusMap)
247 {
248     BytecodeDumper<CodeBlock>::dumpBytecode(this, out, begin, it, statusMap);
249 }
250
251 void CodeBlock::dumpBytecode(PrintStream& out, unsigned bytecodeOffset, const ICStatusMap& statusMap)
252 {
253     const Instruction* it = &instructions()[bytecodeOffset];
254     dumpBytecode(out, instructions().begin(), it, statusMap);
255 }
256
257 #define FOR_EACH_MEMBER_VECTOR(macro) \
258     macro(instructions) \
259     macro(callLinkInfos) \
260     macro(linkedCallerList) \
261     macro(identifiers) \
262     macro(functionExpressions) \
263     macro(constantRegisters)
264
265 template<typename T>
266 static size_t sizeInBytes(const Vector<T>& vector)
267 {
268     return vector.capacity() * sizeof(T);
269 }
270
271 namespace {
272
273 class PutToScopeFireDetail : public FireDetail {
274 public:
275     PutToScopeFireDetail(CodeBlock* codeBlock, const Identifier& ident)
276         : m_codeBlock(codeBlock)
277         , m_ident(ident)
278     {
279     }
280     
281     void dump(PrintStream& out) const override
282     {
283         out.print("Linking put_to_scope in ", FunctionExecutableDump(jsCast<FunctionExecutable*>(m_codeBlock->ownerExecutable())), " for ", m_ident);
284     }
285     
286 private:
287     CodeBlock* m_codeBlock;
288     const Identifier& m_ident;
289 };
290
291 } // anonymous namespace
292
293 CodeBlock::CodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, CodeBlock& other)
294     : JSCell(*vm, structure)
295     , m_globalObject(other.m_globalObject)
296     , m_shouldAlwaysBeInlined(true)
297 #if ENABLE(JIT)
298     , m_capabilityLevelState(DFG::CapabilityLevelNotSet)
299 #endif
300     , m_didFailJITCompilation(false)
301     , m_didFailFTLCompilation(false)
302     , m_hasBeenCompiledWithFTL(false)
303     , m_isConstructor(other.m_isConstructor)
304     , m_isStrictMode(other.m_isStrictMode)
305     , m_codeType(other.m_codeType)
306     , m_numCalleeLocals(other.m_numCalleeLocals)
307     , m_numVars(other.m_numVars)
308     , m_numberOfArgumentsToSkip(other.m_numberOfArgumentsToSkip)
309     , m_hasDebuggerStatement(false)
310     , m_steppingMode(SteppingModeDisabled)
311     , m_numBreakpoints(0)
312     , m_unlinkedCode(*other.vm(), this, other.m_unlinkedCode.get())
313     , m_ownerExecutable(*other.vm(), this, other.m_ownerExecutable.get())
314     , m_poisonedVM(other.m_poisonedVM)
315     , m_instructions(other.m_instructions)
316     , m_thisRegister(other.m_thisRegister)
317     , m_scopeRegister(other.m_scopeRegister)
318     , m_hash(other.m_hash)
319     , m_source(other.m_source)
320     , m_sourceOffset(other.m_sourceOffset)
321     , m_firstLineColumnOffset(other.m_firstLineColumnOffset)
322     , m_constantRegisters(other.m_constantRegisters)
323     , m_constantsSourceCodeRepresentation(other.m_constantsSourceCodeRepresentation)
324     , m_functionDecls(other.m_functionDecls)
325     , m_functionExprs(other.m_functionExprs)
326     , m_osrExitCounter(0)
327     , m_optimizationDelayCounter(0)
328     , m_reoptimizationRetryCounter(0)
329     , m_creationTime(MonotonicTime::now())
330 {
331     ASSERT(heap()->isDeferred());
332     ASSERT(m_scopeRegister.isLocal());
333
334     setNumParameters(other.numParameters());
335     
336     vm->heap.codeBlockSet().add(this);
337 }
338
339 void CodeBlock::finishCreation(VM& vm, CopyParsedBlockTag, CodeBlock& other)
340 {
341     Base::finishCreation(vm);
342     finishCreationCommon(vm);
343
344     optimizeAfterWarmUp();
345     jitAfterWarmUp();
346
347     if (other.m_rareData) {
348         createRareDataIfNecessary();
349         
350         m_rareData->m_exceptionHandlers = other.m_rareData->m_exceptionHandlers;
351         m_rareData->m_switchJumpTables = other.m_rareData->m_switchJumpTables;
352         m_rareData->m_stringSwitchJumpTables = other.m_rareData->m_stringSwitchJumpTables;
353     }
354 }
355
356 CodeBlock::CodeBlock(VM* vm, Structure* structure, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock,
357     JSScope* scope, RefPtr<SourceProvider>&& sourceProvider, unsigned sourceOffset, unsigned firstLineColumnOffset)
358     : JSCell(*vm, structure)
359     , m_globalObject(*vm, this, scope->globalObject(*vm))
360     , m_shouldAlwaysBeInlined(true)
361 #if ENABLE(JIT)
362     , m_capabilityLevelState(DFG::CapabilityLevelNotSet)
363 #endif
364     , m_didFailJITCompilation(false)
365     , m_didFailFTLCompilation(false)
366     , m_hasBeenCompiledWithFTL(false)
367     , m_isConstructor(unlinkedCodeBlock->isConstructor())
368     , m_isStrictMode(unlinkedCodeBlock->isStrictMode())
369     , m_codeType(unlinkedCodeBlock->codeType())
370     , m_numCalleeLocals(unlinkedCodeBlock->numCalleeLocals())
371     , m_numVars(unlinkedCodeBlock->numVars())
372     , m_hasDebuggerStatement(false)
373     , m_steppingMode(SteppingModeDisabled)
374     , m_numBreakpoints(0)
375     , m_unlinkedCode(*vm, this, unlinkedCodeBlock)
376     , m_ownerExecutable(*vm, this, ownerExecutable)
377     , m_poisonedVM(vm)
378     , m_thisRegister(unlinkedCodeBlock->thisRegister())
379     , m_scopeRegister(unlinkedCodeBlock->scopeRegister())
380     , m_source(WTFMove(sourceProvider))
381     , m_sourceOffset(sourceOffset)
382     , m_firstLineColumnOffset(firstLineColumnOffset)
383     , m_osrExitCounter(0)
384     , m_optimizationDelayCounter(0)
385     , m_reoptimizationRetryCounter(0)
386     , m_creationTime(MonotonicTime::now())
387 {
388     ASSERT(heap()->isDeferred());
389     ASSERT(m_scopeRegister.isLocal());
390
391     ASSERT(m_source);
392     setNumParameters(unlinkedCodeBlock->numParameters());
393     
394     vm->heap.codeBlockSet().add(this);
395 }
396
397 // The main purpose of this function is to generate linked bytecode from unlinked bytecode. The process
398 // of linking is taking an abstract representation of bytecode and tying it to a GlobalObject and scope
399 // chain. For example, this process allows us to cache the depth of lexical environment reads that reach
400 // outside of this CodeBlock's compilation unit. It also allows us to generate particular constants that
401 // we can't generate during unlinked bytecode generation. This process is not allowed to generate control
402 // flow or introduce new locals. The reason for this is we rely on liveness analysis to be the same for
403 // all the CodeBlocks of an UnlinkedCodeBlock. We rely on this fact by caching the liveness analysis
404 // inside UnlinkedCodeBlock.
405 bool CodeBlock::finishCreation(VM& vm, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock,
406     JSScope* scope)
407 {
408     Base::finishCreation(vm);
409     finishCreationCommon(vm);
410
411     auto throwScope = DECLARE_THROW_SCOPE(vm);
412
413     if (vm.typeProfiler() || vm.controlFlowProfiler())
414         vm.functionHasExecutedCache()->removeUnexecutedRange(ownerExecutable->sourceID(), ownerExecutable->typeProfilingStartOffset(), ownerExecutable->typeProfilingEndOffset());
415
416     setConstantRegisters(unlinkedCodeBlock->constantRegisters(), unlinkedCodeBlock->constantsSourceCodeRepresentation());
417     RETURN_IF_EXCEPTION(throwScope, false);
418
419     setConstantIdentifierSetRegisters(vm, unlinkedCodeBlock->constantIdentifierSets());
420     RETURN_IF_EXCEPTION(throwScope, false);
421
422     if (unlinkedCodeBlock->usesGlobalObject())
423         m_constantRegisters[unlinkedCodeBlock->globalObjectRegister().toConstantIndex()].set(vm, this, m_globalObject.get());
424
425     for (unsigned i = 0; i < LinkTimeConstantCount; i++) {
426         LinkTimeConstant type = static_cast<LinkTimeConstant>(i);
427         if (unsigned registerIndex = unlinkedCodeBlock->registerIndexForLinkTimeConstant(type))
428             m_constantRegisters[registerIndex].set(vm, this, m_globalObject->jsCellForLinkTimeConstant(type));
429     }
430
431     // We already have the cloned symbol table for the module environment since we need to instantiate
432     // the module environments before linking the code block. We replace the stored symbol table with the already cloned one.
433     if (UnlinkedModuleProgramCodeBlock* unlinkedModuleProgramCodeBlock = jsDynamicCast<UnlinkedModuleProgramCodeBlock*>(vm, unlinkedCodeBlock)) {
434         SymbolTable* clonedSymbolTable = jsCast<ModuleProgramExecutable*>(ownerExecutable)->moduleEnvironmentSymbolTable();
435         if (vm.typeProfiler()) {
436             ConcurrentJSLocker locker(clonedSymbolTable->m_lock);
437             clonedSymbolTable->prepareForTypeProfiling(locker);
438         }
439         replaceConstant(unlinkedModuleProgramCodeBlock->moduleEnvironmentSymbolTableConstantRegisterOffset(), clonedSymbolTable);
440     }
441
442     bool shouldUpdateFunctionHasExecutedCache = vm.typeProfiler() || vm.controlFlowProfiler();
443     m_functionDecls = RefCountedArray<WriteBarrier<FunctionExecutable>>(unlinkedCodeBlock->numberOfFunctionDecls());
444     for (size_t count = unlinkedCodeBlock->numberOfFunctionDecls(), i = 0; i < count; ++i) {
445         UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionDecl(i);
446         if (shouldUpdateFunctionHasExecutedCache)
447             vm.functionHasExecutedCache()->insertUnexecutedRange(ownerExecutable->sourceID(), unlinkedExecutable->typeProfilingStartOffset(), unlinkedExecutable->typeProfilingEndOffset());
448         m_functionDecls[i].set(vm, this, unlinkedExecutable->link(vm, ownerExecutable->source()));
449     }
450
451     m_functionExprs = RefCountedArray<WriteBarrier<FunctionExecutable>>(unlinkedCodeBlock->numberOfFunctionExprs());
452     for (size_t count = unlinkedCodeBlock->numberOfFunctionExprs(), i = 0; i < count; ++i) {
453         UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionExpr(i);
454         if (shouldUpdateFunctionHasExecutedCache)
455             vm.functionHasExecutedCache()->insertUnexecutedRange(ownerExecutable->sourceID(), unlinkedExecutable->typeProfilingStartOffset(), unlinkedExecutable->typeProfilingEndOffset());
456         m_functionExprs[i].set(vm, this, unlinkedExecutable->link(vm, ownerExecutable->source()));
457     }
458
459     if (unlinkedCodeBlock->hasRareData()) {
460         createRareDataIfNecessary();
461         if (size_t count = unlinkedCodeBlock->numberOfExceptionHandlers()) {
462             m_rareData->m_exceptionHandlers.resizeToFit(count);
463             for (size_t i = 0; i < count; i++) {
464                 const UnlinkedHandlerInfo& unlinkedHandler = unlinkedCodeBlock->exceptionHandler(i);
465                 HandlerInfo& handler = m_rareData->m_exceptionHandlers[i];
466 #if ENABLE(JIT)
467                 handler.initialize(unlinkedHandler, CodeLocationLabel<ExceptionHandlerPtrTag>(LLInt::getCodePtr<BytecodePtrTag>(op_catch).retagged<ExceptionHandlerPtrTag>()));
468 #else
469                 handler.initialize(unlinkedHandler);
470 #endif
471             }
472         }
473
474         if (size_t count = unlinkedCodeBlock->numberOfStringSwitchJumpTables()) {
475             m_rareData->m_stringSwitchJumpTables.grow(count);
476             for (size_t i = 0; i < count; i++) {
477                 UnlinkedStringJumpTable::StringOffsetTable::iterator ptr = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.begin();
478                 UnlinkedStringJumpTable::StringOffsetTable::iterator end = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.end();
479                 for (; ptr != end; ++ptr) {
480                     OffsetLocation offset;
481                     offset.branchOffset = ptr->value.branchOffset;
482                     m_rareData->m_stringSwitchJumpTables[i].offsetTable.add(ptr->key, offset);
483                 }
484             }
485         }
486
487         if (size_t count = unlinkedCodeBlock->numberOfSwitchJumpTables()) {
488             m_rareData->m_switchJumpTables.grow(count);
489             for (size_t i = 0; i < count; i++) {
490                 UnlinkedSimpleJumpTable& sourceTable = unlinkedCodeBlock->switchJumpTable(i);
491                 SimpleJumpTable& destTable = m_rareData->m_switchJumpTables[i];
492                 destTable.branchOffsets = sourceTable.branchOffsets;
493                 destTable.min = sourceTable.min;
494             }
495         }
496     }
497
498     // Allocate metadata buffers for the bytecode
499     if (size_t size = unlinkedCodeBlock->numberOfLLintCallLinkInfos())
500         m_llintCallLinkInfos = RefCountedArray<LLIntCallLinkInfo>(size);
501     if (size_t size = unlinkedCodeBlock->numberOfArrayProfiles())
502         m_arrayProfiles.grow(size);
503     if (size_t size = unlinkedCodeBlock->numberOfArrayAllocationProfiles())
504         m_arrayAllocationProfiles = RefCountedArray<ArrayAllocationProfile>(size);
505     if (size_t size = unlinkedCodeBlock->numberOfValueProfiles())
506         m_valueProfiles = RefCountedArray<ValueProfile>(size);
507     if (!vm.canUseJIT())
508         RELEASE_ASSERT(!m_valueProfiles.size());
509     if (size_t size = unlinkedCodeBlock->numberOfObjectAllocationProfiles())
510         m_objectAllocationProfiles = RefCountedArray<ObjectAllocationProfile>(size);
511
512 #if ENABLE(JIT)
513     setCalleeSaveRegisters(RegisterSet::llintBaselineCalleeSaveRegisters());
514 #endif
515
516     // Copy and translate the UnlinkedInstructions
517     unsigned instructionCount = unlinkedCodeBlock->instructions().count();
518     UnlinkedInstructionStream::Reader instructionReader(unlinkedCodeBlock->instructions());
519
520     // Bookkeep the strongly referenced module environments.
521     HashSet<JSModuleEnvironment*> stronglyReferencedModuleEnvironments;
522
523     RefCountedArray<Instruction> instructions(instructionCount);
524
525     unsigned valueProfileCount = 0;
526     auto linkValueProfile = [&](unsigned bytecodeOffset, unsigned opLength) {
527         if (!vm.canUseJIT()) {
528             ASSERT(vm.noJITValueProfileSingleton);
529             instructions[bytecodeOffset + opLength - 1] = vm.noJITValueProfileSingleton.get();
530             return;
531         }
532
533         unsigned valueProfileIndex = valueProfileCount++;
534         ValueProfile* profile = &m_valueProfiles[valueProfileIndex];
535         ASSERT(profile->m_bytecodeOffset == -1);
536         profile->m_bytecodeOffset = bytecodeOffset;
537         instructions[bytecodeOffset + opLength - 1] = profile;
538     };
539
540     for (unsigned i = 0; !instructionReader.atEnd(); ) {
541         const UnlinkedInstruction* pc = instructionReader.next();
542
543         unsigned opLength = opcodeLength(pc[0].u.opcode);
544
545         instructions[i] = Interpreter::getOpcode(pc[0].u.opcode);
546         for (size_t j = 1; j < opLength; ++j) {
547             if (sizeof(int32_t) != sizeof(intptr_t))
548                 instructions[i + j].u.pointer = 0;
549             instructions[i + j].u.operand = pc[j].u.operand;
550         }
551         switch (pc[0].u.opcode) {
552         case op_has_indexed_property: {
553             int arrayProfileIndex = pc[opLength - 1].u.operand;
554             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
555
556             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
557             break;
558         }
559         case op_call_varargs:
560         case op_tail_call_varargs:
561         case op_tail_call_forward_arguments:
562         case op_construct_varargs:
563         case op_get_by_val: {
564             int arrayProfileIndex = pc[opLength - 2].u.operand;
565             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
566
567             instructions[i + opLength - 2] = &m_arrayProfiles[arrayProfileIndex];
568             FALLTHROUGH;
569         }
570         case op_get_direct_pname:
571         case op_get_by_id:
572         case op_get_by_id_with_this:
573         case op_try_get_by_id:
574         case op_get_by_id_direct:
575         case op_get_by_val_with_this:
576         case op_get_from_arguments:
577         case op_to_number:
578         case op_to_object:
579         case op_get_argument: {
580             linkValueProfile(i, opLength);
581             break;
582         }
583
584         case op_to_this: {
585             linkValueProfile(i, opLength);
586             break;
587         }
588
589         case op_in_by_val:
590         case op_put_by_val:
591         case op_put_by_val_direct: {
592             int arrayProfileIndex = pc[opLength - 1].u.operand;
593             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
594             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
595             break;
596         }
597
598         case op_new_array:
599         case op_new_array_with_size:
600         case op_new_array_buffer: {
601             unsigned arrayAllocationProfileIndex;
602             IndexingType recommendedIndexingType;
603             std::tie(arrayAllocationProfileIndex, recommendedIndexingType) = UnlinkedCodeBlock::decompressArrayAllocationProfile(pc[opLength - 1].u.operand);
604
605             ArrayAllocationProfile* profile = &m_arrayAllocationProfiles[arrayAllocationProfileIndex];
606             if (pc[0].u.opcode == op_new_array_buffer)
607                 profile->initializeIndexingMode(recommendedIndexingType);
608             instructions[i + opLength - 1] = profile;
609             break;
610         }
611
612         case op_new_object: {
613             int objectAllocationProfileIndex = pc[opLength - 1].u.operand;
614             ObjectAllocationProfile* objectAllocationProfile = &m_objectAllocationProfiles[objectAllocationProfileIndex];
615             int inferredInlineCapacity = pc[opLength - 2].u.operand;
616
617             instructions[i + opLength - 1] = objectAllocationProfile;
618             objectAllocationProfile->initializeProfile(vm,
619                 m_globalObject.get(), this, m_globalObject->objectPrototype(), inferredInlineCapacity);
620             break;
621         }
622
623         case op_call:
624         case op_tail_call:
625         case op_call_eval: {
626             linkValueProfile(i, opLength);
627             int arrayProfileIndex = pc[opLength - 2].u.operand;
628             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
629             instructions[i + opLength - 2] = &m_arrayProfiles[arrayProfileIndex];
630             instructions[i + 5] = &m_llintCallLinkInfos[pc[5].u.operand];
631             break;
632         }
633         case op_construct: {
634             instructions[i + 5] = &m_llintCallLinkInfos[pc[5].u.operand];
635             linkValueProfile(i, opLength);
636             break;
637         }
638         case op_get_array_length:
639             CRASH();
640
641         case op_resolve_scope: {
642             const Identifier& ident = identifier(pc[3].u.operand);
643             ResolveType type = static_cast<ResolveType>(pc[4].u.operand);
644             RELEASE_ASSERT(type != LocalClosureVar);
645             int localScopeDepth = pc[5].u.operand;
646
647             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Get, type, InitializationMode::NotInitialization);
648             RETURN_IF_EXCEPTION(throwScope, false);
649
650             instructions[i + 4].u.operand = op.type;
651             instructions[i + 5].u.operand = op.depth;
652             if (op.lexicalEnvironment) {
653                 if (op.type == ModuleVar) {
654                     // Keep the linked module environment strongly referenced.
655                     if (stronglyReferencedModuleEnvironments.add(jsCast<JSModuleEnvironment*>(op.lexicalEnvironment)).isNewEntry)
656                         addConstant(op.lexicalEnvironment);
657                     instructions[i + 6].u.jsCell.set(vm, this, op.lexicalEnvironment);
658                 } else
659                     instructions[i + 6].u.symbolTable.set(vm, this, op.lexicalEnvironment->symbolTable());
660             } else if (JSScope* constantScope = JSScope::constantScopeForCodeBlock(op.type, this))
661                 instructions[i + 6].u.jsCell.set(vm, this, constantScope);
662             else
663                 instructions[i + 6].u.pointer = nullptr;
664             break;
665         }
666
667         case op_get_from_scope: {
668             linkValueProfile(i, opLength);
669
670             // get_from_scope dst, scope, id, GetPutInfo, Structure, Operand
671
672             int localScopeDepth = pc[5].u.operand;
673             instructions[i + 5].u.pointer = nullptr;
674
675             GetPutInfo getPutInfo = GetPutInfo(pc[4].u.operand);
676             ASSERT(!isInitialization(getPutInfo.initializationMode()));
677             if (getPutInfo.resolveType() == LocalClosureVar) {
678                 instructions[i + 4] = GetPutInfo(getPutInfo.resolveMode(), ClosureVar, getPutInfo.initializationMode()).operand();
679                 break;
680             }
681
682             const Identifier& ident = identifier(pc[3].u.operand);
683             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Get, getPutInfo.resolveType(), InitializationMode::NotInitialization);
684             RETURN_IF_EXCEPTION(throwScope, false);
685
686             instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), op.type, getPutInfo.initializationMode()).operand();
687             if (op.type == ModuleVar)
688                 instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), ClosureVar, getPutInfo.initializationMode()).operand();
689             if (op.type == GlobalVar || op.type == GlobalVarWithVarInjectionChecks || op.type == GlobalLexicalVar || op.type == GlobalLexicalVarWithVarInjectionChecks)
690                 instructions[i + 5].u.watchpointSet = op.watchpointSet;
691             else if (op.structure)
692                 instructions[i + 5].u.structure.set(vm, this, op.structure);
693             instructions[i + 6].u.pointer = reinterpret_cast<void*>(op.operand);
694             break;
695         }
696
697         case op_put_to_scope: {
698             // put_to_scope scope, id, value, GetPutInfo, Structure, Operand
699             GetPutInfo getPutInfo = GetPutInfo(pc[4].u.operand);
700             if (getPutInfo.resolveType() == LocalClosureVar) {
701                 // Only do watching if the property we're putting to is not anonymous.
702                 if (static_cast<unsigned>(pc[2].u.operand) != UINT_MAX) {
703                     int symbolTableIndex = pc[5].u.operand;
704                     SymbolTable* symbolTable = jsCast<SymbolTable*>(getConstant(symbolTableIndex));
705                     const Identifier& ident = identifier(pc[2].u.operand);
706                     ConcurrentJSLocker locker(symbolTable->m_lock);
707                     auto iter = symbolTable->find(locker, ident.impl());
708                     ASSERT(iter != symbolTable->end(locker));
709                     iter->value.prepareToWatch();
710                     instructions[i + 5].u.watchpointSet = iter->value.watchpointSet();
711                 } else
712                     instructions[i + 5].u.watchpointSet = nullptr;
713                 break;
714             }
715
716             const Identifier& ident = identifier(pc[2].u.operand);
717             int localScopeDepth = pc[5].u.operand;
718             instructions[i + 5].u.pointer = nullptr;
719             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Put, getPutInfo.resolveType(), getPutInfo.initializationMode());
720             RETURN_IF_EXCEPTION(throwScope, false);
721
722             instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), op.type, getPutInfo.initializationMode()).operand();
723             if (op.type == GlobalVar || op.type == GlobalVarWithVarInjectionChecks || op.type == GlobalLexicalVar || op.type == GlobalLexicalVarWithVarInjectionChecks)
724                 instructions[i + 5].u.watchpointSet = op.watchpointSet;
725             else if (op.type == ClosureVar || op.type == ClosureVarWithVarInjectionChecks) {
726                 if (op.watchpointSet)
727                     op.watchpointSet->invalidate(vm, PutToScopeFireDetail(this, ident));
728             } else if (op.structure)
729                 instructions[i + 5].u.structure.set(vm, this, op.structure);
730             instructions[i + 6].u.pointer = reinterpret_cast<void*>(op.operand);
731
732             break;
733         }
734
735         case op_profile_type: {
736             RELEASE_ASSERT(vm.typeProfiler());
737             // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType?
738             size_t instructionOffset = i + opLength - 1;
739             unsigned divotStart, divotEnd;
740             GlobalVariableID globalVariableID = 0;
741             RefPtr<TypeSet> globalTypeSet;
742             bool shouldAnalyze = m_unlinkedCode->typeProfilerExpressionInfoForBytecodeOffset(instructionOffset, divotStart, divotEnd);
743             VirtualRegister profileRegister(pc[1].u.operand);
744             ProfileTypeBytecodeFlag flag = static_cast<ProfileTypeBytecodeFlag>(pc[3].u.operand);
745             SymbolTable* symbolTable = nullptr;
746
747             switch (flag) {
748             case ProfileTypeBytecodeClosureVar: {
749                 const Identifier& ident = identifier(pc[4].u.operand);
750                 int localScopeDepth = pc[2].u.operand;
751                 ResolveType type = static_cast<ResolveType>(pc[5].u.operand);
752                 // Even though type profiling may be profiling either a Get or a Put, we can always claim a Get because
753                 // we're abstractly "read"ing from a JSScope.
754                 ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Get, type, InitializationMode::NotInitialization);
755                 RETURN_IF_EXCEPTION(throwScope, false);
756
757                 if (op.type == ClosureVar || op.type == ModuleVar)
758                     symbolTable = op.lexicalEnvironment->symbolTable();
759                 else if (op.type == GlobalVar)
760                     symbolTable = m_globalObject.get()->symbolTable();
761
762                 UniquedStringImpl* impl = (op.type == ModuleVar) ? op.importedName.get() : ident.impl();
763                 if (symbolTable) {
764                     ConcurrentJSLocker locker(symbolTable->m_lock);
765                     // If our parent scope was created while profiling was disabled, it will not have prepared for profiling yet.
766                     symbolTable->prepareForTypeProfiling(locker);
767                     globalVariableID = symbolTable->uniqueIDForVariable(locker, impl, vm);
768                     globalTypeSet = symbolTable->globalTypeSetForVariable(locker, impl, vm);
769                 } else
770                     globalVariableID = TypeProfilerNoGlobalIDExists;
771
772                 break;
773             }
774             case ProfileTypeBytecodeLocallyResolved: {
775                 int symbolTableIndex = pc[2].u.operand;
776                 SymbolTable* symbolTable = jsCast<SymbolTable*>(getConstant(symbolTableIndex));
777                 const Identifier& ident = identifier(pc[4].u.operand);
778                 ConcurrentJSLocker locker(symbolTable->m_lock);
779                 // If our parent scope was created while profiling was disabled, it will not have prepared for profiling yet.
780                 globalVariableID = symbolTable->uniqueIDForVariable(locker, ident.impl(), vm);
781                 globalTypeSet = symbolTable->globalTypeSetForVariable(locker, ident.impl(), vm);
782
783                 break;
784             }
785             case ProfileTypeBytecodeDoesNotHaveGlobalID: 
786             case ProfileTypeBytecodeFunctionArgument: {
787                 globalVariableID = TypeProfilerNoGlobalIDExists;
788                 break;
789             }
790             case ProfileTypeBytecodeFunctionReturnStatement: {
791                 RELEASE_ASSERT(ownerExecutable->isFunctionExecutable());
792                 globalTypeSet = jsCast<FunctionExecutable*>(ownerExecutable)->returnStatementTypeSet();
793                 globalVariableID = TypeProfilerReturnStatement;
794                 if (!shouldAnalyze) {
795                     // Because a return statement can be added implicitly to return undefined at the end of a function,
796                     // and these nodes don't emit expression ranges because they aren't in the actual source text of
797                     // the user's program, give the type profiler some range to identify these return statements.
798                     // Currently, the text offset that is used as identification is "f" in the function keyword
799                     // and is stored on TypeLocation's m_divotForFunctionOffsetIfReturnStatement member variable.
800                     divotStart = divotEnd = ownerExecutable->typeProfilingStartOffset();
801                     shouldAnalyze = true;
802                 }
803                 break;
804             }
805             }
806
807             std::pair<TypeLocation*, bool> locationPair = vm.typeProfiler()->typeLocationCache()->getTypeLocation(globalVariableID,
808                 ownerExecutable->sourceID(), divotStart, divotEnd, WTFMove(globalTypeSet), &vm);
809             TypeLocation* location = locationPair.first;
810             bool isNewLocation = locationPair.second;
811
812             if (flag == ProfileTypeBytecodeFunctionReturnStatement)
813                 location->m_divotForFunctionOffsetIfReturnStatement = ownerExecutable->typeProfilingStartOffset();
814
815             if (shouldAnalyze && isNewLocation)
816                 vm.typeProfiler()->insertNewLocation(location);
817
818             instructions[i + 2].u.location = location;
819             break;
820         }
821
822         case op_debug: {
823             if (pc[1].u.unsignedValue == DidReachBreakpoint)
824                 m_hasDebuggerStatement = true;
825             break;
826         }
827
828         case op_create_rest: {
829             int numberOfArgumentsToSkip = instructions[i + 3].u.operand;
830             ASSERT_UNUSED(numberOfArgumentsToSkip, numberOfArgumentsToSkip >= 0);
831             // This is used when rematerializing the rest parameter during OSR exit in the FTL JIT.");
832             m_numberOfArgumentsToSkip = numberOfArgumentsToSkip;
833             break;
834         }
835         
836         default:
837             break;
838         }
839
840         i += opLength;
841     }
842
843     if (vm.controlFlowProfiler())
844         insertBasicBlockBoundariesForControlFlowProfiler(instructions);
845
846     m_instructions = WTFMove(instructions);
847
848     // Set optimization thresholds only after m_instructions is initialized, since these
849     // rely on the instruction count (and are in theory permitted to also inspect the
850     // instruction stream to more accurate assess the cost of tier-up).
851     optimizeAfterWarmUp();
852     jitAfterWarmUp();
853
854     // If the concurrent thread will want the code block's hash, then compute it here
855     // synchronously.
856     if (Options::alwaysComputeHash())
857         hash();
858
859     if (Options::dumpGeneratedBytecodes())
860         dumpBytecode();
861
862     heap()->reportExtraMemoryAllocated(m_instructions.size() * sizeof(Instruction));
863
864     return true;
865 }
866
867 void CodeBlock::finishCreationCommon(VM& vm)
868 {
869     m_ownerEdge.set(vm, this, ExecutableToCodeBlockEdge::create(vm, this));
870 }
871
872 CodeBlock::~CodeBlock()
873 {
874     VM& vm = *m_poisonedVM;
875
876     vm.heap.codeBlockSet().remove(this);
877     
878     if (UNLIKELY(vm.m_perBytecodeProfiler))
879         vm.m_perBytecodeProfiler->notifyDestruction(this);
880
881     if (!vm.heap.isShuttingDown() && unlinkedCodeBlock()->didOptimize() == MixedTriState)
882         unlinkedCodeBlock()->setDidOptimize(FalseTriState);
883
884 #if ENABLE(VERBOSE_VALUE_PROFILE)
885     dumpValueProfiles();
886 #endif
887
888     // We may be destroyed before any CodeBlocks that refer to us are destroyed.
889     // Consider that two CodeBlocks become unreachable at the same time. There
890     // is no guarantee about the order in which the CodeBlocks are destroyed.
891     // So, if we don't remove incoming calls, and get destroyed before the
892     // CodeBlock(s) that have calls into us, then the CallLinkInfo vector's
893     // destructor will try to remove nodes from our (no longer valid) linked list.
894     unlinkIncomingCalls();
895     
896     // Note that our outgoing calls will be removed from other CodeBlocks'
897     // m_incomingCalls linked lists through the execution of the ~CallLinkInfo
898     // destructors.
899
900 #if ENABLE(JIT)
901     for (auto iter = m_stubInfos.begin(); !!iter; ++iter) {
902         StructureStubInfo* stub = *iter;
903         stub->aboutToDie();
904         stub->deref();
905     }
906 #endif // ENABLE(JIT)
907 }
908
909 void CodeBlock::setConstantIdentifierSetRegisters(VM& vm, const Vector<ConstantIndentifierSetEntry>& constants)
910 {
911     auto scope = DECLARE_THROW_SCOPE(vm);
912     JSGlobalObject* globalObject = m_globalObject.get();
913     ExecState* exec = globalObject->globalExec();
914
915     for (const auto& entry : constants) {
916         const IdentifierSet& set = entry.first;
917
918         Structure* setStructure = globalObject->setStructure();
919         RETURN_IF_EXCEPTION(scope, void());
920         JSSet* jsSet = JSSet::create(exec, vm, setStructure, set.size());
921         RETURN_IF_EXCEPTION(scope, void());
922
923         for (auto setEntry : set) {
924             JSString* jsString = jsOwnedString(&vm, setEntry.get()); 
925             jsSet->add(exec, jsString);
926             RETURN_IF_EXCEPTION(scope, void());
927         }
928         m_constantRegisters[entry.second].set(vm, this, jsSet);
929     }
930 }
931
932 void CodeBlock::setConstantRegisters(const Vector<WriteBarrier<Unknown>>& constants, const Vector<SourceCodeRepresentation>& constantsSourceCodeRepresentation)
933 {
934     VM& vm = *m_poisonedVM;
935     auto scope = DECLARE_THROW_SCOPE(vm);
936     JSGlobalObject* globalObject = m_globalObject.get();
937     ExecState* exec = globalObject->globalExec();
938
939     ASSERT(constants.size() == constantsSourceCodeRepresentation.size());
940     size_t count = constants.size();
941     m_constantRegisters.resizeToFit(count);
942     bool hasTypeProfiler = !!vm.typeProfiler();
943     for (size_t i = 0; i < count; i++) {
944         JSValue constant = constants[i].get();
945
946         if (!constant.isEmpty()) {
947             if (constant.isCell()) {
948                 JSCell* cell = constant.asCell();
949                 if (SymbolTable* symbolTable = jsDynamicCast<SymbolTable*>(vm, cell)) {
950                     if (hasTypeProfiler) {
951                         ConcurrentJSLocker locker(symbolTable->m_lock);
952                         symbolTable->prepareForTypeProfiling(locker);
953                     }
954
955                     SymbolTable* clone = symbolTable->cloneScopePart(vm);
956                     if (wasCompiledWithDebuggingOpcodes())
957                         clone->setRareDataCodeBlock(this);
958
959                     constant = clone;
960                 } else if (auto* descriptor = jsDynamicCast<JSTemplateObjectDescriptor*>(vm, cell)) {
961                     auto* templateObject = descriptor->createTemplateObject(exec);
962                     RETURN_IF_EXCEPTION(scope, void());
963                     constant = templateObject;
964                 }
965             }
966         }
967
968         m_constantRegisters[i].set(vm, this, constant);
969     }
970
971     m_constantsSourceCodeRepresentation = constantsSourceCodeRepresentation;
972 }
973
974 void CodeBlock::setAlternative(VM& vm, CodeBlock* alternative)
975 {
976     m_alternative.set(vm, this, alternative);
977 }
978
979 void CodeBlock::setNumParameters(int newValue)
980 {
981     m_numParameters = newValue;
982
983     m_argumentValueProfiles = RefCountedArray<ValueProfile>(vm()->canUseJIT() ? newValue : 0);
984 }
985
986 CodeBlock* CodeBlock::specialOSREntryBlockOrNull()
987 {
988 #if ENABLE(FTL_JIT)
989     if (jitType() != JITCode::DFGJIT)
990         return 0;
991     DFG::JITCode* jitCode = m_jitCode->dfg();
992     return jitCode->osrEntryBlock();
993 #else // ENABLE(FTL_JIT)
994     return 0;
995 #endif // ENABLE(FTL_JIT)
996 }
997
998 size_t CodeBlock::estimatedSize(JSCell* cell, VM& vm)
999 {
1000     CodeBlock* thisObject = jsCast<CodeBlock*>(cell);
1001     size_t extraMemoryAllocated = thisObject->m_instructions.size() * sizeof(Instruction);
1002     if (thisObject->m_jitCode)
1003         extraMemoryAllocated += thisObject->m_jitCode->size();
1004     return Base::estimatedSize(cell, vm) + extraMemoryAllocated;
1005 }
1006
1007 void CodeBlock::visitChildren(JSCell* cell, SlotVisitor& visitor)
1008 {
1009     CodeBlock* thisObject = jsCast<CodeBlock*>(cell);
1010     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
1011     Base::visitChildren(cell, visitor);
1012     visitor.append(thisObject->m_ownerEdge);
1013     thisObject->visitChildren(visitor);
1014 }
1015
1016 void CodeBlock::visitChildren(SlotVisitor& visitor)
1017 {
1018     ConcurrentJSLocker locker(m_lock);
1019     if (CodeBlock* otherBlock = specialOSREntryBlockOrNull())
1020         visitor.appendUnbarriered(otherBlock);
1021
1022     if (m_jitCode)
1023         visitor.reportExtraMemoryVisited(m_jitCode->size());
1024     if (m_instructions.size()) {
1025         unsigned refCount = m_instructions.refCount();
1026         if (!refCount) {
1027             dataLog("CodeBlock: ", RawPointer(this), "\n");
1028             dataLog("m_instructions.data(): ", RawPointer(m_instructions.data()), "\n");
1029             dataLog("refCount: ", refCount, "\n");
1030             RELEASE_ASSERT_NOT_REACHED();
1031         }
1032         visitor.reportExtraMemoryVisited(m_instructions.size() * sizeof(Instruction) / refCount);
1033     }
1034
1035     stronglyVisitStrongReferences(locker, visitor);
1036     stronglyVisitWeakReferences(locker, visitor);
1037     
1038     VM::SpaceAndFinalizerSet::finalizerSetFor(*subspace()).add(this);
1039 }
1040
1041 bool CodeBlock::shouldVisitStrongly(const ConcurrentJSLocker& locker)
1042 {
1043     if (Options::forceCodeBlockLiveness())
1044         return true;
1045
1046     if (shouldJettisonDueToOldAge(locker))
1047         return false;
1048
1049     // Interpreter and Baseline JIT CodeBlocks don't need to be jettisoned when
1050     // their weak references go stale. So if a basline JIT CodeBlock gets
1051     // scanned, we can assume that this means that it's live.
1052     if (!JITCode::isOptimizingJIT(jitType()))
1053         return true;
1054
1055     return false;
1056 }
1057
1058 bool CodeBlock::shouldJettisonDueToWeakReference()
1059 {
1060     if (!JITCode::isOptimizingJIT(jitType()))
1061         return false;
1062     return !Heap::isMarked(this);
1063 }
1064
1065 static Seconds timeToLive(JITCode::JITType jitType)
1066 {
1067     if (UNLIKELY(Options::useEagerCodeBlockJettisonTiming())) {
1068         switch (jitType) {
1069         case JITCode::InterpreterThunk:
1070             return 10_ms;
1071         case JITCode::BaselineJIT:
1072             return 30_ms;
1073         case JITCode::DFGJIT:
1074             return 40_ms;
1075         case JITCode::FTLJIT:
1076             return 120_ms;
1077         default:
1078             return Seconds::infinity();
1079         }
1080     }
1081
1082     switch (jitType) {
1083     case JITCode::InterpreterThunk:
1084         return 5_s;
1085     case JITCode::BaselineJIT:
1086         // Effectively 10 additional seconds, since BaselineJIT and
1087         // InterpreterThunk share a CodeBlock.
1088         return 15_s;
1089     case JITCode::DFGJIT:
1090         return 20_s;
1091     case JITCode::FTLJIT:
1092         return 60_s;
1093     default:
1094         return Seconds::infinity();
1095     }
1096 }
1097
1098 bool CodeBlock::shouldJettisonDueToOldAge(const ConcurrentJSLocker&)
1099 {
1100     if (Heap::isMarked(this))
1101         return false;
1102
1103     if (UNLIKELY(Options::forceCodeBlockToJettisonDueToOldAge()))
1104         return true;
1105     
1106     if (timeSinceCreation() < timeToLive(jitType()))
1107         return false;
1108     
1109     return true;
1110 }
1111
1112 #if ENABLE(DFG_JIT)
1113 static bool shouldMarkTransition(DFG::WeakReferenceTransition& transition)
1114 {
1115     if (transition.m_codeOrigin && !Heap::isMarked(transition.m_codeOrigin.get()))
1116         return false;
1117     
1118     if (!Heap::isMarked(transition.m_from.get()))
1119         return false;
1120     
1121     return true;
1122 }
1123 #endif // ENABLE(DFG_JIT)
1124
1125 void CodeBlock::propagateTransitions(const ConcurrentJSLocker&, SlotVisitor& visitor)
1126 {
1127     UNUSED_PARAM(visitor);
1128
1129     VM& vm = *m_poisonedVM;
1130
1131     if (jitType() == JITCode::InterpreterThunk) {
1132         const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
1133         for (size_t i = 0; i < propertyAccessInstructions.size(); ++i) {
1134             Instruction* instruction = &instructions()[propertyAccessInstructions[i]];
1135             switch (Interpreter::getOpcodeID(instruction[0])) {
1136             case op_put_by_id: {
1137                 StructureID oldStructureID = instruction[4].u.structureID;
1138                 StructureID newStructureID = instruction[6].u.structureID;
1139                 if (!oldStructureID || !newStructureID)
1140                     break;
1141                 Structure* oldStructure =
1142                     vm.heap.structureIDTable().get(oldStructureID);
1143                 Structure* newStructure =
1144                     vm.heap.structureIDTable().get(newStructureID);
1145                 if (Heap::isMarked(oldStructure))
1146                     visitor.appendUnbarriered(newStructure);
1147                 break;
1148             }
1149             default:
1150                 break;
1151             }
1152         }
1153     }
1154
1155 #if ENABLE(JIT)
1156     if (JITCode::isJIT(jitType())) {
1157         for (auto iter = m_stubInfos.begin(); !!iter; ++iter)
1158             (*iter)->propagateTransitions(visitor);
1159     }
1160 #endif // ENABLE(JIT)
1161     
1162 #if ENABLE(DFG_JIT)
1163     if (JITCode::isOptimizingJIT(jitType())) {
1164         DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
1165         
1166         dfgCommon->recordedStatuses.markIfCheap(visitor);
1167         
1168         for (auto& weakReference : dfgCommon->weakStructureReferences)
1169             weakReference->markIfCheap(visitor);
1170
1171         for (auto& transition : dfgCommon->transitions) {
1172             if (shouldMarkTransition(transition)) {
1173                 // If the following three things are live, then the target of the
1174                 // transition is also live:
1175                 //
1176                 // - This code block. We know it's live already because otherwise
1177                 //   we wouldn't be scanning ourselves.
1178                 //
1179                 // - The code origin of the transition. Transitions may arise from
1180                 //   code that was inlined. They are not relevant if the user's
1181                 //   object that is required for the inlinee to run is no longer
1182                 //   live.
1183                 //
1184                 // - The source of the transition. The transition checks if some
1185                 //   heap location holds the source, and if so, stores the target.
1186                 //   Hence the source must be live for the transition to be live.
1187                 //
1188                 // We also short-circuit the liveness if the structure is harmless
1189                 // to mark (i.e. its global object and prototype are both already
1190                 // live).
1191
1192                 visitor.append(transition.m_to);
1193             }
1194         }
1195     }
1196 #endif // ENABLE(DFG_JIT)
1197 }
1198
1199 void CodeBlock::determineLiveness(const ConcurrentJSLocker&, SlotVisitor& visitor)
1200 {
1201     UNUSED_PARAM(visitor);
1202     
1203 #if ENABLE(DFG_JIT)
1204     if (Heap::isMarked(this))
1205         return;
1206     
1207     // In rare and weird cases, this could be called on a baseline CodeBlock. One that I found was
1208     // that we might decide that the CodeBlock should be jettisoned due to old age, so the
1209     // isMarked check doesn't protect us.
1210     if (!JITCode::isOptimizingJIT(jitType()))
1211         return;
1212     
1213     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
1214     // Now check all of our weak references. If all of them are live, then we
1215     // have proved liveness and so we scan our strong references. If at end of
1216     // GC we still have not proved liveness, then this code block is toast.
1217     bool allAreLiveSoFar = true;
1218     for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
1219         JSCell* reference = dfgCommon->weakReferences[i].get();
1220         ASSERT(!jsDynamicCast<CodeBlock*>(*reference->vm(), reference));
1221         if (!Heap::isMarked(reference)) {
1222             allAreLiveSoFar = false;
1223             break;
1224         }
1225     }
1226     if (allAreLiveSoFar) {
1227         for (unsigned i = 0; i < dfgCommon->weakStructureReferences.size(); ++i) {
1228             if (!Heap::isMarked(dfgCommon->weakStructureReferences[i].get())) {
1229                 allAreLiveSoFar = false;
1230                 break;
1231             }
1232         }
1233     }
1234     
1235     // If some weak references are dead, then this fixpoint iteration was
1236     // unsuccessful.
1237     if (!allAreLiveSoFar)
1238         return;
1239     
1240     // All weak references are live. Record this information so we don't
1241     // come back here again, and scan the strong references.
1242     visitor.appendUnbarriered(this);
1243 #endif // ENABLE(DFG_JIT)
1244 }
1245
1246 void CodeBlock::clearLLIntGetByIdCache(Instruction* instruction)
1247 {
1248     instruction[0].u.opcode = LLInt::getOpcode(op_get_by_id);
1249     instruction[4].u.pointer = nullptr;
1250     instruction[5].u.pointer = nullptr;
1251     instruction[6].u.pointer = nullptr;
1252 }
1253
1254 void CodeBlock::finalizeLLIntInlineCaches()
1255 {
1256     VM& vm = *m_poisonedVM;
1257     const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
1258     for (size_t size = propertyAccessInstructions.size(), i = 0; i < size; ++i) {
1259         Instruction* curInstruction = &instructions()[propertyAccessInstructions[i]];
1260         switch (Interpreter::getOpcodeID(curInstruction[0])) {
1261         case op_get_by_id: {
1262             StructureID oldStructureID = curInstruction[4].u.structureID;
1263             if (!oldStructureID || Heap::isMarked(vm.heap.structureIDTable().get(oldStructureID)))
1264                 break;
1265             if (Options::verboseOSR())
1266                 dataLogF("Clearing LLInt property access.\n");
1267             clearLLIntGetByIdCache(curInstruction);
1268             break;
1269         }
1270         case op_get_by_id_direct: {
1271             StructureID oldStructureID = curInstruction[4].u.structureID;
1272             if (!oldStructureID || Heap::isMarked(vm.heap.structureIDTable().get(oldStructureID)))
1273                 break;
1274             if (Options::verboseOSR())
1275                 dataLogF("Clearing LLInt property access.\n");
1276             curInstruction[4].u.pointer = nullptr;
1277             curInstruction[5].u.pointer = nullptr;
1278             break;
1279         }
1280         case op_put_by_id: {
1281             StructureID oldStructureID = curInstruction[4].u.structureID;
1282             StructureID newStructureID = curInstruction[6].u.structureID;
1283             StructureChain* chain = curInstruction[7].u.structureChain.get();
1284             if ((!oldStructureID || Heap::isMarked(vm.heap.structureIDTable().get(oldStructureID)))
1285                 && (!newStructureID || Heap::isMarked(vm.heap.structureIDTable().get(newStructureID)))
1286                 && (!chain || Heap::isMarked(chain)))
1287                 break;
1288             if (Options::verboseOSR())
1289                 dataLogF("Clearing LLInt put transition.\n");
1290             curInstruction[4].u.structureID = 0;
1291             curInstruction[5].u.operand = 0;
1292             curInstruction[6].u.structureID = 0;
1293             curInstruction[7].u.structureChain.clear();
1294             break;
1295         }
1296         // FIXME: https://bugs.webkit.org/show_bug.cgi?id=166418
1297         // We need to add optimizations for op_resolve_scope_for_hoisting_func_decl_in_eval to do link time scope resolution.
1298         case op_resolve_scope_for_hoisting_func_decl_in_eval:
1299             break;
1300         case op_get_by_id_proto_load:
1301         case op_get_by_id_unset:
1302         case op_get_array_length:
1303             break;
1304         case op_to_this:
1305             if (!curInstruction[2].u.structure || Heap::isMarked(curInstruction[2].u.structure.get()))
1306                 break;
1307             if (Options::verboseOSR())
1308                 dataLogF("Clearing LLInt to_this with structure %p.\n", curInstruction[2].u.structure.get());
1309             curInstruction[2].u.structure.clear();
1310             curInstruction[3].u.toThisStatus = merge(
1311                 curInstruction[3].u.toThisStatus, ToThisClearedByGC);
1312             break;
1313         case op_create_this: {
1314             auto& cacheWriteBarrier = curInstruction[4].u.jsCell;
1315             if (!cacheWriteBarrier || cacheWriteBarrier.unvalidatedGet() == JSCell::seenMultipleCalleeObjects())
1316                 break;
1317             JSCell* cachedFunction = cacheWriteBarrier.get();
1318             if (Heap::isMarked(cachedFunction))
1319                 break;
1320             if (Options::verboseOSR())
1321                 dataLogF("Clearing LLInt create_this with cached callee %p.\n", cachedFunction);
1322             cacheWriteBarrier.clear();
1323             break;
1324         }
1325         case op_resolve_scope: {
1326             // Right now this isn't strictly necessary. Any symbol tables that this will refer to
1327             // are for outer functions, and we refer to those functions strongly, and they refer
1328             // to the symbol table strongly. But it's nice to be on the safe side.
1329             WriteBarrierBase<SymbolTable>& symbolTable = curInstruction[6].u.symbolTable;
1330             if (!symbolTable || Heap::isMarked(symbolTable.get()))
1331                 break;
1332             if (Options::verboseOSR())
1333                 dataLogF("Clearing dead symbolTable %p.\n", symbolTable.get());
1334             symbolTable.clear();
1335             break;
1336         }
1337         case op_get_from_scope:
1338         case op_put_to_scope: {
1339             GetPutInfo getPutInfo = GetPutInfo(curInstruction[4].u.operand);
1340             if (getPutInfo.resolveType() == GlobalVar || getPutInfo.resolveType() == GlobalVarWithVarInjectionChecks 
1341                 || getPutInfo.resolveType() == LocalClosureVar || getPutInfo.resolveType() == GlobalLexicalVar || getPutInfo.resolveType() == GlobalLexicalVarWithVarInjectionChecks)
1342                 continue;
1343             WriteBarrierBase<Structure>& structure = curInstruction[5].u.structure;
1344             if (!structure || Heap::isMarked(structure.get()))
1345                 break;
1346             if (Options::verboseOSR())
1347                 dataLogF("Clearing scope access with structure %p.\n", structure.get());
1348             structure.clear();
1349             break;
1350         }
1351         default:
1352             OpcodeID opcodeID = Interpreter::getOpcodeID(curInstruction[0]);
1353             ASSERT_WITH_MESSAGE_UNUSED(opcodeID, false, "Unhandled opcode in CodeBlock::finalizeUnconditionally, %s(%d) at bc %u", opcodeNames[opcodeID], opcodeID, propertyAccessInstructions[i]);
1354         }
1355     }
1356
1357     // We can't just remove all the sets when we clear the caches since we might have created a watchpoint set
1358     // then cleared the cache without GCing in between.
1359     m_llintGetByIdWatchpointMap.removeIf([&] (const StructureWatchpointMap::KeyValuePairType& pair) -> bool {
1360         auto clear = [&] () {
1361             Instruction* instruction = std::get<1>(pair.key);
1362             OpcodeID opcode = Interpreter::getOpcodeID(*instruction);
1363             if (opcode == op_get_by_id_proto_load || opcode == op_get_by_id_unset) {
1364                 if (Options::verboseOSR())
1365                     dataLogF("Clearing LLInt property access.\n");
1366                 clearLLIntGetByIdCache(instruction);
1367             }
1368             return true;
1369         };
1370
1371         if (!Heap::isMarked(std::get<0>(pair.key)))
1372             return clear();
1373
1374         for (const LLIntPrototypeLoadAdaptiveStructureWatchpoint* watchpoint : pair.value) {
1375             if (!watchpoint->key().isStillLive())
1376                 return clear();
1377         }
1378
1379         return false;
1380     });
1381
1382     for (unsigned i = 0; i < m_llintCallLinkInfos.size(); ++i) {
1383         if (m_llintCallLinkInfos[i].isLinked() && !Heap::isMarked(m_llintCallLinkInfos[i].callee.get())) {
1384             if (Options::verboseOSR())
1385                 dataLog("Clearing LLInt call from ", *this, "\n");
1386             m_llintCallLinkInfos[i].unlink();
1387         }
1388         if (!!m_llintCallLinkInfos[i].lastSeenCallee && !Heap::isMarked(m_llintCallLinkInfos[i].lastSeenCallee.get()))
1389             m_llintCallLinkInfos[i].lastSeenCallee.clear();
1390     }
1391 }
1392
1393 void CodeBlock::finalizeBaselineJITInlineCaches()
1394 {
1395 #if ENABLE(JIT)
1396     for (auto iter = callLinkInfosBegin(); !!iter; ++iter)
1397         (*iter)->visitWeak(*vm());
1398
1399     for (auto iter = m_stubInfos.begin(); !!iter; ++iter) {
1400         StructureStubInfo& stubInfo = **iter;
1401         stubInfo.visitWeakReferences(this);
1402     }
1403 #endif
1404 }
1405
1406 void CodeBlock::finalizeUnconditionally(VM&)
1407 {
1408     updateAllPredictions();
1409     
1410     if (JITCode::couldBeInterpreted(jitType()))
1411         finalizeLLIntInlineCaches();
1412
1413 #if ENABLE(JIT)
1414     if (!!jitCode())
1415         finalizeBaselineJITInlineCaches();
1416 #endif
1417
1418     if (JITCode::isOptimizingJIT(jitType())) {
1419         DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
1420         dfgCommon->recordedStatuses.finalize();
1421     }
1422
1423     VM::SpaceAndFinalizerSet::finalizerSetFor(*subspace()).remove(this);
1424 }
1425
1426 void CodeBlock::getICStatusMap(const ConcurrentJSLocker&, ICStatusMap& result)
1427 {
1428 #if ENABLE(JIT)
1429     if (JITCode::isJIT(jitType())) {
1430         for (StructureStubInfo* stubInfo : m_stubInfos)
1431             result.add(stubInfo->codeOrigin, ICStatus()).iterator->value.stubInfo = stubInfo;
1432         for (CallLinkInfo* callLinkInfo : m_callLinkInfos)
1433             result.add(callLinkInfo->codeOrigin(), ICStatus()).iterator->value.callLinkInfo = callLinkInfo;
1434         for (ByValInfo* byValInfo : m_byValInfos)
1435             result.add(CodeOrigin(byValInfo->bytecodeIndex), ICStatus()).iterator->value.byValInfo = byValInfo;
1436         if (JITCode::isOptimizingJIT(jitType())) {
1437             DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
1438             for (auto& pair : dfgCommon->recordedStatuses.calls)
1439                 result.add(pair.first, ICStatus()).iterator->value.callStatus = pair.second.get();
1440             for (auto& pair : dfgCommon->recordedStatuses.gets)
1441                 result.add(pair.first, ICStatus()).iterator->value.getStatus = pair.second.get();
1442             for (auto& pair : dfgCommon->recordedStatuses.puts)
1443                 result.add(pair.first, ICStatus()).iterator->value.putStatus = pair.second.get();
1444             for (auto& pair : dfgCommon->recordedStatuses.ins)
1445                 result.add(pair.first, ICStatus()).iterator->value.inStatus = pair.second.get();
1446         }
1447     }
1448 #else
1449     UNUSED_PARAM(result);
1450 #endif
1451 }
1452
1453 void CodeBlock::getICStatusMap(ICStatusMap& result)
1454 {
1455     ConcurrentJSLocker locker(m_lock);
1456     getICStatusMap(locker, result);
1457 }
1458
1459 #if ENABLE(JIT)
1460 StructureStubInfo* CodeBlock::addStubInfo(AccessType accessType)
1461 {
1462     ConcurrentJSLocker locker(m_lock);
1463     return m_stubInfos.add(accessType);
1464 }
1465
1466 JITAddIC* CodeBlock::addJITAddIC(ArithProfile* arithProfile, Instruction* instruction)
1467 {
1468     return m_addICs.add(arithProfile, instruction);
1469 }
1470
1471 JITMulIC* CodeBlock::addJITMulIC(ArithProfile* arithProfile, Instruction* instruction)
1472 {
1473     return m_mulICs.add(arithProfile, instruction);
1474 }
1475
1476 JITSubIC* CodeBlock::addJITSubIC(ArithProfile* arithProfile, Instruction* instruction)
1477 {
1478     return m_subICs.add(arithProfile, instruction);
1479 }
1480
1481 JITNegIC* CodeBlock::addJITNegIC(ArithProfile* arithProfile, Instruction* instruction)
1482 {
1483     return m_negICs.add(arithProfile, instruction);
1484 }
1485
1486 StructureStubInfo* CodeBlock::findStubInfo(CodeOrigin codeOrigin)
1487 {
1488     for (StructureStubInfo* stubInfo : m_stubInfos) {
1489         if (stubInfo->codeOrigin == codeOrigin)
1490             return stubInfo;
1491     }
1492     return nullptr;
1493 }
1494
1495 ByValInfo* CodeBlock::addByValInfo()
1496 {
1497     ConcurrentJSLocker locker(m_lock);
1498     return m_byValInfos.add();
1499 }
1500
1501 CallLinkInfo* CodeBlock::addCallLinkInfo()
1502 {
1503     ConcurrentJSLocker locker(m_lock);
1504     return m_callLinkInfos.add();
1505 }
1506
1507 CallLinkInfo* CodeBlock::getCallLinkInfoForBytecodeIndex(unsigned index)
1508 {
1509     for (auto iter = m_callLinkInfos.begin(); !!iter; ++iter) {
1510         if ((*iter)->codeOrigin() == CodeOrigin(index))
1511             return *iter;
1512     }
1513     return nullptr;
1514 }
1515
1516 void CodeBlock::resetJITData()
1517 {
1518     RELEASE_ASSERT(!JITCode::isJIT(jitType()));
1519     ConcurrentJSLocker locker(m_lock);
1520     
1521     // We can clear these because no other thread will have references to any stub infos, call
1522     // link infos, or by val infos if we don't have JIT code. Attempts to query these data
1523     // structures using the concurrent API (getICStatusMap and friends) will return nothing if we
1524     // don't have JIT code.
1525     m_stubInfos.clear();
1526     m_callLinkInfos.clear();
1527     m_byValInfos.clear();
1528     
1529     // We can clear this because the DFG's queries to these data structures are guarded by whether
1530     // there is JIT code.
1531     m_rareCaseProfiles.clear();
1532 }
1533 #endif
1534
1535 void CodeBlock::visitOSRExitTargets(const ConcurrentJSLocker&, SlotVisitor& visitor)
1536 {
1537     // We strongly visit OSR exits targets because we don't want to deal with
1538     // the complexity of generating an exit target CodeBlock on demand and
1539     // guaranteeing that it matches the details of the CodeBlock we compiled
1540     // the OSR exit against.
1541
1542     visitor.append(m_alternative);
1543
1544 #if ENABLE(DFG_JIT)
1545     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
1546     if (dfgCommon->inlineCallFrames) {
1547         for (auto* inlineCallFrame : *dfgCommon->inlineCallFrames) {
1548             ASSERT(inlineCallFrame->baselineCodeBlock);
1549             visitor.append(inlineCallFrame->baselineCodeBlock);
1550         }
1551     }
1552 #endif
1553 }
1554
1555 void CodeBlock::stronglyVisitStrongReferences(const ConcurrentJSLocker& locker, SlotVisitor& visitor)
1556 {
1557     UNUSED_PARAM(locker);
1558     
1559     visitor.append(m_globalObject);
1560     visitor.append(m_ownerExecutable); // This is extra important since it causes the ExecutableToCodeBlockEdge to be marked.
1561     visitor.append(m_unlinkedCode);
1562     if (m_rareData)
1563         m_rareData->m_directEvalCodeCache.visitAggregate(visitor);
1564     visitor.appendValues(m_constantRegisters.data(), m_constantRegisters.size());
1565     for (auto& functionExpr : m_functionExprs)
1566         visitor.append(functionExpr);
1567     for (auto& functionDecl : m_functionDecls)
1568         visitor.append(functionDecl);
1569     for (auto& objectAllocationProfile : m_objectAllocationProfiles)
1570         objectAllocationProfile.visitAggregate(visitor);
1571
1572 #if ENABLE(JIT)
1573     for (ByValInfo* byValInfo : m_byValInfos)
1574         visitor.append(byValInfo->cachedSymbol);
1575 #endif
1576
1577 #if ENABLE(DFG_JIT)
1578     if (JITCode::isOptimizingJIT(jitType()))
1579         visitOSRExitTargets(locker, visitor);
1580 #endif
1581 }
1582
1583 void CodeBlock::stronglyVisitWeakReferences(const ConcurrentJSLocker&, SlotVisitor& visitor)
1584 {
1585     UNUSED_PARAM(visitor);
1586
1587 #if ENABLE(DFG_JIT)
1588     if (!JITCode::isOptimizingJIT(jitType()))
1589         return;
1590     
1591     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
1592
1593     for (auto& transition : dfgCommon->transitions) {
1594         if (!!transition.m_codeOrigin)
1595             visitor.append(transition.m_codeOrigin); // Almost certainly not necessary, since the code origin should also be a weak reference. Better to be safe, though.
1596         visitor.append(transition.m_from);
1597         visitor.append(transition.m_to);
1598     }
1599
1600     for (auto& weakReference : dfgCommon->weakReferences)
1601         visitor.append(weakReference);
1602
1603     for (auto& weakStructureReference : dfgCommon->weakStructureReferences)
1604         visitor.append(weakStructureReference);
1605
1606     dfgCommon->livenessHasBeenProved = true;
1607 #endif    
1608 }
1609
1610 CodeBlock* CodeBlock::baselineAlternative()
1611 {
1612 #if ENABLE(JIT)
1613     CodeBlock* result = this;
1614     while (result->alternative())
1615         result = result->alternative();
1616     RELEASE_ASSERT(result);
1617     RELEASE_ASSERT(JITCode::isBaselineCode(result->jitType()) || result->jitType() == JITCode::None);
1618     return result;
1619 #else
1620     return this;
1621 #endif
1622 }
1623
1624 CodeBlock* CodeBlock::baselineVersion()
1625 {
1626 #if ENABLE(JIT)
1627     JITCode::JITType selfJITType = jitType();
1628     if (JITCode::isBaselineCode(selfJITType))
1629         return this;
1630     CodeBlock* result = replacement();
1631     if (!result) {
1632         if (JITCode::isOptimizingJIT(selfJITType)) {
1633             // The replacement can be null if we've had a memory clean up and the executable
1634             // has been purged of its codeBlocks (see ExecutableBase::clearCode()). Regardless,
1635             // the current codeBlock is still live on the stack, and as an optimizing JIT
1636             // codeBlock, it will keep its baselineAlternative() alive for us to fetch below.
1637             result = this;
1638         } else {
1639             // This can happen if we're creating the original CodeBlock for an executable.
1640             // Assume that we're the baseline CodeBlock.
1641             RELEASE_ASSERT(selfJITType == JITCode::None);
1642             return this;
1643         }
1644     }
1645     result = result->baselineAlternative();
1646     ASSERT(result);
1647     return result;
1648 #else
1649     return this;
1650 #endif
1651 }
1652
1653 #if ENABLE(JIT)
1654 bool CodeBlock::hasOptimizedReplacement(JITCode::JITType typeToReplace)
1655 {
1656     CodeBlock* replacement = this->replacement();
1657     return replacement && JITCode::isHigherTier(replacement->jitType(), typeToReplace);
1658 }
1659
1660 bool CodeBlock::hasOptimizedReplacement()
1661 {
1662     return hasOptimizedReplacement(jitType());
1663 }
1664 #endif
1665
1666 HandlerInfo* CodeBlock::handlerForBytecodeOffset(unsigned bytecodeOffset, RequiredHandler requiredHandler)
1667 {
1668     RELEASE_ASSERT(bytecodeOffset < instructions().size());
1669     return handlerForIndex(bytecodeOffset, requiredHandler);
1670 }
1671
1672 HandlerInfo* CodeBlock::handlerForIndex(unsigned index, RequiredHandler requiredHandler)
1673 {
1674     if (!m_rareData)
1675         return 0;
1676     return HandlerInfo::handlerForIndex(m_rareData->m_exceptionHandlers, index, requiredHandler);
1677 }
1678
1679 CallSiteIndex CodeBlock::newExceptionHandlingCallSiteIndex(CallSiteIndex originalCallSite)
1680 {
1681 #if ENABLE(DFG_JIT)
1682     RELEASE_ASSERT(JITCode::isOptimizingJIT(jitType()));
1683     RELEASE_ASSERT(canGetCodeOrigin(originalCallSite));
1684     ASSERT(!!handlerForIndex(originalCallSite.bits()));
1685     CodeOrigin originalOrigin = codeOrigin(originalCallSite);
1686     return m_jitCode->dfgCommon()->addUniqueCallSiteIndex(originalOrigin);
1687 #else
1688     // We never create new on-the-fly exception handling
1689     // call sites outside the DFG/FTL inline caches.
1690     UNUSED_PARAM(originalCallSite);
1691     RELEASE_ASSERT_NOT_REACHED();
1692     return CallSiteIndex(0u);
1693 #endif
1694 }
1695
1696 void CodeBlock::ensureCatchLivenessIsComputedForBytecodeOffsetSlow(unsigned bytecodeOffset)
1697 {
1698     ASSERT(Interpreter::getOpcodeID(m_instructions[bytecodeOffset]) == op_catch);
1699     BytecodeLivenessAnalysis& bytecodeLiveness = livenessAnalysis();
1700
1701     // We get the live-out set of variables at op_catch, not the live-in. This
1702     // is because the variables that the op_catch defines might be dead, and
1703     // we can avoid profiling them and extracting them when doing OSR entry
1704     // into the DFG.
1705     FastBitVector liveLocals = bytecodeLiveness.getLivenessInfoAtBytecodeOffset(this, bytecodeOffset + OPCODE_LENGTH(op_catch));
1706     Vector<VirtualRegister> liveOperands;
1707     liveOperands.reserveInitialCapacity(liveLocals.bitCount());
1708     liveLocals.forEachSetBit([&] (unsigned liveLocal) {
1709         liveOperands.append(virtualRegisterForLocal(liveLocal));
1710     });
1711
1712     for (int i = 0; i < numParameters(); ++i)
1713         liveOperands.append(virtualRegisterForArgument(i));
1714
1715     auto profiles = std::make_unique<ValueProfileAndOperandBuffer>(liveOperands.size());
1716     RELEASE_ASSERT(profiles->m_size == liveOperands.size());
1717     for (unsigned i = 0; i < profiles->m_size; ++i)
1718         profiles->m_buffer.get()[i].m_operand = liveOperands[i].offset();
1719
1720     // The compiler thread will read this pointer value and then proceed to dereference it
1721     // if it is not null. We need to make sure all above stores happen before this store so
1722     // the compiler thread reads fully initialized data.
1723     WTF::storeStoreFence(); 
1724
1725     m_instructions[bytecodeOffset + 3].u.pointer = profiles.get();
1726
1727     {
1728         ConcurrentJSLocker locker(m_lock);
1729         m_catchProfiles.append(WTFMove(profiles));
1730     }
1731 }
1732
1733 void CodeBlock::removeExceptionHandlerForCallSite(CallSiteIndex callSiteIndex)
1734 {
1735     RELEASE_ASSERT(m_rareData);
1736     Vector<HandlerInfo>& exceptionHandlers = m_rareData->m_exceptionHandlers;
1737     unsigned index = callSiteIndex.bits();
1738     for (size_t i = 0; i < exceptionHandlers.size(); ++i) {
1739         HandlerInfo& handler = exceptionHandlers[i];
1740         if (handler.start <= index && handler.end > index) {
1741             exceptionHandlers.remove(i);
1742             return;
1743         }
1744     }
1745
1746     RELEASE_ASSERT_NOT_REACHED();
1747 }
1748
1749 unsigned CodeBlock::lineNumberForBytecodeOffset(unsigned bytecodeOffset)
1750 {
1751     RELEASE_ASSERT(bytecodeOffset < instructions().size());
1752     return ownerScriptExecutable()->firstLine() + m_unlinkedCode->lineNumberForBytecodeOffset(bytecodeOffset);
1753 }
1754
1755 unsigned CodeBlock::columnNumberForBytecodeOffset(unsigned bytecodeOffset)
1756 {
1757     int divot;
1758     int startOffset;
1759     int endOffset;
1760     unsigned line;
1761     unsigned column;
1762     expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
1763     return column;
1764 }
1765
1766 void CodeBlock::expressionRangeForBytecodeOffset(unsigned bytecodeOffset, int& divot, int& startOffset, int& endOffset, unsigned& line, unsigned& column) const
1767 {
1768     m_unlinkedCode->expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
1769     divot += m_sourceOffset;
1770     column += line ? 1 : firstLineColumnOffset();
1771     line += ownerScriptExecutable()->firstLine();
1772 }
1773
1774 bool CodeBlock::hasOpDebugForLineAndColumn(unsigned line, unsigned column)
1775 {
1776     const Instruction* begin = instructions().begin();
1777     const Instruction* end = instructions().end();
1778     for (const Instruction* it = begin; it != end;) {
1779         OpcodeID opcodeID = Interpreter::getOpcodeID(*it);
1780         if (opcodeID == op_debug) {
1781             unsigned bytecodeOffset = it - begin;
1782             int unused;
1783             unsigned opDebugLine;
1784             unsigned opDebugColumn;
1785             expressionRangeForBytecodeOffset(bytecodeOffset, unused, unused, unused, opDebugLine, opDebugColumn);
1786             if (line == opDebugLine && (column == Breakpoint::unspecifiedColumn || column == opDebugColumn))
1787                 return true;
1788         }
1789         it += opcodeLengths[opcodeID];
1790     }
1791     return false;
1792 }
1793
1794 void CodeBlock::shrinkToFit(ShrinkMode shrinkMode)
1795 {
1796     ConcurrentJSLocker locker(m_lock);
1797
1798     m_rareCaseProfiles.shrinkToFit();
1799     
1800     if (shrinkMode == EarlyShrink) {
1801         m_constantRegisters.shrinkToFit();
1802         m_constantsSourceCodeRepresentation.shrinkToFit();
1803         
1804         if (m_rareData) {
1805             m_rareData->m_switchJumpTables.shrinkToFit();
1806             m_rareData->m_stringSwitchJumpTables.shrinkToFit();
1807         }
1808     } // else don't shrink these, because we would have already pointed pointers into these tables.
1809 }
1810
1811 #if ENABLE(JIT)
1812 void CodeBlock::linkIncomingCall(ExecState* callerFrame, CallLinkInfo* incoming)
1813 {
1814     noticeIncomingCall(callerFrame);
1815     m_incomingCalls.push(incoming);
1816 }
1817
1818 void CodeBlock::linkIncomingPolymorphicCall(ExecState* callerFrame, PolymorphicCallNode* incoming)
1819 {
1820     noticeIncomingCall(callerFrame);
1821     m_incomingPolymorphicCalls.push(incoming);
1822 }
1823 #endif // ENABLE(JIT)
1824
1825 void CodeBlock::unlinkIncomingCalls()
1826 {
1827     while (m_incomingLLIntCalls.begin() != m_incomingLLIntCalls.end())
1828         m_incomingLLIntCalls.begin()->unlink();
1829 #if ENABLE(JIT)
1830     while (m_incomingCalls.begin() != m_incomingCalls.end())
1831         m_incomingCalls.begin()->unlink(*vm());
1832     while (m_incomingPolymorphicCalls.begin() != m_incomingPolymorphicCalls.end())
1833         m_incomingPolymorphicCalls.begin()->unlink(*vm());
1834 #endif // ENABLE(JIT)
1835 }
1836
1837 void CodeBlock::linkIncomingCall(ExecState* callerFrame, LLIntCallLinkInfo* incoming)
1838 {
1839     noticeIncomingCall(callerFrame);
1840     m_incomingLLIntCalls.push(incoming);
1841 }
1842
1843 CodeBlock* CodeBlock::newReplacement()
1844 {
1845     return ownerScriptExecutable()->newReplacementCodeBlockFor(specializationKind());
1846 }
1847
1848 #if ENABLE(JIT)
1849 CodeBlock* CodeBlock::replacement()
1850 {
1851     const ClassInfo* classInfo = this->classInfo(*vm());
1852
1853     if (classInfo == FunctionCodeBlock::info())
1854         return jsCast<FunctionExecutable*>(ownerExecutable())->codeBlockFor(m_isConstructor ? CodeForConstruct : CodeForCall);
1855
1856     if (classInfo == EvalCodeBlock::info())
1857         return jsCast<EvalExecutable*>(ownerExecutable())->codeBlock();
1858
1859     if (classInfo == ProgramCodeBlock::info())
1860         return jsCast<ProgramExecutable*>(ownerExecutable())->codeBlock();
1861
1862     if (classInfo == ModuleProgramCodeBlock::info())
1863         return jsCast<ModuleProgramExecutable*>(ownerExecutable())->codeBlock();
1864
1865     RELEASE_ASSERT_NOT_REACHED();
1866     return nullptr;
1867 }
1868
1869 DFG::CapabilityLevel CodeBlock::computeCapabilityLevel()
1870 {
1871     const ClassInfo* classInfo = this->classInfo(*vm());
1872
1873     if (classInfo == FunctionCodeBlock::info()) {
1874         if (m_isConstructor)
1875             return DFG::functionForConstructCapabilityLevel(this);
1876         return DFG::functionForCallCapabilityLevel(this);
1877     }
1878
1879     if (classInfo == EvalCodeBlock::info())
1880         return DFG::evalCapabilityLevel(this);
1881
1882     if (classInfo == ProgramCodeBlock::info())
1883         return DFG::programCapabilityLevel(this);
1884
1885     if (classInfo == ModuleProgramCodeBlock::info())
1886         return DFG::programCapabilityLevel(this);
1887
1888     RELEASE_ASSERT_NOT_REACHED();
1889     return DFG::CannotCompile;
1890 }
1891
1892 #endif // ENABLE(JIT)
1893
1894 void CodeBlock::jettison(Profiler::JettisonReason reason, ReoptimizationMode mode, const FireDetail* detail)
1895 {
1896 #if !ENABLE(DFG_JIT)
1897     UNUSED_PARAM(mode);
1898     UNUSED_PARAM(detail);
1899 #endif
1900     
1901     CODEBLOCK_LOG_EVENT(this, "jettison", ("due to ", reason, ", counting = ", mode == CountReoptimization, ", detail = ", pointerDump(detail)));
1902
1903     RELEASE_ASSERT(reason != Profiler::NotJettisoned);
1904     
1905 #if ENABLE(DFG_JIT)
1906     if (DFG::shouldDumpDisassembly()) {
1907         dataLog("Jettisoning ", *this);
1908         if (mode == CountReoptimization)
1909             dataLog(" and counting reoptimization");
1910         dataLog(" due to ", reason);
1911         if (detail)
1912             dataLog(", ", *detail);
1913         dataLog(".\n");
1914     }
1915     
1916     if (reason == Profiler::JettisonDueToWeakReference) {
1917         if (DFG::shouldDumpDisassembly()) {
1918             dataLog(*this, " will be jettisoned because of the following dead references:\n");
1919             DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
1920             for (auto& transition : dfgCommon->transitions) {
1921                 JSCell* origin = transition.m_codeOrigin.get();
1922                 JSCell* from = transition.m_from.get();
1923                 JSCell* to = transition.m_to.get();
1924                 if ((!origin || Heap::isMarked(origin)) && Heap::isMarked(from))
1925                     continue;
1926                 dataLog("    Transition under ", RawPointer(origin), ", ", RawPointer(from), " -> ", RawPointer(to), ".\n");
1927             }
1928             for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
1929                 JSCell* weak = dfgCommon->weakReferences[i].get();
1930                 if (Heap::isMarked(weak))
1931                     continue;
1932                 dataLog("    Weak reference ", RawPointer(weak), ".\n");
1933             }
1934         }
1935     }
1936 #endif // ENABLE(DFG_JIT)
1937
1938     VM& vm = *m_poisonedVM;
1939     DeferGCForAWhile deferGC(*heap());
1940     
1941     // We want to accomplish two things here:
1942     // 1) Make sure that if this CodeBlock is on the stack right now, then if we return to it
1943     //    we should OSR exit at the top of the next bytecode instruction after the return.
1944     // 2) Make sure that if we call the owner executable, then we shouldn't call this CodeBlock.
1945
1946 #if ENABLE(DFG_JIT)
1947     if (reason != Profiler::JettisonDueToOldAge) {
1948         Profiler::Compilation* compilation = jitCode()->dfgCommon()->compilation.get();
1949         if (UNLIKELY(compilation))
1950             compilation->setJettisonReason(reason, detail);
1951         
1952         // This accomplishes (1), and does its own book-keeping about whether it has already happened.
1953         if (!jitCode()->dfgCommon()->invalidate()) {
1954             // We've already been invalidated.
1955             RELEASE_ASSERT(this != replacement() || (vm.heap.isCurrentThreadBusy() && !Heap::isMarked(ownerScriptExecutable())));
1956             return;
1957         }
1958     }
1959     
1960     if (DFG::shouldDumpDisassembly())
1961         dataLog("    Did invalidate ", *this, "\n");
1962     
1963     // Count the reoptimization if that's what the user wanted.
1964     if (mode == CountReoptimization) {
1965         // FIXME: Maybe this should call alternative().
1966         // https://bugs.webkit.org/show_bug.cgi?id=123677
1967         baselineAlternative()->countReoptimization();
1968         if (DFG::shouldDumpDisassembly())
1969             dataLog("    Did count reoptimization for ", *this, "\n");
1970     }
1971     
1972     if (this != replacement()) {
1973         // This means that we were never the entrypoint. This can happen for OSR entry code
1974         // blocks.
1975         return;
1976     }
1977
1978     if (alternative())
1979         alternative()->optimizeAfterWarmUp();
1980
1981     if (reason != Profiler::JettisonDueToOldAge && reason != Profiler::JettisonDueToVMTraps)
1982         tallyFrequentExitSites();
1983 #endif // ENABLE(DFG_JIT)
1984
1985     // Jettison can happen during GC. We don't want to install code to a dead executable
1986     // because that would add a dead object to the remembered set.
1987     if (vm.heap.isCurrentThreadBusy() && !Heap::isMarked(ownerScriptExecutable()))
1988         return;
1989
1990     // This accomplishes (2).
1991     ownerScriptExecutable()->installCode(vm, alternative(), codeType(), specializationKind());
1992
1993 #if ENABLE(DFG_JIT)
1994     if (DFG::shouldDumpDisassembly())
1995         dataLog("    Did install baseline version of ", *this, "\n");
1996 #endif // ENABLE(DFG_JIT)
1997 }
1998
1999 JSGlobalObject* CodeBlock::globalObjectFor(CodeOrigin codeOrigin)
2000 {
2001     if (!codeOrigin.inlineCallFrame)
2002         return globalObject();
2003     return codeOrigin.inlineCallFrame->baselineCodeBlock->globalObject();
2004 }
2005
2006 class RecursionCheckFunctor {
2007 public:
2008     RecursionCheckFunctor(CallFrame* startCallFrame, CodeBlock* codeBlock, unsigned depthToCheck)
2009         : m_startCallFrame(startCallFrame)
2010         , m_codeBlock(codeBlock)
2011         , m_depthToCheck(depthToCheck)
2012         , m_foundStartCallFrame(false)
2013         , m_didRecurse(false)
2014     { }
2015
2016     StackVisitor::Status operator()(StackVisitor& visitor) const
2017     {
2018         CallFrame* currentCallFrame = visitor->callFrame();
2019
2020         if (currentCallFrame == m_startCallFrame)
2021             m_foundStartCallFrame = true;
2022
2023         if (m_foundStartCallFrame) {
2024             if (visitor->callFrame()->codeBlock() == m_codeBlock) {
2025                 m_didRecurse = true;
2026                 return StackVisitor::Done;
2027             }
2028
2029             if (!m_depthToCheck--)
2030                 return StackVisitor::Done;
2031         }
2032
2033         return StackVisitor::Continue;
2034     }
2035
2036     bool didRecurse() const { return m_didRecurse; }
2037
2038 private:
2039     CallFrame* m_startCallFrame;
2040     CodeBlock* m_codeBlock;
2041     mutable unsigned m_depthToCheck;
2042     mutable bool m_foundStartCallFrame;
2043     mutable bool m_didRecurse;
2044 };
2045
2046 void CodeBlock::noticeIncomingCall(ExecState* callerFrame)
2047 {
2048     CodeBlock* callerCodeBlock = callerFrame->codeBlock();
2049     
2050     if (Options::verboseCallLink())
2051         dataLog("Noticing call link from ", pointerDump(callerCodeBlock), " to ", *this, "\n");
2052     
2053 #if ENABLE(DFG_JIT)
2054     if (!m_shouldAlwaysBeInlined)
2055         return;
2056     
2057     if (!callerCodeBlock) {
2058         m_shouldAlwaysBeInlined = false;
2059         if (Options::verboseCallLink())
2060             dataLog("    Clearing SABI because caller is native.\n");
2061         return;
2062     }
2063
2064     if (!hasBaselineJITProfiling())
2065         return;
2066
2067     if (!DFG::mightInlineFunction(this))
2068         return;
2069
2070     if (!canInline(capabilityLevelState()))
2071         return;
2072     
2073     if (!DFG::isSmallEnoughToInlineCodeInto(callerCodeBlock)) {
2074         m_shouldAlwaysBeInlined = false;
2075         if (Options::verboseCallLink())
2076             dataLog("    Clearing SABI because caller is too large.\n");
2077         return;
2078     }
2079
2080     if (callerCodeBlock->jitType() == JITCode::InterpreterThunk) {
2081         // If the caller is still in the interpreter, then we can't expect inlining to
2082         // happen anytime soon. Assume it's profitable to optimize it separately. This
2083         // ensures that a function is SABI only if it is called no more frequently than
2084         // any of its callers.
2085         m_shouldAlwaysBeInlined = false;
2086         if (Options::verboseCallLink())
2087             dataLog("    Clearing SABI because caller is in LLInt.\n");
2088         return;
2089     }
2090     
2091     if (JITCode::isOptimizingJIT(callerCodeBlock->jitType())) {
2092         m_shouldAlwaysBeInlined = false;
2093         if (Options::verboseCallLink())
2094             dataLog("    Clearing SABI bcause caller was already optimized.\n");
2095         return;
2096     }
2097     
2098     if (callerCodeBlock->codeType() != FunctionCode) {
2099         // If the caller is either eval or global code, assume that that won't be
2100         // optimized anytime soon. For eval code this is particularly true since we
2101         // delay eval optimization by a *lot*.
2102         m_shouldAlwaysBeInlined = false;
2103         if (Options::verboseCallLink())
2104             dataLog("    Clearing SABI because caller is not a function.\n");
2105         return;
2106     }
2107
2108     // Recursive calls won't be inlined.
2109     RecursionCheckFunctor functor(callerFrame, this, Options::maximumInliningDepth());
2110     vm()->topCallFrame->iterate(functor);
2111
2112     if (functor.didRecurse()) {
2113         if (Options::verboseCallLink())
2114             dataLog("    Clearing SABI because recursion was detected.\n");
2115         m_shouldAlwaysBeInlined = false;
2116         return;
2117     }
2118     
2119     if (callerCodeBlock->capabilityLevelState() == DFG::CapabilityLevelNotSet) {
2120         dataLog("In call from ", FullCodeOrigin(callerCodeBlock, callerFrame->codeOrigin()), " to ", *this, ": caller's DFG capability level is not set.\n");
2121         CRASH();
2122     }
2123     
2124     if (canCompile(callerCodeBlock->capabilityLevelState()))
2125         return;
2126     
2127     if (Options::verboseCallLink())
2128         dataLog("    Clearing SABI because the caller is not a DFG candidate.\n");
2129     
2130     m_shouldAlwaysBeInlined = false;
2131 #endif
2132 }
2133
2134 unsigned CodeBlock::reoptimizationRetryCounter() const
2135 {
2136 #if ENABLE(JIT)
2137     ASSERT(m_reoptimizationRetryCounter <= Options::reoptimizationRetryCounterMax());
2138     return m_reoptimizationRetryCounter;
2139 #else
2140     return 0;
2141 #endif // ENABLE(JIT)
2142 }
2143
2144 #if ENABLE(JIT)
2145 void CodeBlock::setCalleeSaveRegisters(RegisterSet calleeSaveRegisters)
2146 {
2147     m_calleeSaveRegisters = std::make_unique<RegisterAtOffsetList>(calleeSaveRegisters);
2148 }
2149
2150 void CodeBlock::setCalleeSaveRegisters(std::unique_ptr<RegisterAtOffsetList> registerAtOffsetList)
2151 {
2152     m_calleeSaveRegisters = WTFMove(registerAtOffsetList);
2153 }
2154     
2155 static size_t roundCalleeSaveSpaceAsVirtualRegisters(size_t calleeSaveRegisters)
2156 {
2157     static const unsigned cpuRegisterSize = sizeof(void*);
2158     return (WTF::roundUpToMultipleOf(sizeof(Register), calleeSaveRegisters * cpuRegisterSize) / sizeof(Register));
2159
2160 }
2161
2162 size_t CodeBlock::llintBaselineCalleeSaveSpaceAsVirtualRegisters()
2163 {
2164     return roundCalleeSaveSpaceAsVirtualRegisters(numberOfLLIntBaselineCalleeSaveRegisters());
2165 }
2166
2167 size_t CodeBlock::calleeSaveSpaceAsVirtualRegisters()
2168 {
2169     return roundCalleeSaveSpaceAsVirtualRegisters(m_calleeSaveRegisters->size());
2170 }
2171
2172 void CodeBlock::countReoptimization()
2173 {
2174     m_reoptimizationRetryCounter++;
2175     if (m_reoptimizationRetryCounter > Options::reoptimizationRetryCounterMax())
2176         m_reoptimizationRetryCounter = Options::reoptimizationRetryCounterMax();
2177 }
2178
2179 unsigned CodeBlock::numberOfDFGCompiles()
2180 {
2181     ASSERT(JITCode::isBaselineCode(jitType()));
2182     if (Options::testTheFTL()) {
2183         if (m_didFailFTLCompilation)
2184             return 1000000;
2185         return (m_hasBeenCompiledWithFTL ? 1 : 0) + m_reoptimizationRetryCounter;
2186     }
2187     CodeBlock* replacement = this->replacement();
2188     return ((replacement && JITCode::isOptimizingJIT(replacement->jitType())) ? 1 : 0) + m_reoptimizationRetryCounter;
2189 }
2190
2191 int32_t CodeBlock::codeTypeThresholdMultiplier() const
2192 {
2193     if (codeType() == EvalCode)
2194         return Options::evalThresholdMultiplier();
2195     
2196     return 1;
2197 }
2198
2199 double CodeBlock::optimizationThresholdScalingFactor()
2200 {
2201     // This expression arises from doing a least-squares fit of
2202     //
2203     // F[x_] =: a * Sqrt[x + b] + Abs[c * x] + d
2204     //
2205     // against the data points:
2206     //
2207     //    x       F[x_]
2208     //    10       0.9          (smallest reasonable code block)
2209     //   200       1.0          (typical small-ish code block)
2210     //   320       1.2          (something I saw in 3d-cube that I wanted to optimize)
2211     //  1268       5.0          (something I saw in 3d-cube that I didn't want to optimize)
2212     //  4000       5.5          (random large size, used to cause the function to converge to a shallow curve of some sort)
2213     // 10000       6.0          (similar to above)
2214     //
2215     // I achieve the minimization using the following Mathematica code:
2216     //
2217     // MyFunctionTemplate[x_, a_, b_, c_, d_] := a*Sqrt[x + b] + Abs[c*x] + d
2218     //
2219     // samples = {{10, 0.9}, {200, 1}, {320, 1.2}, {1268, 5}, {4000, 5.5}, {10000, 6}}
2220     //
2221     // solution = 
2222     //     Minimize[Plus @@ ((MyFunctionTemplate[#[[1]], a, b, c, d] - #[[2]])^2 & /@ samples),
2223     //         {a, b, c, d}][[2]]
2224     //
2225     // And the code below (to initialize a, b, c, d) is generated by:
2226     //
2227     // Print["const double " <> ToString[#[[1]]] <> " = " <>
2228     //     If[#[[2]] < 0.00001, "0.0", ToString[#[[2]]]] <> ";"] & /@ solution
2229     //
2230     // We've long known the following to be true:
2231     // - Small code blocks are cheap to optimize and so we should do it sooner rather
2232     //   than later.
2233     // - Large code blocks are expensive to optimize and so we should postpone doing so,
2234     //   and sometimes have a large enough threshold that we never optimize them.
2235     // - The difference in cost is not totally linear because (a) just invoking the
2236     //   DFG incurs some base cost and (b) for large code blocks there is enough slop
2237     //   in the correlation between instruction count and the actual compilation cost
2238     //   that for those large blocks, the instruction count should not have a strong
2239     //   influence on our threshold.
2240     //
2241     // I knew the goals but I didn't know how to achieve them; so I picked an interesting
2242     // example where the heuristics were right (code block in 3d-cube with instruction
2243     // count 320, which got compiled early as it should have been) and one where they were
2244     // totally wrong (code block in 3d-cube with instruction count 1268, which was expensive
2245     // to compile and didn't run often enough to warrant compilation in my opinion), and
2246     // then threw in additional data points that represented my own guess of what our
2247     // heuristics should do for some round-numbered examples.
2248     //
2249     // The expression to which I decided to fit the data arose because I started with an
2250     // affine function, and then did two things: put the linear part in an Abs to ensure
2251     // that the fit didn't end up choosing a negative value of c (which would result in
2252     // the function turning over and going negative for large x) and I threw in a Sqrt
2253     // term because Sqrt represents my intution that the function should be more sensitive
2254     // to small changes in small values of x, but less sensitive when x gets large.
2255     
2256     // Note that the current fit essentially eliminates the linear portion of the
2257     // expression (c == 0.0).
2258     const double a = 0.061504;
2259     const double b = 1.02406;
2260     const double c = 0.0;
2261     const double d = 0.825914;
2262     
2263     double instructionCount = this->instructionCount();
2264     
2265     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.
2266     
2267     double result = d + a * sqrt(instructionCount + b) + c * instructionCount;
2268     
2269     result *= codeTypeThresholdMultiplier();
2270     
2271     if (Options::verboseOSR()) {
2272         dataLog(
2273             *this, ": instruction count is ", instructionCount,
2274             ", scaling execution counter by ", result, " * ", codeTypeThresholdMultiplier(),
2275             "\n");
2276     }
2277     return result;
2278 }
2279
2280 static int32_t clipThreshold(double threshold)
2281 {
2282     if (threshold < 1.0)
2283         return 1;
2284     
2285     if (threshold > static_cast<double>(std::numeric_limits<int32_t>::max()))
2286         return std::numeric_limits<int32_t>::max();
2287     
2288     return static_cast<int32_t>(threshold);
2289 }
2290
2291 int32_t CodeBlock::adjustedCounterValue(int32_t desiredThreshold)
2292 {
2293     return clipThreshold(
2294         static_cast<double>(desiredThreshold) *
2295         optimizationThresholdScalingFactor() *
2296         (1 << reoptimizationRetryCounter()));
2297 }
2298
2299 bool CodeBlock::checkIfOptimizationThresholdReached()
2300 {
2301 #if ENABLE(DFG_JIT)
2302     if (DFG::Worklist* worklist = DFG::existingGlobalDFGWorklistOrNull()) {
2303         if (worklist->compilationState(DFG::CompilationKey(this, DFG::DFGMode))
2304             == DFG::Worklist::Compiled) {
2305             optimizeNextInvocation();
2306             return true;
2307         }
2308     }
2309 #endif
2310     
2311     return m_jitExecuteCounter.checkIfThresholdCrossedAndSet(this);
2312 }
2313
2314 #if ENABLE(DFG_JIT)
2315 auto CodeBlock::updateOSRExitCounterAndCheckIfNeedToReoptimize(DFG::OSRExitState& exitState) -> OptimizeAction
2316 {
2317     DFG::OSRExitBase& exit = exitState.exit;
2318     if (!exitKindMayJettison(exit.m_kind)) {
2319         // FIXME: We may want to notice that we're frequently exiting
2320         // at an op_catch that we didn't compile an entrypoint for, and
2321         // then trigger a reoptimization of this CodeBlock:
2322         // https://bugs.webkit.org/show_bug.cgi?id=175842
2323         return OptimizeAction::None;
2324     }
2325
2326     exit.m_count++;
2327     m_osrExitCounter++;
2328
2329     CodeBlock* baselineCodeBlock = exitState.baselineCodeBlock;
2330     ASSERT(baselineCodeBlock == baselineAlternative());
2331     if (UNLIKELY(baselineCodeBlock->jitExecuteCounter().hasCrossedThreshold()))
2332         return OptimizeAction::ReoptimizeNow;
2333
2334     // We want to figure out if there's a possibility that we're in a loop. For the outermost
2335     // code block in the inline stack, we handle this appropriately by having the loop OSR trigger
2336     // check the exit count of the replacement of the CodeBlock from which we are OSRing. The
2337     // problem is the inlined functions, which might also have loops, but whose baseline versions
2338     // don't know where to look for the exit count. Figure out if those loops are severe enough
2339     // that we had tried to OSR enter. If so, then we should use the loop reoptimization trigger.
2340     // Otherwise, we should use the normal reoptimization trigger.
2341
2342     bool didTryToEnterInLoop = false;
2343     for (InlineCallFrame* inlineCallFrame = exit.m_codeOrigin.inlineCallFrame; inlineCallFrame; inlineCallFrame = inlineCallFrame->directCaller.inlineCallFrame) {
2344         if (inlineCallFrame->baselineCodeBlock->ownerScriptExecutable()->didTryToEnterInLoop()) {
2345             didTryToEnterInLoop = true;
2346             break;
2347         }
2348     }
2349
2350     uint32_t exitCountThreshold = didTryToEnterInLoop
2351         ? exitCountThresholdForReoptimizationFromLoop()
2352         : exitCountThresholdForReoptimization();
2353
2354     if (m_osrExitCounter > exitCountThreshold)
2355         return OptimizeAction::ReoptimizeNow;
2356
2357     // Too few fails. Adjust the execution counter such that the target is to only optimize after a while.
2358     baselineCodeBlock->m_jitExecuteCounter.setNewThresholdForOSRExit(exitState.activeThreshold, exitState.memoryUsageAdjustedThreshold);
2359     return OptimizeAction::None;
2360 }
2361 #endif
2362
2363 void CodeBlock::optimizeNextInvocation()
2364 {
2365     if (Options::verboseOSR())
2366         dataLog(*this, ": Optimizing next invocation.\n");
2367     m_jitExecuteCounter.setNewThreshold(0, this);
2368 }
2369
2370 void CodeBlock::dontOptimizeAnytimeSoon()
2371 {
2372     if (Options::verboseOSR())
2373         dataLog(*this, ": Not optimizing anytime soon.\n");
2374     m_jitExecuteCounter.deferIndefinitely();
2375 }
2376
2377 void CodeBlock::optimizeAfterWarmUp()
2378 {
2379     if (Options::verboseOSR())
2380         dataLog(*this, ": Optimizing after warm-up.\n");
2381 #if ENABLE(DFG_JIT)
2382     m_jitExecuteCounter.setNewThreshold(
2383         adjustedCounterValue(Options::thresholdForOptimizeAfterWarmUp()), this);
2384 #endif
2385 }
2386
2387 void CodeBlock::optimizeAfterLongWarmUp()
2388 {
2389     if (Options::verboseOSR())
2390         dataLog(*this, ": Optimizing after long warm-up.\n");
2391 #if ENABLE(DFG_JIT)
2392     m_jitExecuteCounter.setNewThreshold(
2393         adjustedCounterValue(Options::thresholdForOptimizeAfterLongWarmUp()), this);
2394 #endif
2395 }
2396
2397 void CodeBlock::optimizeSoon()
2398 {
2399     if (Options::verboseOSR())
2400         dataLog(*this, ": Optimizing soon.\n");
2401 #if ENABLE(DFG_JIT)
2402     m_jitExecuteCounter.setNewThreshold(
2403         adjustedCounterValue(Options::thresholdForOptimizeSoon()), this);
2404 #endif
2405 }
2406
2407 void CodeBlock::forceOptimizationSlowPathConcurrently()
2408 {
2409     if (Options::verboseOSR())
2410         dataLog(*this, ": Forcing slow path concurrently.\n");
2411     m_jitExecuteCounter.forceSlowPathConcurrently();
2412 }
2413
2414 #if ENABLE(DFG_JIT)
2415 void CodeBlock::setOptimizationThresholdBasedOnCompilationResult(CompilationResult result)
2416 {
2417     JITCode::JITType type = jitType();
2418     if (type != JITCode::BaselineJIT) {
2419         dataLog(*this, ": expected to have baseline code but have ", type, "\n");
2420         RELEASE_ASSERT_NOT_REACHED();
2421     }
2422     
2423     CodeBlock* replacement = this->replacement();
2424     bool hasReplacement = (replacement && replacement != this);
2425     if ((result == CompilationSuccessful) != hasReplacement) {
2426         dataLog(*this, ": we have result = ", result, " but ");
2427         if (replacement == this)
2428             dataLog("we are our own replacement.\n");
2429         else
2430             dataLog("our replacement is ", pointerDump(replacement), "\n");
2431         RELEASE_ASSERT_NOT_REACHED();
2432     }
2433     
2434     switch (result) {
2435     case CompilationSuccessful:
2436         RELEASE_ASSERT(replacement && 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