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