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