42060067229aa40ab47e9b40529621fe82edb34d
[WebKit-https.git] / Source / JavaScriptCore / runtime / Executable.cpp
1 /*
2  * Copyright (C) 2009, 2010, 2013, 2015 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25
26 #include "config.h"
27 #include "Executable.h"
28
29 #include "BatchedTransitionOptimizer.h"
30 #include "CodeBlock.h"
31 #include "DFGDriver.h"
32 #include "JIT.h"
33 #include "JSCInlines.h"
34 #include "JSWASMModule.h"
35 #include "LLIntEntrypoint.h"
36 #include "Parser.h"
37 #include "ProfilerDatabase.h"
38 #include "TypeProfiler.h"
39 #include "WASMFunctionParser.h"
40 #include <wtf/CommaPrinter.h>
41 #include <wtf/Vector.h>
42 #include <wtf/text/StringBuilder.h>
43
44 namespace JSC {
45
46 const ClassInfo ExecutableBase::s_info = { "Executable", 0, 0, CREATE_METHOD_TABLE(ExecutableBase) };
47
48 void ExecutableBase::destroy(JSCell* cell)
49 {
50     static_cast<ExecutableBase*>(cell)->ExecutableBase::~ExecutableBase();
51 }
52
53 void ExecutableBase::clearCode()
54 {
55 #if ENABLE(JIT)
56     m_jitCodeForCall = nullptr;
57     m_jitCodeForConstruct = nullptr;
58     m_jitCodeForCallWithArityCheck = MacroAssemblerCodePtr();
59     m_jitCodeForConstructWithArityCheck = MacroAssemblerCodePtr();
60 #endif
61     m_numParametersForCall = NUM_PARAMETERS_NOT_COMPILED;
62     m_numParametersForConstruct = NUM_PARAMETERS_NOT_COMPILED;
63
64     if (classInfo() == FunctionExecutable::info()) {
65         FunctionExecutable* executable = jsCast<FunctionExecutable*>(this);
66         executable->m_codeBlockForCall.clear();
67         executable->m_codeBlockForConstruct.clear();
68         return;
69     }
70
71     if (classInfo() == EvalExecutable::info()) {
72         EvalExecutable* executable = jsCast<EvalExecutable*>(this);
73         executable->m_evalCodeBlock.clear();
74         executable->m_unlinkedEvalCodeBlock.clear();
75         return;
76     }
77     
78     if (classInfo() == ProgramExecutable::info()) {
79         ProgramExecutable* executable = jsCast<ProgramExecutable*>(this);
80         executable->m_programCodeBlock.clear();
81         executable->m_unlinkedProgramCodeBlock.clear();
82         return;
83     }
84
85     if (classInfo() == ModuleProgramExecutable::info()) {
86         ModuleProgramExecutable* executable = jsCast<ModuleProgramExecutable*>(this);
87         executable->m_moduleProgramCodeBlock.clear();
88         executable->m_unlinkedModuleProgramCodeBlock.clear();
89         executable->m_moduleEnvironmentSymbolTable.clear();
90         return;
91     }
92     
93 #if ENABLE(WEBASSEMBLY)
94     if (classInfo() == WebAssemblyExecutable::info()) {
95         WebAssemblyExecutable* executable = jsCast<WebAssemblyExecutable*>(this);
96         executable->m_codeBlockForCall.clear();
97         return;
98     }
99 #endif
100
101     ASSERT(classInfo() == NativeExecutable::info());
102 }
103
104 #if ENABLE(DFG_JIT)
105 Intrinsic ExecutableBase::intrinsic() const
106 {
107     if (const NativeExecutable* nativeExecutable = jsDynamicCast<const NativeExecutable*>(this))
108         return nativeExecutable->intrinsic();
109     return NoIntrinsic;
110 }
111 #else
112 Intrinsic ExecutableBase::intrinsic() const
113 {
114     return NoIntrinsic;
115 }
116 #endif
117
118 const ClassInfo NativeExecutable::s_info = { "NativeExecutable", &ExecutableBase::s_info, 0, CREATE_METHOD_TABLE(NativeExecutable) };
119
120 void NativeExecutable::destroy(JSCell* cell)
121 {
122     static_cast<NativeExecutable*>(cell)->NativeExecutable::~NativeExecutable();
123 }
124
125 #if ENABLE(DFG_JIT)
126 Intrinsic NativeExecutable::intrinsic() const
127 {
128     return m_intrinsic;
129 }
130 #endif
131
132 const ClassInfo ScriptExecutable::s_info = { "ScriptExecutable", &ExecutableBase::s_info, 0, CREATE_METHOD_TABLE(ScriptExecutable) };
133
134 ScriptExecutable::ScriptExecutable(Structure* structure, VM& vm, const SourceCode& source, bool isInStrictContext)
135     : ExecutableBase(vm, structure, NUM_PARAMETERS_NOT_COMPILED)
136     , m_source(source)
137     , m_features(isInStrictContext ? StrictModeFeature : 0)
138     , m_hasCapturedVariables(false)
139     , m_neverInline(false)
140     , m_didTryToEnterInLoop(false)
141     , m_overrideLineNumber(-1)
142     , m_firstLine(-1)
143     , m_lastLine(-1)
144     , m_startColumn(UINT_MAX)
145     , m_endColumn(UINT_MAX)
146     , m_typeProfilingStartOffset(UINT_MAX)
147     , m_typeProfilingEndOffset(UINT_MAX)
148 {
149 }
150
151 void ScriptExecutable::destroy(JSCell* cell)
152 {
153     static_cast<ScriptExecutable*>(cell)->ScriptExecutable::~ScriptExecutable();
154 }
155
156 void ScriptExecutable::installCode(CodeBlock* codeBlock)
157 {
158     installCode(*codeBlock->vm(), codeBlock, codeBlock->codeType(), codeBlock->specializationKind());
159 }
160
161 void ScriptExecutable::installCode(VM& vm, CodeBlock* genericCodeBlock, CodeType codeType, CodeSpecializationKind kind)
162 {
163     ASSERT(vm.heap.isDeferred());
164     
165     CodeBlock* oldCodeBlock = nullptr;
166     
167     switch (codeType) {
168     case GlobalCode: {
169         ProgramExecutable* executable = jsCast<ProgramExecutable*>(this);
170         ProgramCodeBlock* codeBlock = static_cast<ProgramCodeBlock*>(genericCodeBlock);
171         
172         ASSERT(kind == CodeForCall);
173         
174         oldCodeBlock = executable->m_programCodeBlock.get();
175         executable->m_programCodeBlock.setMayBeNull(vm, this, codeBlock);
176         break;
177     }
178
179     case ModuleCode: {
180         ModuleProgramExecutable* executable = jsCast<ModuleProgramExecutable*>(this);
181         ModuleProgramCodeBlock* codeBlock = static_cast<ModuleProgramCodeBlock*>(genericCodeBlock);
182
183         ASSERT(kind == CodeForCall);
184
185         oldCodeBlock = executable->m_moduleProgramCodeBlock.get();
186         executable->m_moduleProgramCodeBlock.setMayBeNull(vm, this, codeBlock);
187         break;
188     }
189
190     case EvalCode: {
191         EvalExecutable* executable = jsCast<EvalExecutable*>(this);
192         EvalCodeBlock* codeBlock = static_cast<EvalCodeBlock*>(genericCodeBlock);
193         
194         ASSERT(kind == CodeForCall);
195         
196         oldCodeBlock = executable->m_evalCodeBlock.get();
197         executable->m_evalCodeBlock.setMayBeNull(vm, this, codeBlock);
198         break;
199     }
200         
201     case FunctionCode: {
202         FunctionExecutable* executable = jsCast<FunctionExecutable*>(this);
203         FunctionCodeBlock* codeBlock = static_cast<FunctionCodeBlock*>(genericCodeBlock);
204         
205         switch (kind) {
206         case CodeForCall:
207             oldCodeBlock = executable->m_codeBlockForCall.get();
208             executable->m_codeBlockForCall.setMayBeNull(vm, this, codeBlock);
209             break;
210         case CodeForConstruct:
211             oldCodeBlock = executable->m_codeBlockForConstruct.get();
212             executable->m_codeBlockForConstruct.setMayBeNull(vm, this, codeBlock);
213             break;
214         }
215         break;
216     }
217     }
218
219     switch (kind) {
220     case CodeForCall:
221         m_jitCodeForCall = genericCodeBlock ? genericCodeBlock->jitCode() : nullptr;
222         m_jitCodeForCallWithArityCheck = MacroAssemblerCodePtr();
223         m_numParametersForCall = genericCodeBlock ? genericCodeBlock->numParameters() : NUM_PARAMETERS_NOT_COMPILED;
224         break;
225     case CodeForConstruct:
226         m_jitCodeForConstruct = genericCodeBlock ? genericCodeBlock->jitCode() : nullptr;
227         m_jitCodeForConstructWithArityCheck = MacroAssemblerCodePtr();
228         m_numParametersForConstruct = genericCodeBlock ? genericCodeBlock->numParameters() : NUM_PARAMETERS_NOT_COMPILED;
229         break;
230     }
231
232     if (genericCodeBlock) {
233         RELEASE_ASSERT(genericCodeBlock->ownerExecutable() == this);
234         RELEASE_ASSERT(JITCode::isExecutableScript(genericCodeBlock->jitType()));
235         
236         if (Options::verboseOSR())
237             dataLog("Installing ", *genericCodeBlock, "\n");
238         
239         if (vm.m_perBytecodeProfiler)
240             vm.m_perBytecodeProfiler->ensureBytecodesFor(genericCodeBlock);
241         
242         if (Debugger* debugger = genericCodeBlock->globalObject()->debugger())
243             debugger->registerCodeBlock(genericCodeBlock);
244     }
245
246     if (oldCodeBlock)
247         oldCodeBlock->unlinkIncomingCalls();
248
249     vm.heap.writeBarrier(this);
250 }
251
252 CodeBlock* ScriptExecutable::newCodeBlockFor(
253     CodeSpecializationKind kind, JSFunction* function, JSScope* scope, JSObject*& exception)
254 {
255     VM* vm = scope->vm();
256
257     ASSERT(vm->heap.isDeferred());
258     ASSERT(startColumn() != UINT_MAX);
259     ASSERT(endColumn() != UINT_MAX);
260
261     if (classInfo() == EvalExecutable::info()) {
262         EvalExecutable* executable = jsCast<EvalExecutable*>(this);
263         RELEASE_ASSERT(kind == CodeForCall);
264         RELEASE_ASSERT(!executable->m_evalCodeBlock);
265         RELEASE_ASSERT(!function);
266         return EvalCodeBlock::create(vm,
267             executable, executable->m_unlinkedEvalCodeBlock.get(), scope,
268             executable->source().provider());
269     }
270     
271     if (classInfo() == ProgramExecutable::info()) {
272         ProgramExecutable* executable = jsCast<ProgramExecutable*>(this);
273         RELEASE_ASSERT(kind == CodeForCall);
274         RELEASE_ASSERT(!executable->m_programCodeBlock);
275         RELEASE_ASSERT(!function);
276         return ProgramCodeBlock::create(vm,
277             executable, executable->m_unlinkedProgramCodeBlock.get(), scope,
278             executable->source().provider(), executable->source().startColumn());
279     }
280
281     if (classInfo() == ModuleProgramExecutable::info()) {
282         ModuleProgramExecutable* executable = jsCast<ModuleProgramExecutable*>(this);
283         RELEASE_ASSERT(kind == CodeForCall);
284         RELEASE_ASSERT(!executable->m_moduleProgramCodeBlock);
285         RELEASE_ASSERT(!function);
286         return ModuleProgramCodeBlock::create(vm,
287             executable, executable->m_unlinkedModuleProgramCodeBlock.get(), scope,
288             executable->source().provider(), executable->source().startColumn());
289     }
290
291     RELEASE_ASSERT(classInfo() == FunctionExecutable::info());
292     RELEASE_ASSERT(function);
293     FunctionExecutable* executable = jsCast<FunctionExecutable*>(this);
294     RELEASE_ASSERT(!executable->codeBlockFor(kind));
295     JSGlobalObject* globalObject = scope->globalObject();
296     ParserError error;
297     DebuggerMode debuggerMode = globalObject->hasDebugger() ? DebuggerOn : DebuggerOff;
298     ProfilerMode profilerMode = globalObject->hasProfiler() ? ProfilerOn : ProfilerOff;
299     UnlinkedFunctionCodeBlock* unlinkedCodeBlock = 
300         executable->m_unlinkedExecutable->unlinkedCodeBlockFor(
301             *vm, executable->m_source, kind, debuggerMode, profilerMode, error, 
302             executable->parseMode());
303     recordParse(
304         executable->m_unlinkedExecutable->features(), 
305         executable->m_unlinkedExecutable->hasCapturedVariables(), firstLine(), 
306         lastLine(), startColumn(), endColumn()); 
307     if (!unlinkedCodeBlock) {
308         exception = vm->throwException(
309             globalObject->globalExec(),
310             error.toErrorObject(globalObject, executable->m_source));
311         return nullptr;
312     }
313
314     SourceProvider* provider = executable->source().provider();
315     unsigned sourceOffset = executable->source().startOffset();
316     unsigned startColumn = executable->source().startColumn();
317
318     return FunctionCodeBlock::create(vm,
319         executable, unlinkedCodeBlock, scope, provider, sourceOffset, startColumn);
320 }
321
322 CodeBlock* ScriptExecutable::newReplacementCodeBlockFor(
323     CodeSpecializationKind kind)
324 {
325     if (classInfo() == EvalExecutable::info()) {
326         RELEASE_ASSERT(kind == CodeForCall);
327         EvalExecutable* executable = jsCast<EvalExecutable*>(this);
328         EvalCodeBlock* baseline = static_cast<EvalCodeBlock*>(
329             executable->m_evalCodeBlock->baselineVersion());
330         EvalCodeBlock* result = EvalCodeBlock::create(vm(),
331             CodeBlock::CopyParsedBlock, *baseline);
332         result->setAlternative(*vm(), baseline);
333         return result;
334     }
335     
336     if (classInfo() == ProgramExecutable::info()) {
337         RELEASE_ASSERT(kind == CodeForCall);
338         ProgramExecutable* executable = jsCast<ProgramExecutable*>(this);
339         ProgramCodeBlock* baseline = static_cast<ProgramCodeBlock*>(
340             executable->m_programCodeBlock->baselineVersion());
341         ProgramCodeBlock* result = ProgramCodeBlock::create(vm(),
342             CodeBlock::CopyParsedBlock, *baseline);
343         result->setAlternative(*vm(), baseline);
344         return result;
345     }
346
347     if (classInfo() == ModuleProgramExecutable::info()) {
348         RELEASE_ASSERT(kind == CodeForCall);
349         ModuleProgramExecutable* executable = jsCast<ModuleProgramExecutable*>(this);
350         ModuleProgramCodeBlock* baseline = static_cast<ModuleProgramCodeBlock*>(
351             executable->m_moduleProgramCodeBlock->baselineVersion());
352         ModuleProgramCodeBlock* result = ModuleProgramCodeBlock::create(vm(),
353             CodeBlock::CopyParsedBlock, *baseline);
354         result->setAlternative(*vm(), baseline);
355         return result;
356     }
357
358     RELEASE_ASSERT(classInfo() == FunctionExecutable::info());
359     FunctionExecutable* executable = jsCast<FunctionExecutable*>(this);
360     FunctionCodeBlock* baseline = static_cast<FunctionCodeBlock*>(
361         executable->codeBlockFor(kind)->baselineVersion());
362     FunctionCodeBlock* result = FunctionCodeBlock::create(vm(),
363         CodeBlock::CopyParsedBlock, *baseline);
364     result->setAlternative(*vm(), baseline);
365     return result;
366 }
367
368 static void setupLLInt(VM& vm, CodeBlock* codeBlock)
369 {
370     LLInt::setEntrypoint(vm, codeBlock);
371 }
372
373 static void setupJIT(VM& vm, CodeBlock* codeBlock)
374 {
375 #if ENABLE(JIT)
376     CompilationResult result = JIT::compile(&vm, codeBlock, JITCompilationMustSucceed);
377     RELEASE_ASSERT(result == CompilationSuccessful);
378 #else
379     UNUSED_PARAM(vm);
380     UNUSED_PARAM(codeBlock);
381     UNREACHABLE_FOR_PLATFORM();
382 #endif
383 }
384
385 JSObject* ScriptExecutable::prepareForExecutionImpl(
386     ExecState* exec, JSFunction* function, JSScope* scope, CodeSpecializationKind kind)
387 {
388     VM& vm = exec->vm();
389     DeferGC deferGC(vm.heap);
390
391     if (vm.getAndClearFailNextNewCodeBlock())
392         return createError(exec->callerFrame(), ASCIILiteral("Forced Failure"));
393
394     JSObject* exception = 0;
395     CodeBlock* codeBlock = newCodeBlockFor(kind, function, scope, exception);
396     if (!codeBlock) {
397         RELEASE_ASSERT(exception);
398         return exception;
399     }
400     
401     if (Options::validateBytecode())
402         codeBlock->validate();
403     
404     if (Options::useLLInt())
405         setupLLInt(vm, codeBlock);
406     else
407         setupJIT(vm, codeBlock);
408     
409     installCode(*codeBlock->vm(), codeBlock, codeBlock->codeType(), codeBlock->specializationKind());
410     return 0;
411 }
412
413 const ClassInfo EvalExecutable::s_info = { "EvalExecutable", &ScriptExecutable::s_info, 0, CREATE_METHOD_TABLE(EvalExecutable) };
414
415 EvalExecutable* EvalExecutable::create(ExecState* exec, const SourceCode& source, bool isInStrictContext, ThisTDZMode thisTDZMode, const VariableEnvironment* variablesUnderTDZ)
416 {
417     JSGlobalObject* globalObject = exec->lexicalGlobalObject();
418     if (!globalObject->evalEnabled()) {
419         exec->vm().throwException(exec, createEvalError(exec, globalObject->evalDisabledErrorMessage()));
420         return 0;
421     }
422
423     EvalExecutable* executable = new (NotNull, allocateCell<EvalExecutable>(*exec->heap())) EvalExecutable(exec, source, isInStrictContext);
424     executable->finishCreation(exec->vm());
425
426     UnlinkedEvalCodeBlock* unlinkedEvalCode = globalObject->createEvalCodeBlock(exec, executable, thisTDZMode, variablesUnderTDZ);
427     if (!unlinkedEvalCode)
428         return 0;
429
430     executable->m_unlinkedEvalCodeBlock.set(exec->vm(), executable, unlinkedEvalCode);
431
432     return executable;
433 }
434
435 EvalExecutable::EvalExecutable(ExecState* exec, const SourceCode& source, bool inStrictContext)
436     : ScriptExecutable(exec->vm().evalExecutableStructure.get(), exec->vm(), source, inStrictContext)
437 {
438 }
439
440 void EvalExecutable::destroy(JSCell* cell)
441 {
442     static_cast<EvalExecutable*>(cell)->EvalExecutable::~EvalExecutable();
443 }
444
445 const ClassInfo ProgramExecutable::s_info = { "ProgramExecutable", &ScriptExecutable::s_info, 0, CREATE_METHOD_TABLE(ProgramExecutable) };
446
447 ProgramExecutable::ProgramExecutable(ExecState* exec, const SourceCode& source)
448     : ScriptExecutable(exec->vm().programExecutableStructure.get(), exec->vm(), source, false)
449 {
450     m_typeProfilingStartOffset = 0;
451     m_typeProfilingEndOffset = source.length() - 1;
452     if (exec->vm().typeProfiler() || exec->vm().controlFlowProfiler())
453         exec->vm().functionHasExecutedCache()->insertUnexecutedRange(sourceID(), m_typeProfilingStartOffset, m_typeProfilingEndOffset);
454 }
455
456 void ProgramExecutable::destroy(JSCell* cell)
457 {
458     static_cast<ProgramExecutable*>(cell)->ProgramExecutable::~ProgramExecutable();
459 }
460
461 const ClassInfo ModuleProgramExecutable::s_info = { "ModuleProgramExecutable", &ScriptExecutable::s_info, 0, CREATE_METHOD_TABLE(ModuleProgramExecutable) };
462
463 ModuleProgramExecutable::ModuleProgramExecutable(ExecState* exec, const SourceCode& source)
464     : ScriptExecutable(exec->vm().moduleProgramExecutableStructure.get(), exec->vm(), source, false)
465 {
466     m_typeProfilingStartOffset = 0;
467     m_typeProfilingEndOffset = source.length() - 1;
468     if (exec->vm().typeProfiler() || exec->vm().controlFlowProfiler())
469         exec->vm().functionHasExecutedCache()->insertUnexecutedRange(sourceID(), m_typeProfilingStartOffset, m_typeProfilingEndOffset);
470 }
471
472 ModuleProgramExecutable* ModuleProgramExecutable::create(ExecState* exec, const SourceCode& source)
473 {
474     JSGlobalObject* globalObject = exec->lexicalGlobalObject();
475     ModuleProgramExecutable* executable = new (NotNull, allocateCell<ModuleProgramExecutable>(*exec->heap())) ModuleProgramExecutable(exec, source);
476     executable->finishCreation(exec->vm());
477
478     UnlinkedModuleProgramCodeBlock* unlinkedModuleProgramCode = globalObject->createModuleProgramCodeBlock(exec, executable);
479     if (!unlinkedModuleProgramCode)
480         return nullptr;
481     executable->m_unlinkedModuleProgramCodeBlock.set(exec->vm(), executable, unlinkedModuleProgramCode);
482
483     executable->m_moduleEnvironmentSymbolTable.set(exec->vm(), executable, jsCast<SymbolTable*>(unlinkedModuleProgramCode->constantRegister(unlinkedModuleProgramCode->moduleEnvironmentSymbolTableConstantRegisterOffset()).get())->cloneScopePart(exec->vm()));
484
485     return executable;
486 }
487
488 void ModuleProgramExecutable::destroy(JSCell* cell)
489 {
490     static_cast<ModuleProgramExecutable*>(cell)->ModuleProgramExecutable::~ModuleProgramExecutable();
491 }
492
493 const ClassInfo FunctionExecutable::s_info = { "FunctionExecutable", &ScriptExecutable::s_info, 0, CREATE_METHOD_TABLE(FunctionExecutable) };
494
495 FunctionExecutable::FunctionExecutable(VM& vm, const SourceCode& source, 
496     UnlinkedFunctionExecutable* unlinkedExecutable, unsigned firstLine, 
497     unsigned lastLine, unsigned startColumn, unsigned endColumn)
498     : ScriptExecutable(vm.functionExecutableStructure.get(), vm, source, unlinkedExecutable->isInStrictContext())
499     , m_unlinkedExecutable(vm, this, unlinkedExecutable)
500 {
501     RELEASE_ASSERT(!source.isNull());
502     ASSERT(source.length());
503     m_firstLine = firstLine;
504     m_lastLine = lastLine;
505     ASSERT(startColumn != UINT_MAX);
506     ASSERT(endColumn != UINT_MAX);
507     m_startColumn = startColumn;
508     m_endColumn = endColumn;
509     m_parametersStartOffset = unlinkedExecutable->parametersStartOffset();
510     m_typeProfilingStartOffset = unlinkedExecutable->typeProfilingStartOffset();
511     m_typeProfilingEndOffset = unlinkedExecutable->typeProfilingEndOffset();
512 }
513
514 void FunctionExecutable::finishCreation(VM& vm)
515 {
516     Base::finishCreation(vm);
517     m_singletonFunction.set(vm, this, InferredValue::create(vm));
518 }
519
520 void FunctionExecutable::destroy(JSCell* cell)
521 {
522     static_cast<FunctionExecutable*>(cell)->FunctionExecutable::~FunctionExecutable();
523 }
524
525 inline const char* samplingDescription(JITCode::JITType jitType)
526 {
527     switch (jitType) {
528     case JITCode::InterpreterThunk:
529         return "Interpreter Compilation (TOTAL)";
530     case JITCode::BaselineJIT:
531         return "Baseline Compilation (TOTAL)";
532     case JITCode::DFGJIT:
533         return "DFG Compilation (TOTAL)";
534     case JITCode::FTLJIT:
535         return "FTL Compilation (TOTAL)";
536     default:
537         RELEASE_ASSERT_NOT_REACHED();
538         return 0;
539     }
540 }
541
542 void EvalExecutable::visitChildren(JSCell* cell, SlotVisitor& visitor)
543 {
544     EvalExecutable* thisObject = jsCast<EvalExecutable*>(cell);
545     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
546     ScriptExecutable::visitChildren(thisObject, visitor);
547     visitor.append(&thisObject->m_unlinkedEvalCodeBlock);
548     if (thisObject->m_evalCodeBlock)
549         thisObject->m_evalCodeBlock->visitWeakly(visitor);
550 }
551
552 JSObject* ProgramExecutable::checkSyntax(ExecState* exec)
553 {
554     ParserError error;
555     VM* vm = &exec->vm();
556     JSGlobalObject* lexicalGlobalObject = exec->lexicalGlobalObject();
557     std::unique_ptr<ProgramNode> programNode = parse<ProgramNode>(
558         vm, m_source, Identifier(), JSParserBuiltinMode::NotBuiltin, 
559         JSParserStrictMode::NotStrict, SourceParseMode::ProgramMode, SuperBinding::NotNeeded, error);
560     if (programNode)
561         return 0;
562     ASSERT(error.isValid());
563     return error.toErrorObject(lexicalGlobalObject, m_source);
564 }
565
566 JSObject* ProgramExecutable::initializeGlobalProperties(VM& vm, CallFrame* callFrame, JSScope* scope)
567 {
568     RELEASE_ASSERT(scope);
569     JSGlobalObject* globalObject = scope->globalObject();
570     RELEASE_ASSERT(globalObject);
571     ASSERT(&globalObject->vm() == &vm);
572
573     JSObject* exception = 0;
574     UnlinkedProgramCodeBlock* unlinkedCodeBlock = globalObject->createProgramCodeBlock(callFrame, this, &exception);
575     if (exception)
576         return exception;
577
578     JSGlobalLexicalEnvironment* globalLexicalEnvironment = globalObject->globalLexicalEnvironment();
579     const VariableEnvironment& variableDeclarations = unlinkedCodeBlock->variableDeclarations();
580     const VariableEnvironment& lexicalDeclarations = unlinkedCodeBlock->lexicalDeclarations();
581     // The ES6 spec says that no vars/global properties/let/const can be duplicated in the global scope.
582     // This carried out section 15.1.8 of the ES6 spec: http://www.ecma-international.org/ecma-262/6.0/index.html#sec-globaldeclarationinstantiation
583     {
584         ExecState* exec = globalObject->globalExec();
585         // Check for intersection of "var" and "let"/"const"/"class"
586         for (auto& entry : lexicalDeclarations) {
587             if (variableDeclarations.contains(entry.key))
588                 return createSyntaxError(exec, makeString("Can't create duplicate variable: '", String(entry.key.get()), "'"));
589         }
590
591         // Check if any new "let"/"const"/"class" will shadow any pre-existing global property names, or "var"/"let"/"const" variables.
592         // It's an error to introduce a shadow.
593         for (auto& entry : lexicalDeclarations) {
594             if (globalObject->hasProperty(exec, entry.key.get()))
595                 return createSyntaxError(exec, makeString("Can't create duplicate variable that shadows a global property: '", String(entry.key.get()), "'"));
596
597             if (globalLexicalEnvironment->hasProperty(exec, entry.key.get()))
598                 return createSyntaxError(exec, makeString("Can't create duplicate variable: '", String(entry.key.get()), "'"));
599         }
600
601         // Check if any new "var"s will shadow any previous "let"/"const"/"class" names.
602         // It's an error to introduce a shadow.
603         if (!globalLexicalEnvironment->isEmpty()) {
604             for (auto& entry : variableDeclarations) {
605                 if (globalLexicalEnvironment->hasProperty(exec, entry.key.get()))
606                     return createSyntaxError(exec, makeString("Can't create duplicate variable: '", String(entry.key.get()), "'"));
607             }
608         }
609     }
610
611
612     m_unlinkedProgramCodeBlock.set(vm, this, unlinkedCodeBlock);
613
614     BatchedTransitionOptimizer optimizer(vm, globalObject);
615
616     for (size_t i = 0, numberOfFunctions = unlinkedCodeBlock->numberOfFunctionDecls(); i < numberOfFunctions; ++i) {
617         UnlinkedFunctionExecutable* unlinkedFunctionExecutable = unlinkedCodeBlock->functionDecl(i);
618         ASSERT(!unlinkedFunctionExecutable->name().isEmpty());
619         globalObject->addFunction(callFrame, unlinkedFunctionExecutable->name());
620         if (vm.typeProfiler() || vm.controlFlowProfiler()) {
621             vm.functionHasExecutedCache()->insertUnexecutedRange(sourceID(), 
622                 unlinkedFunctionExecutable->typeProfilingStartOffset(), 
623                 unlinkedFunctionExecutable->typeProfilingEndOffset());
624         }
625     }
626
627     for (auto& entry : variableDeclarations) {
628         ASSERT(entry.value.isVar());
629         globalObject->addVar(callFrame, Identifier::fromUid(&vm, entry.key.get()));
630     }
631
632     {
633         JSGlobalLexicalEnvironment* globalLexicalEnvironment = jsCast<JSGlobalLexicalEnvironment*>(globalObject->globalScope());
634         SymbolTable* symbolTable = globalLexicalEnvironment->symbolTable();
635         ConcurrentJITLocker locker(symbolTable->m_lock);
636         for (auto& entry : lexicalDeclarations) {
637             ScopeOffset offset = symbolTable->takeNextScopeOffset(locker);
638             SymbolTableEntry newEntry(VarOffset(offset), entry.value.isConst() ? ReadOnly : 0);
639             newEntry.prepareToWatch();
640             symbolTable->add(locker, entry.key.get(), newEntry);
641             
642             ScopeOffset offsetForAssert = globalLexicalEnvironment->addVariables(1, jsTDZValue());
643             RELEASE_ASSERT(offsetForAssert == offset);
644         }
645     }
646     return 0;
647 }
648
649 void ProgramExecutable::visitChildren(JSCell* cell, SlotVisitor& visitor)
650 {
651     ProgramExecutable* thisObject = jsCast<ProgramExecutable*>(cell);
652     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
653     ScriptExecutable::visitChildren(thisObject, visitor);
654     visitor.append(&thisObject->m_unlinkedProgramCodeBlock);
655     if (thisObject->m_programCodeBlock)
656         thisObject->m_programCodeBlock->visitWeakly(visitor);
657 }
658
659 void ModuleProgramExecutable::visitChildren(JSCell* cell, SlotVisitor& visitor)
660 {
661     ModuleProgramExecutable* thisObject = jsCast<ModuleProgramExecutable*>(cell);
662     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
663     ScriptExecutable::visitChildren(thisObject, visitor);
664     visitor.append(&thisObject->m_unlinkedModuleProgramCodeBlock);
665     visitor.append(&thisObject->m_moduleEnvironmentSymbolTable);
666     if (thisObject->m_moduleProgramCodeBlock)
667         thisObject->m_moduleProgramCodeBlock->visitWeakly(visitor);
668 }
669
670 FunctionCodeBlock* FunctionExecutable::baselineCodeBlockFor(CodeSpecializationKind kind)
671 {
672     FunctionCodeBlock* result;
673     if (kind == CodeForCall)
674         result = m_codeBlockForCall.get();
675     else {
676         RELEASE_ASSERT(kind == CodeForConstruct);
677         result = m_codeBlockForConstruct.get();
678     }
679     if (!result)
680         return 0;
681     return static_cast<FunctionCodeBlock*>(result->baselineAlternative());
682 }
683
684 void FunctionExecutable::visitChildren(JSCell* cell, SlotVisitor& visitor)
685 {
686     FunctionExecutable* thisObject = jsCast<FunctionExecutable*>(cell);
687     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
688     ScriptExecutable::visitChildren(thisObject, visitor);
689     if (thisObject->m_codeBlockForCall)
690         thisObject->m_codeBlockForCall->visitWeakly(visitor);
691     if (thisObject->m_codeBlockForConstruct)
692         thisObject->m_codeBlockForConstruct->visitWeakly(visitor);
693     visitor.append(&thisObject->m_unlinkedExecutable);
694     visitor.append(&thisObject->m_singletonFunction);
695 }
696
697 FunctionExecutable* FunctionExecutable::fromGlobalCode(
698     const Identifier& name, ExecState& exec, const SourceCode& source, 
699     JSObject*& exception, int overrideLineNumber)
700 {
701     UnlinkedFunctionExecutable* unlinkedExecutable = 
702         UnlinkedFunctionExecutable::fromGlobalCode(
703             name, exec, source, exception, overrideLineNumber);
704     if (!unlinkedExecutable)
705         return nullptr;
706
707     return unlinkedExecutable->link(exec.vm(), source, overrideLineNumber);
708 }
709
710 #if ENABLE(WEBASSEMBLY)
711 const ClassInfo WebAssemblyExecutable::s_info = { "WebAssemblyExecutable", &ExecutableBase::s_info, 0, CREATE_METHOD_TABLE(WebAssemblyExecutable) };
712
713 WebAssemblyExecutable::WebAssemblyExecutable(VM& vm, const SourceCode& source, JSWASMModule* module, unsigned functionIndex)
714     : ExecutableBase(vm, vm.webAssemblyExecutableStructure.get(), NUM_PARAMETERS_NOT_COMPILED)
715     , m_source(source)
716     , m_module(vm, this, module)
717     , m_functionIndex(functionIndex)
718 {
719 }
720
721 void WebAssemblyExecutable::destroy(JSCell* cell)
722 {
723     static_cast<WebAssemblyExecutable*>(cell)->WebAssemblyExecutable::~WebAssemblyExecutable();
724 }
725
726 void WebAssemblyExecutable::visitChildren(JSCell* cell, SlotVisitor& visitor)
727 {
728     WebAssemblyExecutable* thisObject = jsCast<WebAssemblyExecutable*>(cell);
729     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
730     ExecutableBase::visitChildren(thisObject, visitor);
731     if (thisObject->m_codeBlockForCall)
732         thisObject->m_codeBlockForCall->visitWeakly(visitor);
733     visitor.append(&thisObject->m_module);
734 }
735
736 void WebAssemblyExecutable::prepareForExecution(ExecState* exec)
737 {
738     if (hasJITCodeForCall())
739         return;
740
741     VM& vm = exec->vm();
742     DeferGC deferGC(vm.heap);
743
744     WebAssemblyCodeBlock* codeBlock = WebAssemblyCodeBlock::create(&vm,
745         this, exec->lexicalGlobalObject());
746
747     WASMFunctionParser::compile(vm, codeBlock, m_module.get(), m_source, m_functionIndex);
748
749     m_jitCodeForCall = codeBlock->jitCode();
750     m_jitCodeForCallWithArityCheck = MacroAssemblerCodePtr();
751     m_numParametersForCall = codeBlock->numParameters();
752
753     m_codeBlockForCall.set(vm, this, codeBlock);
754
755     Heap::heap(this)->writeBarrier(this);
756 }
757 #endif
758
759 void ExecutableBase::dump(PrintStream& out) const
760 {
761     ExecutableBase* realThis = const_cast<ExecutableBase*>(this);
762     
763     if (classInfo() == NativeExecutable::info()) {
764         NativeExecutable* native = jsCast<NativeExecutable*>(realThis);
765         out.print("NativeExecutable:", RawPointer(bitwise_cast<void*>(native->function())), "/", RawPointer(bitwise_cast<void*>(native->constructor())));
766         return;
767     }
768     
769     if (classInfo() == EvalExecutable::info()) {
770         EvalExecutable* eval = jsCast<EvalExecutable*>(realThis);
771         if (CodeBlock* codeBlock = eval->codeBlock())
772             out.print(*codeBlock);
773         else
774             out.print("EvalExecutable w/o CodeBlock");
775         return;
776     }
777     
778     if (classInfo() == ProgramExecutable::info()) {
779         ProgramExecutable* eval = jsCast<ProgramExecutable*>(realThis);
780         if (CodeBlock* codeBlock = eval->codeBlock())
781             out.print(*codeBlock);
782         else
783             out.print("ProgramExecutable w/o CodeBlock");
784         return;
785     }
786
787     if (classInfo() == ModuleProgramExecutable::info()) {
788         ModuleProgramExecutable* executable = jsCast<ModuleProgramExecutable*>(realThis);
789         if (CodeBlock* codeBlock = executable->codeBlock())
790             out.print(*codeBlock);
791         else
792             out.print("ModuleProgramExecutable w/o CodeBlock");
793         return;
794     }
795     
796     FunctionExecutable* function = jsCast<FunctionExecutable*>(realThis);
797     if (!function->eitherCodeBlock())
798         out.print("FunctionExecutable w/o CodeBlock");
799     else {
800         CommaPrinter comma("/");
801         if (function->codeBlockForCall())
802             out.print(comma, *function->codeBlockForCall());
803         if (function->codeBlockForConstruct())
804             out.print(comma, *function->codeBlockForConstruct());
805     }
806 }
807
808 CodeBlockHash ExecutableBase::hashFor(CodeSpecializationKind kind) const
809 {
810     if (this->classInfo() == NativeExecutable::info())
811         return jsCast<const NativeExecutable*>(this)->hashFor(kind);
812     
813     return jsCast<const ScriptExecutable*>(this)->hashFor(kind);
814 }
815
816 CodeBlockHash NativeExecutable::hashFor(CodeSpecializationKind kind) const
817 {
818     if (kind == CodeForCall)
819         return CodeBlockHash(static_cast<unsigned>(bitwise_cast<size_t>(m_function)));
820     
821     RELEASE_ASSERT(kind == CodeForConstruct);
822     return CodeBlockHash(static_cast<unsigned>(bitwise_cast<size_t>(m_constructor)));
823 }
824
825 CodeBlockHash ScriptExecutable::hashFor(CodeSpecializationKind kind) const
826 {
827     return CodeBlockHash(source(), kind);
828 }
829
830 }