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