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