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