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