030bcc5158782bffc9876e5b0584c0c8b865191a
[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->isArrowFunction());
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     JSObject* exception = 0;
392     CodeBlock* codeBlock = newCodeBlockFor(kind, function, scope, exception);
393     if (!codeBlock) {
394         RELEASE_ASSERT(exception);
395         return exception;
396     }
397     
398     if (Options::validateBytecode())
399         codeBlock->validate();
400     
401     if (Options::useLLInt())
402         setupLLInt(vm, codeBlock);
403     else
404         setupJIT(vm, codeBlock);
405     
406     installCode(*codeBlock->vm(), codeBlock, codeBlock->codeType(), codeBlock->specializationKind());
407     return 0;
408 }
409
410 const ClassInfo EvalExecutable::s_info = { "EvalExecutable", &ScriptExecutable::s_info, 0, CREATE_METHOD_TABLE(EvalExecutable) };
411
412 EvalExecutable* EvalExecutable::create(ExecState* exec, const SourceCode& source, bool isInStrictContext, ThisTDZMode thisTDZMode, const VariableEnvironment* variablesUnderTDZ)
413 {
414     JSGlobalObject* globalObject = exec->lexicalGlobalObject();
415     if (!globalObject->evalEnabled()) {
416         exec->vm().throwException(exec, createEvalError(exec, globalObject->evalDisabledErrorMessage()));
417         return 0;
418     }
419
420     EvalExecutable* executable = new (NotNull, allocateCell<EvalExecutable>(*exec->heap())) EvalExecutable(exec, source, isInStrictContext);
421     executable->finishCreation(exec->vm());
422
423     UnlinkedEvalCodeBlock* unlinkedEvalCode = globalObject->createEvalCodeBlock(exec, executable, thisTDZMode, variablesUnderTDZ);
424     if (!unlinkedEvalCode)
425         return 0;
426
427     executable->m_unlinkedEvalCodeBlock.set(exec->vm(), executable, unlinkedEvalCode);
428
429     return executable;
430 }
431
432 EvalExecutable::EvalExecutable(ExecState* exec, const SourceCode& source, bool inStrictContext)
433     : ScriptExecutable(exec->vm().evalExecutableStructure.get(), exec->vm(), source, inStrictContext)
434 {
435 }
436
437 void EvalExecutable::destroy(JSCell* cell)
438 {
439     static_cast<EvalExecutable*>(cell)->EvalExecutable::~EvalExecutable();
440 }
441
442 const ClassInfo ProgramExecutable::s_info = { "ProgramExecutable", &ScriptExecutable::s_info, 0, CREATE_METHOD_TABLE(ProgramExecutable) };
443
444 ProgramExecutable::ProgramExecutable(ExecState* exec, const SourceCode& source)
445     : ScriptExecutable(exec->vm().programExecutableStructure.get(), exec->vm(), source, false)
446 {
447     m_typeProfilingStartOffset = 0;
448     m_typeProfilingEndOffset = source.length() - 1;
449     if (exec->vm().typeProfiler() || exec->vm().controlFlowProfiler())
450         exec->vm().functionHasExecutedCache()->insertUnexecutedRange(sourceID(), m_typeProfilingStartOffset, m_typeProfilingEndOffset);
451 }
452
453 void ProgramExecutable::destroy(JSCell* cell)
454 {
455     static_cast<ProgramExecutable*>(cell)->ProgramExecutable::~ProgramExecutable();
456 }
457
458 const ClassInfo ModuleProgramExecutable::s_info = { "ModuleProgramExecutable", &ScriptExecutable::s_info, 0, CREATE_METHOD_TABLE(ModuleProgramExecutable) };
459
460 ModuleProgramExecutable::ModuleProgramExecutable(ExecState* exec, const SourceCode& source)
461     : ScriptExecutable(exec->vm().moduleProgramExecutableStructure.get(), exec->vm(), source, false)
462 {
463     m_typeProfilingStartOffset = 0;
464     m_typeProfilingEndOffset = source.length() - 1;
465     if (exec->vm().typeProfiler() || exec->vm().controlFlowProfiler())
466         exec->vm().functionHasExecutedCache()->insertUnexecutedRange(sourceID(), m_typeProfilingStartOffset, m_typeProfilingEndOffset);
467 }
468
469 ModuleProgramExecutable* ModuleProgramExecutable::create(ExecState* exec, const SourceCode& source)
470 {
471     JSGlobalObject* globalObject = exec->lexicalGlobalObject();
472     ModuleProgramExecutable* executable = new (NotNull, allocateCell<ModuleProgramExecutable>(*exec->heap())) ModuleProgramExecutable(exec, source);
473     executable->finishCreation(exec->vm());
474
475     UnlinkedModuleProgramCodeBlock* unlinkedModuleProgramCode = globalObject->createModuleProgramCodeBlock(exec, executable);
476     if (!unlinkedModuleProgramCode)
477         return nullptr;
478     executable->m_unlinkedModuleProgramCodeBlock.set(exec->vm(), executable, unlinkedModuleProgramCode);
479
480     executable->m_moduleEnvironmentSymbolTable.set(exec->vm(), executable, jsCast<SymbolTable*>(unlinkedModuleProgramCode->constantRegister(unlinkedModuleProgramCode->moduleEnvironmentSymbolTableConstantRegisterOffset()).get())->cloneScopePart(exec->vm()));
481
482     return executable;
483 }
484
485 void ModuleProgramExecutable::destroy(JSCell* cell)
486 {
487     static_cast<ModuleProgramExecutable*>(cell)->ModuleProgramExecutable::~ModuleProgramExecutable();
488 }
489
490 const ClassInfo FunctionExecutable::s_info = { "FunctionExecutable", &ScriptExecutable::s_info, 0, CREATE_METHOD_TABLE(FunctionExecutable) };
491
492 FunctionExecutable::FunctionExecutable(VM& vm, const SourceCode& source, 
493     UnlinkedFunctionExecutable* unlinkedExecutable, unsigned firstLine, 
494     unsigned lastLine, unsigned startColumn, unsigned endColumn)
495     : ScriptExecutable(vm.functionExecutableStructure.get(), vm, source, unlinkedExecutable->isInStrictContext())
496     , m_unlinkedExecutable(vm, this, unlinkedExecutable)
497 {
498     RELEASE_ASSERT(!source.isNull());
499     ASSERT(source.length());
500     m_firstLine = firstLine;
501     m_lastLine = lastLine;
502     ASSERT(startColumn != UINT_MAX);
503     ASSERT(endColumn != UINT_MAX);
504     m_startColumn = startColumn;
505     m_endColumn = endColumn;
506     m_parametersStartOffset = unlinkedExecutable->parametersStartOffset();
507     m_typeProfilingStartOffset = unlinkedExecutable->typeProfilingStartOffset();
508     m_typeProfilingEndOffset = unlinkedExecutable->typeProfilingEndOffset();
509 }
510
511 void FunctionExecutable::finishCreation(VM& vm)
512 {
513     Base::finishCreation(vm);
514     m_singletonFunction.set(vm, this, InferredValue::create(vm));
515 }
516
517 void FunctionExecutable::destroy(JSCell* cell)
518 {
519     static_cast<FunctionExecutable*>(cell)->FunctionExecutable::~FunctionExecutable();
520 }
521
522 inline const char* samplingDescription(JITCode::JITType jitType)
523 {
524     switch (jitType) {
525     case JITCode::InterpreterThunk:
526         return "Interpreter Compilation (TOTAL)";
527     case JITCode::BaselineJIT:
528         return "Baseline Compilation (TOTAL)";
529     case JITCode::DFGJIT:
530         return "DFG Compilation (TOTAL)";
531     case JITCode::FTLJIT:
532         return "FTL Compilation (TOTAL)";
533     default:
534         RELEASE_ASSERT_NOT_REACHED();
535         return 0;
536     }
537 }
538
539 void EvalExecutable::visitChildren(JSCell* cell, SlotVisitor& visitor)
540 {
541     EvalExecutable* thisObject = jsCast<EvalExecutable*>(cell);
542     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
543     ScriptExecutable::visitChildren(thisObject, visitor);
544     visitor.append(&thisObject->m_unlinkedEvalCodeBlock);
545     if (thisObject->m_evalCodeBlock)
546         thisObject->m_evalCodeBlock->visitWeakly(visitor);
547 }
548
549 JSObject* ProgramExecutable::checkSyntax(ExecState* exec)
550 {
551     ParserError error;
552     VM* vm = &exec->vm();
553     JSGlobalObject* lexicalGlobalObject = exec->lexicalGlobalObject();
554     std::unique_ptr<ProgramNode> programNode = parse<ProgramNode>(
555         vm, m_source, Identifier(), JSParserBuiltinMode::NotBuiltin, 
556         JSParserStrictMode::NotStrict, SourceParseMode::ProgramMode, error);
557     if (programNode)
558         return 0;
559     ASSERT(error.isValid());
560     return error.toErrorObject(lexicalGlobalObject, m_source);
561 }
562
563 JSObject* ProgramExecutable::initializeGlobalProperties(VM& vm, CallFrame* callFrame, JSScope* scope)
564 {
565     RELEASE_ASSERT(scope);
566     JSGlobalObject* globalObject = scope->globalObject();
567     RELEASE_ASSERT(globalObject);
568     ASSERT(&globalObject->vm() == &vm);
569
570     JSObject* exception = 0;
571     UnlinkedProgramCodeBlock* unlinkedCodeBlock = globalObject->createProgramCodeBlock(callFrame, this, &exception);
572     if (exception)
573         return exception;
574
575     JSGlobalLexicalEnvironment* globalLexicalEnvironment = globalObject->globalLexicalEnvironment();
576     const VariableEnvironment& variableDeclarations = unlinkedCodeBlock->variableDeclarations();
577     const VariableEnvironment& lexicalDeclarations = unlinkedCodeBlock->lexicalDeclarations();
578     // The ES6 spec says that no vars/global properties/let/const can be duplicated in the global scope.
579     // This carried out section 15.1.8 of the ES6 spec: http://www.ecma-international.org/ecma-262/6.0/index.html#sec-globaldeclarationinstantiation
580     {
581         ExecState* exec = globalObject->globalExec();
582         // Check for intersection of "var" and "let"/"const"/"class"
583         for (auto& entry : lexicalDeclarations) {
584             if (variableDeclarations.contains(entry.key))
585                 return createSyntaxError(exec, makeString("Can't create duplicate variable: '", String(entry.key.get()), "'"));
586         }
587
588         // Check if any new "let"/"const"/"class" will shadow any pre-existing global property names, or "var"/"let"/"const" variables.
589         // It's an error to introduce a shadow.
590         for (auto& entry : lexicalDeclarations) {
591             if (globalObject->hasProperty(exec, entry.key.get()))
592                 return createSyntaxError(exec, makeString("Can't create duplicate variable that shadows a global property: '", String(entry.key.get()), "'"));
593
594             if (globalLexicalEnvironment->hasProperty(exec, entry.key.get()))
595                 return createSyntaxError(exec, makeString("Can't create duplicate variable: '", String(entry.key.get()), "'"));
596         }
597
598         // Check if any new "var"s will shadow any previous "let"/"const"/"class" names.
599         // It's an error to introduce a shadow.
600         if (!globalLexicalEnvironment->isEmpty()) {
601             for (auto& entry : variableDeclarations) {
602                 if (globalLexicalEnvironment->hasProperty(exec, entry.key.get()))
603                     return createSyntaxError(exec, makeString("Can't create duplicate variable: '", String(entry.key.get()), "'"));
604             }
605         }
606     }
607
608
609     m_unlinkedProgramCodeBlock.set(vm, this, unlinkedCodeBlock);
610
611     BatchedTransitionOptimizer optimizer(vm, globalObject);
612
613     for (size_t i = 0, numberOfFunctions = unlinkedCodeBlock->numberOfFunctionDecls(); i < numberOfFunctions; ++i) {
614         UnlinkedFunctionExecutable* unlinkedFunctionExecutable = unlinkedCodeBlock->functionDecl(i);
615         ASSERT(!unlinkedFunctionExecutable->name().isEmpty());
616         globalObject->addFunction(callFrame, unlinkedFunctionExecutable->name());
617         if (vm.typeProfiler() || vm.controlFlowProfiler()) {
618             vm.functionHasExecutedCache()->insertUnexecutedRange(sourceID(), 
619                 unlinkedFunctionExecutable->typeProfilingStartOffset(), 
620                 unlinkedFunctionExecutable->typeProfilingEndOffset());
621         }
622     }
623
624     for (auto& entry : variableDeclarations) {
625         ASSERT(entry.value.isVar());
626         globalObject->addVar(callFrame, Identifier::fromUid(&vm, entry.key.get()));
627     }
628
629     {
630         JSGlobalLexicalEnvironment* globalLexicalEnvironment = jsCast<JSGlobalLexicalEnvironment*>(globalObject->globalScope());
631         SymbolTable* symbolTable = globalLexicalEnvironment->symbolTable();
632         ConcurrentJITLocker locker(symbolTable->m_lock);
633         for (auto& entry : lexicalDeclarations) {
634             ScopeOffset offset = symbolTable->takeNextScopeOffset(locker);
635             SymbolTableEntry newEntry(VarOffset(offset), entry.value.isConst() ? ReadOnly : 0);
636             newEntry.prepareToWatch();
637             symbolTable->add(locker, entry.key.get(), newEntry);
638             
639             ScopeOffset offsetForAssert = globalLexicalEnvironment->addVariables(1, jsTDZValue());
640             RELEASE_ASSERT(offsetForAssert == offset);
641         }
642     }
643     return 0;
644 }
645
646 void ProgramExecutable::visitChildren(JSCell* cell, SlotVisitor& visitor)
647 {
648     ProgramExecutable* thisObject = jsCast<ProgramExecutable*>(cell);
649     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
650     ScriptExecutable::visitChildren(thisObject, visitor);
651     visitor.append(&thisObject->m_unlinkedProgramCodeBlock);
652     if (thisObject->m_programCodeBlock)
653         thisObject->m_programCodeBlock->visitWeakly(visitor);
654 }
655
656 void ModuleProgramExecutable::visitChildren(JSCell* cell, SlotVisitor& visitor)
657 {
658     ModuleProgramExecutable* thisObject = jsCast<ModuleProgramExecutable*>(cell);
659     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
660     ScriptExecutable::visitChildren(thisObject, visitor);
661     visitor.append(&thisObject->m_unlinkedModuleProgramCodeBlock);
662     visitor.append(&thisObject->m_moduleEnvironmentSymbolTable);
663     if (thisObject->m_moduleProgramCodeBlock)
664         thisObject->m_moduleProgramCodeBlock->visitWeakly(visitor);
665 }
666
667 FunctionCodeBlock* FunctionExecutable::baselineCodeBlockFor(CodeSpecializationKind kind)
668 {
669     FunctionCodeBlock* result;
670     if (kind == CodeForCall)
671         result = m_codeBlockForCall.get();
672     else {
673         RELEASE_ASSERT(kind == CodeForConstruct);
674         result = m_codeBlockForConstruct.get();
675     }
676     if (!result)
677         return 0;
678     return static_cast<FunctionCodeBlock*>(result->baselineAlternative());
679 }
680
681 void FunctionExecutable::visitChildren(JSCell* cell, SlotVisitor& visitor)
682 {
683     FunctionExecutable* thisObject = jsCast<FunctionExecutable*>(cell);
684     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
685     ScriptExecutable::visitChildren(thisObject, visitor);
686     if (thisObject->m_codeBlockForCall)
687         thisObject->m_codeBlockForCall->visitWeakly(visitor);
688     if (thisObject->m_codeBlockForConstruct)
689         thisObject->m_codeBlockForConstruct->visitWeakly(visitor);
690     visitor.append(&thisObject->m_unlinkedExecutable);
691     visitor.append(&thisObject->m_singletonFunction);
692 }
693
694 FunctionExecutable* FunctionExecutable::fromGlobalCode(
695     const Identifier& name, ExecState& exec, const SourceCode& source, 
696     JSObject*& exception, int overrideLineNumber)
697 {
698     UnlinkedFunctionExecutable* unlinkedExecutable = 
699         UnlinkedFunctionExecutable::fromGlobalCode(
700             name, exec, source, exception, overrideLineNumber);
701     if (!unlinkedExecutable)
702         return nullptr;
703
704     return unlinkedExecutable->link(exec.vm(), source, overrideLineNumber);
705 }
706
707 #if ENABLE(WEBASSEMBLY)
708 const ClassInfo WebAssemblyExecutable::s_info = { "WebAssemblyExecutable", &ExecutableBase::s_info, 0, CREATE_METHOD_TABLE(WebAssemblyExecutable) };
709
710 WebAssemblyExecutable::WebAssemblyExecutable(VM& vm, const SourceCode& source, JSWASMModule* module, unsigned functionIndex)
711     : ExecutableBase(vm, vm.webAssemblyExecutableStructure.get(), NUM_PARAMETERS_NOT_COMPILED)
712     , m_source(source)
713     , m_module(vm, this, module)
714     , m_functionIndex(functionIndex)
715 {
716 }
717
718 void WebAssemblyExecutable::destroy(JSCell* cell)
719 {
720     static_cast<WebAssemblyExecutable*>(cell)->WebAssemblyExecutable::~WebAssemblyExecutable();
721 }
722
723 void WebAssemblyExecutable::visitChildren(JSCell* cell, SlotVisitor& visitor)
724 {
725     WebAssemblyExecutable* thisObject = jsCast<WebAssemblyExecutable*>(cell);
726     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
727     ExecutableBase::visitChildren(thisObject, visitor);
728     if (thisObject->m_codeBlockForCall)
729         thisObject->m_codeBlockForCall->visitWeakly(visitor);
730     visitor.append(&thisObject->m_module);
731 }
732
733 void WebAssemblyExecutable::prepareForExecution(ExecState* exec)
734 {
735     if (hasJITCodeForCall())
736         return;
737
738     VM& vm = exec->vm();
739     DeferGC deferGC(vm.heap);
740
741     WebAssemblyCodeBlock* codeBlock = WebAssemblyCodeBlock::create(vm,
742         this, exec->lexicalGlobalObject()));
743
744     WASMFunctionParser::compile(vm, codeBlock, m_module.get(), m_source, m_functionIndex);
745
746     m_jitCodeForCall = codeBlock->jitCode();
747     m_jitCodeForCallWithArityCheck = MacroAssemblerCodePtr();
748     m_numParametersForCall = codeBlock->numParameters();
749
750     m_codeBlockForCall.set(vm, this, codeBlock);
751
752     Heap::heap(this)->writeBarrier(this);
753 }
754 #endif
755
756 void ExecutableBase::dump(PrintStream& out) const
757 {
758     ExecutableBase* realThis = const_cast<ExecutableBase*>(this);
759     
760     if (classInfo() == NativeExecutable::info()) {
761         NativeExecutable* native = jsCast<NativeExecutable*>(realThis);
762         out.print("NativeExecutable:", RawPointer(bitwise_cast<void*>(native->function())), "/", RawPointer(bitwise_cast<void*>(native->constructor())));
763         return;
764     }
765     
766     if (classInfo() == EvalExecutable::info()) {
767         EvalExecutable* eval = jsCast<EvalExecutable*>(realThis);
768         if (CodeBlock* codeBlock = eval->codeBlock())
769             out.print(*codeBlock);
770         else
771             out.print("EvalExecutable w/o CodeBlock");
772         return;
773     }
774     
775     if (classInfo() == ProgramExecutable::info()) {
776         ProgramExecutable* eval = jsCast<ProgramExecutable*>(realThis);
777         if (CodeBlock* codeBlock = eval->codeBlock())
778             out.print(*codeBlock);
779         else
780             out.print("ProgramExecutable w/o CodeBlock");
781         return;
782     }
783
784     if (classInfo() == ModuleProgramExecutable::info()) {
785         ModuleProgramExecutable* executable = jsCast<ModuleProgramExecutable*>(realThis);
786         if (CodeBlock* codeBlock = executable->codeBlock())
787             out.print(*codeBlock);
788         else
789             out.print("ModuleProgramExecutable w/o CodeBlock");
790         return;
791     }
792     
793     FunctionExecutable* function = jsCast<FunctionExecutable*>(realThis);
794     if (!function->eitherCodeBlock())
795         out.print("FunctionExecutable w/o CodeBlock");
796     else {
797         CommaPrinter comma("/");
798         if (function->codeBlockForCall())
799             out.print(comma, *function->codeBlockForCall());
800         if (function->codeBlockForConstruct())
801             out.print(comma, *function->codeBlockForConstruct());
802     }
803 }
804
805 CodeBlockHash ExecutableBase::hashFor(CodeSpecializationKind kind) const
806 {
807     if (this->classInfo() == NativeExecutable::info())
808         return jsCast<const NativeExecutable*>(this)->hashFor(kind);
809     
810     return jsCast<const ScriptExecutable*>(this)->hashFor(kind);
811 }
812
813 CodeBlockHash NativeExecutable::hashFor(CodeSpecializationKind kind) const
814 {
815     if (kind == CodeForCall)
816         return CodeBlockHash(static_cast<unsigned>(bitwise_cast<size_t>(m_function)));
817     
818     RELEASE_ASSERT(kind == CodeForConstruct);
819     return CodeBlockHash(static_cast<unsigned>(bitwise_cast<size_t>(m_constructor)));
820 }
821
822 CodeBlockHash ScriptExecutable::hashFor(CodeSpecializationKind kind) const
823 {
824     return CodeBlockHash(source(), kind);
825 }
826
827 }