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