Unreviewed, rolling out r223691 and r223729.
[WebKit-https.git] / Source / JavaScriptCore / bytecompiler / BytecodeGenerator.cpp
1 /*
2  * Copyright (C) 2008-2017 Apple Inc. All rights reserved.
3  * Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca>
4  * Copyright (C) 2012 Igalia, S.L.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1.  Redistributions of source code must retain the above copyright
11  *     notice, this list of conditions and the following disclaimer.
12  * 2.  Redistributions in binary form must reproduce the above copyright
13  *     notice, this list of conditions and the following disclaimer in the
14  *     documentation and/or other materials provided with the distribution.
15  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
16  *     its contributors may be used to endorse or promote products derived
17  *     from this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include "config.h"
32 #include "BytecodeGenerator.h"
33
34 #include "ArithProfile.h"
35 #include "BuiltinExecutables.h"
36 #include "BuiltinNames.h"
37 #include "BytecodeGeneratorification.h"
38 #include "BytecodeLivenessAnalysis.h"
39 #include "DefinePropertyAttributes.h"
40 #include "Interpreter.h"
41 #include "JSAsyncGeneratorFunction.h"
42 #include "JSCInlines.h"
43 #include "JSFunction.h"
44 #include "JSGeneratorFunction.h"
45 #include "JSLexicalEnvironment.h"
46 #include "JSTemplateRegistryKey.h"
47 #include "LowLevelInterpreter.h"
48 #include "Options.h"
49 #include "StackAlignment.h"
50 #include "StrongInlines.h"
51 #include "UnlinkedCodeBlock.h"
52 #include "UnlinkedEvalCodeBlock.h"
53 #include "UnlinkedFunctionCodeBlock.h"
54 #include "UnlinkedInstructionStream.h"
55 #include "UnlinkedModuleProgramCodeBlock.h"
56 #include "UnlinkedProgramCodeBlock.h"
57 #include <wtf/BitVector.h>
58 #include <wtf/CommaPrinter.h>
59 #include <wtf/SmallPtrSet.h>
60 #include <wtf/StdLibExtras.h>
61 #include <wtf/text/WTFString.h>
62
63 using namespace std;
64
65 namespace JSC {
66
67 template<typename T>
68 static inline void shrinkToFit(T& segmentedVector)
69 {
70     while (segmentedVector.size() && !segmentedVector.last().refCount())
71         segmentedVector.removeLast();
72 }
73
74 void Label::setLocation(BytecodeGenerator& generator, unsigned location)
75 {
76     m_location = location;
77     
78     unsigned size = m_unresolvedJumps.size();
79     for (unsigned i = 0; i < size; ++i)
80         generator.instructions()[m_unresolvedJumps[i].second].u.operand = m_location - m_unresolvedJumps[i].first;
81 }
82
83 void Variable::dump(PrintStream& out) const
84 {
85     out.print(
86         "{ident = ", m_ident,
87         ", offset = ", m_offset,
88         ", local = ", RawPointer(m_local),
89         ", attributes = ", m_attributes,
90         ", kind = ", m_kind,
91         ", symbolTableConstantIndex = ", m_symbolTableConstantIndex,
92         ", isLexicallyScoped = ", m_isLexicallyScoped, "}");
93 }
94
95 ParserError BytecodeGenerator::generate()
96 {
97     m_codeBlock->setThisRegister(m_thisRegister.virtualRegister());
98
99     emitLogShadowChickenPrologueIfNecessary();
100     
101     // If we have declared a variable named "arguments" and we are using arguments then we should
102     // perform that assignment now.
103     if (m_needToInitializeArguments)
104         initializeVariable(variable(propertyNames().arguments), m_argumentsRegister);
105
106     if (m_restParameter)
107         m_restParameter->emit(*this);
108
109     {
110         RefPtr<RegisterID> temp = newTemporary();
111         RefPtr<RegisterID> tolLevelScope;
112         for (auto functionPair : m_functionsToInitialize) {
113             FunctionMetadataNode* metadata = functionPair.first;
114             FunctionVariableType functionType = functionPair.second;
115             emitNewFunction(temp.get(), metadata);
116             if (functionType == NormalFunctionVariable)
117                 initializeVariable(variable(metadata->ident()), temp.get());
118             else if (functionType == TopLevelFunctionVariable) {
119                 if (!tolLevelScope) {
120                     // We know this will resolve to the top level scope or global object because our parser/global initialization code 
121                     // doesn't allow let/const/class variables to have the same names as functions.
122                     // This is a top level function, and it's an error to ever create a top level function
123                     // name that would resolve to a lexical variable. E.g:
124                     // ```
125                     //     function f() {
126                     //         {
127                     //             let x;
128                     //             {
129                     //             //// error thrown here
130                     //                  eval("function x(){}");
131                     //             }
132                     //         }
133                     //     }
134                     // ```
135                     // Therefore, we're guaranteed to have this resolve to a top level variable.
136                     RefPtr<RegisterID> tolLevelObjectScope = emitResolveScope(nullptr, Variable(metadata->ident()));
137                     tolLevelScope = newBlockScopeVariable();
138                     emitMove(tolLevelScope.get(), tolLevelObjectScope.get());
139                 }
140                 emitPutToScope(tolLevelScope.get(), Variable(metadata->ident()), temp.get(), ThrowIfNotFound, InitializationMode::NotInitialization);
141             } else
142                 RELEASE_ASSERT_NOT_REACHED();
143         }
144     }
145     
146     bool callingClassConstructor = constructorKind() != ConstructorKind::None && !isConstructor();
147     if (!callingClassConstructor)
148         m_scopeNode->emitBytecode(*this);
149     else {
150         // At this point we would have emitted an unconditional throw followed by some nonsense that's
151         // just an artifact of how this generator is structured. That code never runs, but it confuses
152         // bytecode analyses because it constitutes an unterminated basic block. So, we terminate the
153         // basic block the strongest way possible.
154         emitUnreachable();
155     }
156
157     for (auto& tuple : m_catchesToEmit) {
158         Ref<Label> realCatchTarget = newEmittedLabel();
159         emitOpcode(op_catch);
160         instructions().append(std::get<1>(tuple));
161         instructions().append(std::get<2>(tuple));
162         instructions().append(0);
163
164         TryData* tryData = std::get<0>(tuple);
165         emitJump(tryData->target.get());
166         tryData->target = WTFMove(realCatchTarget);
167     }
168
169     m_staticPropertyAnalyzer.kill();
170
171     for (auto& range : m_tryRanges) {
172         int start = range.start->bind();
173         int end = range.end->bind();
174         
175         // This will happen for empty try blocks and for some cases of finally blocks:
176         //
177         // try {
178         //    try {
179         //    } finally {
180         //        return 42;
181         //        // *HERE*
182         //    }
183         // } finally {
184         //    print("things");
185         // }
186         //
187         // The return will pop scopes to execute the outer finally block. But this includes
188         // popping the try context for the inner try. The try context is live in the fall-through
189         // part of the finally block not because we will emit a handler that overlaps the finally,
190         // but because we haven't yet had a chance to plant the catch target. Then when we finish
191         // emitting code for the outer finally block, we repush the try contex, this time with a
192         // new start index. But that means that the start index for the try range corresponding
193         // to the inner-finally-following-the-return (marked as "*HERE*" above) will be greater
194         // than the end index of the try block. This is harmless since end < start handlers will
195         // never get matched in our logic, but we do the runtime a favor and choose to not emit
196         // such handlers at all.
197         if (end <= start)
198             continue;
199         
200         UnlinkedHandlerInfo info(static_cast<uint32_t>(start), static_cast<uint32_t>(end),
201             static_cast<uint32_t>(range.tryData->target->bind()), range.tryData->handlerType);
202         m_codeBlock->addExceptionHandler(info);
203     }
204     
205
206     if (isGeneratorOrAsyncFunctionBodyParseMode(m_codeBlock->parseMode()))
207         performGeneratorification(m_codeBlock.get(), m_instructions, m_generatorFrameSymbolTable.get(), m_generatorFrameSymbolTableIndex);
208
209     RELEASE_ASSERT(static_cast<unsigned>(m_codeBlock->numCalleeLocals()) < static_cast<unsigned>(FirstConstantRegisterIndex));
210     m_codeBlock->setInstructions(std::make_unique<UnlinkedInstructionStream>(m_instructions));
211
212     m_codeBlock->shrinkToFit();
213
214     if (m_expressionTooDeep)
215         return ParserError(ParserError::OutOfMemory);
216     return ParserError(ParserError::ErrorNone);
217 }
218
219 BytecodeGenerator::BytecodeGenerator(VM& vm, ProgramNode* programNode, UnlinkedProgramCodeBlock* codeBlock, DebuggerMode debuggerMode, const VariableEnvironment* parentScopeTDZVariables)
220     : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
221     , m_scopeNode(programNode)
222     , m_codeBlock(vm, codeBlock)
223     , m_thisRegister(CallFrame::thisArgumentOffset())
224     , m_codeType(GlobalCode)
225     , m_vm(&vm)
226     , m_needsToUpdateArrowFunctionContext(programNode->usesArrowFunction() || programNode->usesEval())
227 {
228     ASSERT_UNUSED(parentScopeTDZVariables, !parentScopeTDZVariables->size());
229
230     for (auto& constantRegister : m_linkTimeConstantRegisters)
231         constantRegister = nullptr;
232
233     allocateCalleeSaveSpace();
234
235     m_codeBlock->setNumParameters(1); // Allocate space for "this"
236
237     emitEnter();
238
239     allocateAndEmitScope();
240
241     emitCheckTraps();
242
243     const FunctionStack& functionStack = programNode->functionStack();
244
245     for (auto* function : functionStack)
246         m_functionsToInitialize.append(std::make_pair(function, TopLevelFunctionVariable));
247
248     if (Options::validateBytecode()) {
249         for (auto& entry : programNode->varDeclarations())
250             RELEASE_ASSERT(entry.value.isVar());
251     }
252     codeBlock->setVariableDeclarations(programNode->varDeclarations());
253     codeBlock->setLexicalDeclarations(programNode->lexicalVariables());
254     // Even though this program may have lexical variables that go under TDZ, when linking the get_from_scope/put_to_scope
255     // operations we emit we will have ResolveTypes that implictly do TDZ checks. Therefore, we don't need
256     // additional TDZ checks on top of those. This is why we can omit pushing programNode->lexicalVariables()
257     // to the TDZ stack.
258     
259     if (needsToUpdateArrowFunctionContext()) {
260         initializeArrowFunctionContextScopeIfNeeded();
261         emitPutThisToArrowFunctionContextScope();
262     }
263 }
264
265 BytecodeGenerator::BytecodeGenerator(VM& vm, FunctionNode* functionNode, UnlinkedFunctionCodeBlock* codeBlock, DebuggerMode debuggerMode, const VariableEnvironment* parentScopeTDZVariables)
266     : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
267     , m_scopeNode(functionNode)
268     , m_codeBlock(vm, codeBlock)
269     , m_codeType(FunctionCode)
270     , m_vm(&vm)
271     , m_isBuiltinFunction(codeBlock->isBuiltinFunction())
272     , m_usesNonStrictEval(codeBlock->usesEval() && !codeBlock->isStrictMode())
273     // FIXME: We should be able to have tail call elimination with the profiler
274     // enabled. This is currently not possible because the profiler expects
275     // op_will_call / op_did_call pairs before and after a call, which are not
276     // compatible with tail calls (we have no way of emitting op_did_call).
277     // https://bugs.webkit.org/show_bug.cgi?id=148819
278     , m_inTailPosition(Options::useTailCalls() && !isConstructor() && constructorKind() == ConstructorKind::None && isStrictMode())
279     , m_needsToUpdateArrowFunctionContext(functionNode->usesArrowFunction() || functionNode->usesEval())
280     , m_derivedContextType(codeBlock->derivedContextType())
281 {
282     for (auto& constantRegister : m_linkTimeConstantRegisters)
283         constantRegister = nullptr;
284
285     if (m_isBuiltinFunction)
286         m_shouldEmitDebugHooks = false;
287
288     allocateCalleeSaveSpace();
289     
290     SymbolTable* functionSymbolTable = SymbolTable::create(*m_vm);
291     functionSymbolTable->setUsesNonStrictEval(m_usesNonStrictEval);
292     int symbolTableConstantIndex = 0;
293
294     FunctionParameters& parameters = *functionNode->parameters(); 
295     // http://www.ecma-international.org/ecma-262/6.0/index.html#sec-functiondeclarationinstantiation
296     // This implements IsSimpleParameterList in the Ecma 2015 spec.
297     // If IsSimpleParameterList is false, we will create a strict-mode like arguments object.
298     // IsSimpleParameterList is false if the argument list contains any default parameter values,
299     // a rest parameter, or any destructuring patterns.
300     // If we do have default parameters, destructuring parameters, or a rest parameter, our parameters will be allocated in a different scope.
301     bool isSimpleParameterList = parameters.isSimpleParameterList();
302
303     SourceParseMode parseMode = codeBlock->parseMode();
304
305     bool containsArrowOrEvalButNotInArrowBlock = ((functionNode->usesArrowFunction() && functionNode->doAnyInnerArrowFunctionsUseAnyFeature()) || functionNode->usesEval()) && !m_codeBlock->isArrowFunction();
306     bool shouldCaptureSomeOfTheThings = m_shouldEmitDebugHooks || functionNode->needsActivation() || containsArrowOrEvalButNotInArrowBlock;
307
308     bool shouldCaptureAllOfTheThings = m_shouldEmitDebugHooks || codeBlock->usesEval();
309     bool needsArguments = ((functionNode->usesArguments() && !codeBlock->isArrowFunction()) || codeBlock->usesEval() || (functionNode->usesArrowFunction() && !codeBlock->isArrowFunction() && isArgumentsUsedInInnerArrowFunction()));
310
311     if (isGeneratorOrAsyncFunctionBodyParseMode(parseMode)) {
312         // Generator and AsyncFunction never provides "arguments". "arguments" reference will be resolved in an upper generator function scope.
313         needsArguments = false;
314
315         // Generator and AsyncFunction uses the var scope to save and resume its variables. So the lexical scope is always instantiated.
316         shouldCaptureSomeOfTheThings = true;
317     }
318
319     if (isGeneratorOrAsyncFunctionWrapperParseMode(parseMode) && needsArguments) {
320         // Generator does not provide "arguments". Instead, wrapping GeneratorFunction provides "arguments".
321         // This is because arguments of a generator should be evaluated before starting it.
322         // To workaround it, we evaluate these arguments as arguments of a wrapping generator function, and reference it from a generator.
323         //
324         //    function *gen(a, b = hello())
325         //    {
326         //        return {
327         //            @generatorNext: function (@generator, @generatorState, @generatorValue, @generatorResumeMode, @generatorFrame)
328         //            {
329         //                arguments;  // This `arguments` should reference to the gen's arguments.
330         //                ...
331         //            }
332         //        }
333         //    }
334         shouldCaptureSomeOfTheThings = true;
335     }
336
337     if (shouldCaptureAllOfTheThings)
338         functionNode->varDeclarations().markAllVariablesAsCaptured();
339     
340     auto captures = [&] (UniquedStringImpl* uid) -> bool {
341         if (!shouldCaptureSomeOfTheThings)
342             return false;
343         if (needsArguments && uid == propertyNames().arguments.impl()) {
344             // Actually, we only need to capture the arguments object when we "need full activation"
345             // because of name scopes. But historically we did it this way, so for now we just preserve
346             // the old behavior.
347             // FIXME: https://bugs.webkit.org/show_bug.cgi?id=143072
348             return true;
349         }
350         return functionNode->captures(uid);
351     };
352     auto varKind = [&] (UniquedStringImpl* uid) -> VarKind {
353         return captures(uid) ? VarKind::Scope : VarKind::Stack;
354     };
355
356     m_calleeRegister.setIndex(CallFrameSlot::callee);
357
358     initializeParameters(parameters);
359     ASSERT(!(isSimpleParameterList && m_restParameter));
360
361     emitEnter();
362
363     if (isGeneratorOrAsyncFunctionBodyParseMode(parseMode))
364         m_generatorRegister = &m_parameters[1];
365
366     allocateAndEmitScope();
367
368     emitCheckTraps();
369     
370     if (functionNameIsInScope(functionNode->ident(), functionNode->functionMode())) {
371         ASSERT(parseMode != SourceParseMode::GeneratorBodyMode);
372         ASSERT(!isAsyncFunctionBodyParseMode(parseMode));
373         bool isDynamicScope = functionNameScopeIsDynamic(codeBlock->usesEval(), codeBlock->isStrictMode());
374         bool isFunctionNameCaptured = captures(functionNode->ident().impl());
375         bool markAsCaptured = isDynamicScope || isFunctionNameCaptured;
376         emitPushFunctionNameScope(functionNode->ident(), &m_calleeRegister, markAsCaptured);
377     }
378
379     if (shouldCaptureSomeOfTheThings)
380         m_lexicalEnvironmentRegister = addVar();
381
382     if (shouldCaptureSomeOfTheThings || vm.typeProfiler())
383         symbolTableConstantIndex = addConstantValue(functionSymbolTable)->index();
384
385     // We can allocate the "var" environment if we don't have default parameter expressions. If we have
386     // default parameter expressions, we have to hold off on allocating the "var" environment because
387     // the parent scope of the "var" environment is the parameter environment.
388     if (isSimpleParameterList)
389         initializeVarLexicalEnvironment(symbolTableConstantIndex, functionSymbolTable, shouldCaptureSomeOfTheThings);
390
391     // Figure out some interesting facts about our arguments.
392     bool capturesAnyArgumentByName = false;
393     if (functionNode->hasCapturedVariables()) {
394         FunctionParameters& parameters = *functionNode->parameters();
395         for (size_t i = 0; i < parameters.size(); ++i) {
396             auto pattern = parameters.at(i).first;
397             if (!pattern->isBindingNode())
398                 continue;
399             const Identifier& ident = static_cast<const BindingNode*>(pattern)->boundProperty();
400             capturesAnyArgumentByName |= captures(ident.impl());
401         }
402     }
403     
404     if (capturesAnyArgumentByName)
405         ASSERT(m_lexicalEnvironmentRegister);
406
407     // Need to know what our functions are called. Parameters have some goofy behaviors when it
408     // comes to functions of the same name.
409     for (FunctionMetadataNode* function : functionNode->functionStack())
410         m_functions.add(function->ident().impl());
411     
412     if (needsArguments) {
413         // Create the arguments object now. We may put the arguments object into the activation if
414         // it is captured. Either way, we create two arguments object variables: one is our
415         // private variable that is immutable, and another that is the user-visible variable. The
416         // immutable one is only used here, or during formal parameter resolutions if we opt for
417         // DirectArguments.
418         
419         m_argumentsRegister = addVar();
420         m_argumentsRegister->ref();
421     }
422     
423     if (needsArguments && !codeBlock->isStrictMode() && isSimpleParameterList) {
424         // If we captured any formal parameter by name, then we use ScopedArguments. Otherwise we
425         // use DirectArguments. With ScopedArguments, we lift all of our arguments into the
426         // activation.
427         
428         if (capturesAnyArgumentByName) {
429             functionSymbolTable->setArgumentsLength(vm, parameters.size());
430             
431             // For each parameter, we have two possibilities:
432             // Either it's a binding node with no function overlap, in which case it gets a name
433             // in the symbol table - or it just gets space reserved in the symbol table. Either
434             // way we lift the value into the scope.
435             for (unsigned i = 0; i < parameters.size(); ++i) {
436                 ScopeOffset offset = functionSymbolTable->takeNextScopeOffset(NoLockingNecessary);
437                 functionSymbolTable->setArgumentOffset(vm, i, offset);
438                 if (UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first)) {
439                     VarOffset varOffset(offset);
440                     SymbolTableEntry entry(varOffset);
441                     // Stores to these variables via the ScopedArguments object will not do
442                     // notifyWrite(), since that would be cumbersome. Also, watching formal
443                     // parameters when "arguments" is in play is unlikely to be super profitable.
444                     // So, we just disable it.
445                     entry.disableWatching(*m_vm);
446                     functionSymbolTable->set(NoLockingNecessary, name, entry);
447                 }
448                 emitOpcode(op_put_to_scope);
449                 instructions().append(m_lexicalEnvironmentRegister->index());
450                 instructions().append(UINT_MAX);
451                 instructions().append(virtualRegisterForArgument(1 + i).offset());
452                 instructions().append(GetPutInfo(ThrowIfNotFound, LocalClosureVar, InitializationMode::NotInitialization).operand());
453                 instructions().append(symbolTableConstantIndex);
454                 instructions().append(offset.offset());
455             }
456             
457             // This creates a scoped arguments object and copies the overflow arguments into the
458             // scope. It's the equivalent of calling ScopedArguments::createByCopying().
459             emitOpcode(op_create_scoped_arguments);
460             instructions().append(m_argumentsRegister->index());
461             instructions().append(m_lexicalEnvironmentRegister->index());
462         } else {
463             // We're going to put all parameters into the DirectArguments object. First ensure
464             // that the symbol table knows that this is happening.
465             for (unsigned i = 0; i < parameters.size(); ++i) {
466                 if (UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first))
467                     functionSymbolTable->set(NoLockingNecessary, name, SymbolTableEntry(VarOffset(DirectArgumentsOffset(i))));
468             }
469             
470             emitOpcode(op_create_direct_arguments);
471             instructions().append(m_argumentsRegister->index());
472         }
473     } else if (isSimpleParameterList) {
474         // Create the formal parameters the normal way. Any of them could be captured, or not. If
475         // captured, lift them into the scope. We cannot do this if we have default parameter expressions
476         // because when default parameter expressions exist, they belong in their own lexical environment
477         // separate from the "var" lexical environment.
478         for (unsigned i = 0; i < parameters.size(); ++i) {
479             UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first);
480             if (!name)
481                 continue;
482             
483             if (!captures(name)) {
484                 // This is the easy case - just tell the symbol table about the argument. It will
485                 // be accessed directly.
486                 functionSymbolTable->set(NoLockingNecessary, name, SymbolTableEntry(VarOffset(virtualRegisterForArgument(1 + i))));
487                 continue;
488             }
489             
490             ScopeOffset offset = functionSymbolTable->takeNextScopeOffset(NoLockingNecessary);
491             const Identifier& ident =
492                 static_cast<const BindingNode*>(parameters.at(i).first)->boundProperty();
493             functionSymbolTable->set(NoLockingNecessary, name, SymbolTableEntry(VarOffset(offset)));
494             
495             emitOpcode(op_put_to_scope);
496             instructions().append(m_lexicalEnvironmentRegister->index());
497             instructions().append(addConstant(ident));
498             instructions().append(virtualRegisterForArgument(1 + i).offset());
499             instructions().append(GetPutInfo(ThrowIfNotFound, LocalClosureVar, InitializationMode::NotInitialization).operand());
500             instructions().append(symbolTableConstantIndex);
501             instructions().append(offset.offset());
502         }
503     }
504     
505     if (needsArguments && (codeBlock->isStrictMode() || !isSimpleParameterList)) {
506         // Allocate a cloned arguments object.
507         emitOpcode(op_create_cloned_arguments);
508         instructions().append(m_argumentsRegister->index());
509     }
510     
511     // There are some variables that need to be preinitialized to something other than Undefined:
512     //
513     // - "arguments": unless it's used as a function or parameter, this should refer to the
514     //   arguments object.
515     //
516     // - functions: these always override everything else.
517     //
518     // The most logical way to do all of this is to initialize none of the variables until now,
519     // and then initialize them in BytecodeGenerator::generate() in such an order that the rules
520     // for how these things override each other end up holding. We would initialize "arguments" first, 
521     // then all arguments, then the functions.
522     //
523     // But some arguments are already initialized by default, since if they aren't captured and we
524     // don't have "arguments" then we just point the symbol table at the stack slot of those
525     // arguments. We end up initializing the rest of the arguments that have an uncomplicated
526     // binding (i.e. don't involve destructuring) above when figuring out how to lay them out,
527     // because that's just the simplest thing. This means that when we initialize them, we have to
528     // watch out for the things that override arguments (namely, functions).
529     
530     // This is our final act of weirdness. "arguments" is overridden by everything except the
531     // callee. We add it to the symbol table if it's not already there and it's not an argument.
532     bool shouldCreateArgumentsVariableInParameterScope = false;
533     if (needsArguments) {
534         // If "arguments" is overridden by a function or destructuring parameter name, then it's
535         // OK for us to call createVariable() because it won't change anything. It's also OK for
536         // us to them tell BytecodeGenerator::generate() to write to it because it will do so
537         // before it initializes functions and destructuring parameters. But if "arguments" is
538         // overridden by a "simple" function parameter, then we have to bail: createVariable()
539         // would assert and BytecodeGenerator::generate() would write the "arguments" after the
540         // argument value had already been properly initialized.
541         
542         bool haveParameterNamedArguments = false;
543         for (unsigned i = 0; i < parameters.size(); ++i) {
544             UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first);
545             if (name == propertyNames().arguments.impl()) {
546                 haveParameterNamedArguments = true;
547                 break;
548             }
549         }
550
551         bool shouldCreateArgumensVariable = !haveParameterNamedArguments
552             && !SourceParseModeSet(SourceParseMode::ArrowFunctionMode, SourceParseMode::AsyncArrowFunctionMode).contains(m_codeBlock->parseMode());
553         shouldCreateArgumentsVariableInParameterScope = shouldCreateArgumensVariable && !isSimpleParameterList;
554         // Do not create arguments variable in case of Arrow function. Value will be loaded from parent scope
555         if (shouldCreateArgumensVariable && !shouldCreateArgumentsVariableInParameterScope) {
556             createVariable(
557                 propertyNames().arguments, varKind(propertyNames().arguments.impl()), functionSymbolTable);
558
559             m_needToInitializeArguments = true;
560         }
561     }
562
563     for (FunctionMetadataNode* function : functionNode->functionStack()) {
564         const Identifier& ident = function->ident();
565         createVariable(ident, varKind(ident.impl()), functionSymbolTable);
566         m_functionsToInitialize.append(std::make_pair(function, NormalFunctionVariable));
567     }
568     for (auto& entry : functionNode->varDeclarations()) {
569         ASSERT(!entry.value.isLet() && !entry.value.isConst());
570         if (!entry.value.isVar()) // This is either a parameter or callee.
571             continue;
572         if (shouldCreateArgumentsVariableInParameterScope && entry.key.get() == propertyNames().arguments.impl())
573             continue;
574         createVariable(Identifier::fromUid(m_vm, entry.key.get()), varKind(entry.key.get()), functionSymbolTable, IgnoreExisting);
575     }
576
577
578     m_newTargetRegister = addVar();
579     switch (parseMode) {
580     case SourceParseMode::GeneratorWrapperFunctionMode:
581     case SourceParseMode::GeneratorWrapperMethodMode:
582     case SourceParseMode::AsyncGeneratorWrapperMethodMode:
583     case SourceParseMode::AsyncGeneratorWrapperFunctionMode: {
584         m_generatorRegister = addVar();
585
586         // FIXME: Emit to_this only when Generator uses it.
587         // https://bugs.webkit.org/show_bug.cgi?id=151586
588         m_codeBlock->addPropertyAccessInstruction(instructions().size());
589         emitOpcode(op_to_this);
590         instructions().append(kill(&m_thisRegister));
591         instructions().append(0);
592         instructions().append(0);
593
594         emitMove(m_generatorRegister, &m_calleeRegister);
595         emitCreateThis(m_generatorRegister);
596         break;
597     }
598
599     case SourceParseMode::AsyncArrowFunctionMode:
600     case SourceParseMode::AsyncMethodMode:
601     case SourceParseMode::AsyncFunctionMode: {
602         ASSERT(!isConstructor());
603         ASSERT(constructorKind() == ConstructorKind::None);
604         m_generatorRegister = addVar();
605         m_promiseCapabilityRegister = addVar();
606
607         if (parseMode != SourceParseMode::AsyncArrowFunctionMode) {
608             // FIXME: Emit to_this only when AsyncFunctionBody uses it.
609             // https://bugs.webkit.org/show_bug.cgi?id=151586
610             m_codeBlock->addPropertyAccessInstruction(instructions().size());
611             emitOpcode(op_to_this);
612             instructions().append(kill(&m_thisRegister));
613             instructions().append(0);
614             instructions().append(0);
615         }
616
617         emitNewObject(m_generatorRegister);
618
619         // let promiseCapability be @newPromiseCapability(@Promise)
620         auto varNewPromiseCapability = variable(propertyNames().builtinNames().newPromiseCapabilityPrivateName());
621         RefPtr<RegisterID> scope = newTemporary();
622         moveToDestinationIfNeeded(scope.get(), emitResolveScope(scope.get(), varNewPromiseCapability));
623         RefPtr<RegisterID> newPromiseCapability = emitGetFromScope(newTemporary(), scope.get(), varNewPromiseCapability, ThrowIfNotFound);
624
625         CallArguments args(*this, nullptr, 1);
626         emitLoad(args.thisRegister(), jsUndefined());
627
628         auto varPromiseConstructor = variable(propertyNames().builtinNames().PromisePrivateName());
629         moveToDestinationIfNeeded(scope.get(), emitResolveScope(scope.get(), varPromiseConstructor));
630         emitGetFromScope(args.argumentRegister(0), scope.get(), varPromiseConstructor, ThrowIfNotFound);
631
632         // JSTextPosition(int _line, int _offset, int _lineStartOffset)
633         JSTextPosition divot(m_scopeNode->firstLine(), m_scopeNode->startOffset(), m_scopeNode->lineStartOffset());
634         emitCall(promiseCapabilityRegister(), newPromiseCapability.get(), NoExpectedFunction, args, divot, divot, divot, DebuggableCall::No);
635         break;
636     }
637
638     case SourceParseMode::AsyncGeneratorBodyMode:
639     case SourceParseMode::AsyncFunctionBodyMode:
640     case SourceParseMode::AsyncArrowFunctionBodyMode:
641     case SourceParseMode::GeneratorBodyMode: {
642         // |this| is already filled correctly before here.
643         emitLoad(m_newTargetRegister, jsUndefined());
644         break;
645     }
646
647     default: {
648         if (SourceParseMode::ArrowFunctionMode != parseMode) {
649             if (isConstructor()) {
650                 emitMove(m_newTargetRegister, &m_thisRegister);
651                 if (constructorKind() == ConstructorKind::Extends) {
652                     emitMoveEmptyValue(&m_thisRegister);
653                 } else
654                     emitCreateThis(&m_thisRegister);
655             } else if (constructorKind() != ConstructorKind::None)
656                 emitThrowTypeError("Cannot call a class constructor without |new|");
657             else {
658                 bool shouldEmitToThis = false;
659                 if (functionNode->usesThis() || codeBlock->usesEval() || m_scopeNode->doAnyInnerArrowFunctionsUseThis() || m_scopeNode->doAnyInnerArrowFunctionsUseEval())
660                     shouldEmitToThis = true;
661                 else if ((functionNode->usesSuperProperty() || m_scopeNode->doAnyInnerArrowFunctionsUseSuperProperty()) && !codeBlock->isStrictMode()) {
662                     // We must emit to_this when we're not in strict mode because we
663                     // will convert |this| to an object, and that object may be passed
664                     // to a strict function as |this|. This is observable because that
665                     // strict function's to_this will just return the object.
666                     //
667                     // We don't need to emit this for strict-mode code because
668                     // strict-mode code may call another strict function, which will
669                     // to_this if it directly uses this; this is OK, because we defer
670                     // to_this until |this| is used directly. Strict-mode code might
671                     // also call a sloppy mode function, and that will to_this, which
672                     // will defer the conversion, again, until necessary.
673                     shouldEmitToThis = true;
674                 }
675
676                 if (shouldEmitToThis) {
677                     m_codeBlock->addPropertyAccessInstruction(instructions().size());
678                     emitOpcode(op_to_this);
679                     instructions().append(kill(&m_thisRegister));
680                     instructions().append(0);
681                     instructions().append(0);
682                 }
683             }
684         }
685         break;
686     }
687     }
688
689     // We need load |super| & |this| for arrow function before initializeDefaultParameterValuesAndSetupFunctionScopeStack
690     // if we have default parameter expression. Because |super| & |this| values can be used there
691     if ((SourceParseModeSet(SourceParseMode::ArrowFunctionMode, SourceParseMode::AsyncArrowFunctionMode).contains(parseMode) && !isSimpleParameterList) || parseMode == SourceParseMode::AsyncArrowFunctionBodyMode) {
692         if (functionNode->usesThis() || functionNode->usesSuperProperty())
693             emitLoadThisFromArrowFunctionLexicalEnvironment();
694
695         if (m_scopeNode->usesNewTarget() || m_scopeNode->usesSuperCall())
696             emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
697     }
698
699     if (needsToUpdateArrowFunctionContext() && !codeBlock->isArrowFunction()) {
700         bool canReuseLexicalEnvironment = isSimpleParameterList;
701         initializeArrowFunctionContextScopeIfNeeded(functionSymbolTable, canReuseLexicalEnvironment);
702         emitPutThisToArrowFunctionContextScope();
703         emitPutNewTargetToArrowFunctionContextScope();
704         emitPutDerivedConstructorToArrowFunctionContextScope();
705     }
706
707     // All "addVar()"s needs to happen before "initializeDefaultParameterValuesAndSetupFunctionScopeStack()" is called
708     // because a function's default parameter ExpressionNodes will use temporary registers.
709     pushTDZVariables(*parentScopeTDZVariables, TDZCheckOptimization::DoNotOptimize, TDZRequirement::UnderTDZ);
710
711     Ref<Label> catchLabel = newLabel();
712     TryData* tryFormalParametersData = nullptr;
713     bool needTryCatch = isAsyncFunctionWrapperParseMode(parseMode) && !isSimpleParameterList;
714     if (needTryCatch) {
715         Ref<Label> tryFormalParametersStart = newEmittedLabel();
716         tryFormalParametersData = pushTry(tryFormalParametersStart.get(), catchLabel.get(), HandlerType::SynthesizedCatch);
717     }
718
719     initializeDefaultParameterValuesAndSetupFunctionScopeStack(parameters, isSimpleParameterList, functionNode, functionSymbolTable, symbolTableConstantIndex, captures, shouldCreateArgumentsVariableInParameterScope);
720
721     if (needTryCatch) {
722         Ref<Label> didNotThrow = newLabel();
723         emitJump(didNotThrow.get());
724         emitLabel(catchLabel.get());
725         popTry(tryFormalParametersData, catchLabel.get());
726
727         RefPtr<RegisterID> thrownValue = newTemporary();
728         RegisterID* unused = newTemporary();
729         emitCatch(unused, thrownValue.get(), tryFormalParametersData);
730
731         // return promiseCapability.@reject(thrownValue)
732         RefPtr<RegisterID> reject = emitGetById(newTemporary(), promiseCapabilityRegister(), m_vm->propertyNames->builtinNames().rejectPrivateName());
733
734         CallArguments args(*this, nullptr, 1);
735         emitLoad(args.thisRegister(), jsUndefined());
736         emitMove(args.argumentRegister(0), thrownValue.get());
737
738         JSTextPosition divot(functionNode->firstLine(), functionNode->startOffset(), functionNode->lineStartOffset());
739
740         RefPtr<RegisterID> result = emitCall(newTemporary(), reject.get(), NoExpectedFunction, args, divot, divot, divot, DebuggableCall::No);
741         emitReturn(emitGetById(newTemporary(), promiseCapabilityRegister(), m_vm->propertyNames->builtinNames().promisePrivateName()));
742
743         emitLabel(didNotThrow.get());
744     }
745
746     // If we don't have  default parameter expression, then loading |this| inside an arrow function must be done
747     // after initializeDefaultParameterValuesAndSetupFunctionScopeStack() because that function sets up the
748     // SymbolTable stack and emitLoadThisFromArrowFunctionLexicalEnvironment() consults the SymbolTable stack
749     if (SourceParseModeSet(SourceParseMode::ArrowFunctionMode, SourceParseMode::AsyncArrowFunctionMode).contains(parseMode) && isSimpleParameterList) {
750         if (functionNode->usesThis() || functionNode->usesSuperProperty())
751             emitLoadThisFromArrowFunctionLexicalEnvironment();
752     
753         if (m_scopeNode->usesNewTarget() || m_scopeNode->usesSuperCall())
754             emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
755     }
756     
757     // Set up the lexical environment scope as the generator frame. We store the saved and resumed generator registers into this scope with the symbol keys.
758     // Since they are symbol keyed, these variables cannot be reached from the usual code.
759     if (isGeneratorOrAsyncFunctionBodyParseMode(parseMode)) {
760         ASSERT(m_lexicalEnvironmentRegister);
761         m_generatorFrameSymbolTable.set(*m_vm, functionSymbolTable);
762         m_generatorFrameSymbolTableIndex = symbolTableConstantIndex;
763         emitMove(generatorFrameRegister(), m_lexicalEnvironmentRegister);
764         emitPutById(generatorRegister(), propertyNames().builtinNames().generatorFramePrivateName(), generatorFrameRegister());
765     }
766
767     bool shouldInitializeBlockScopedFunctions = false; // We generate top-level function declarations in ::generate().
768     pushLexicalScope(m_scopeNode, TDZCheckOptimization::Optimize, NestedScopeType::IsNotNested, nullptr, shouldInitializeBlockScopedFunctions);
769 }
770
771 BytecodeGenerator::BytecodeGenerator(VM& vm, EvalNode* evalNode, UnlinkedEvalCodeBlock* codeBlock, DebuggerMode debuggerMode, const VariableEnvironment* parentScopeTDZVariables)
772     : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
773     , m_scopeNode(evalNode)
774     , m_codeBlock(vm, codeBlock)
775     , m_thisRegister(CallFrame::thisArgumentOffset())
776     , m_codeType(EvalCode)
777     , m_vm(&vm)
778     , m_usesNonStrictEval(codeBlock->usesEval() && !codeBlock->isStrictMode())
779     , m_needsToUpdateArrowFunctionContext(evalNode->usesArrowFunction() || evalNode->usesEval())
780     , m_derivedContextType(codeBlock->derivedContextType())
781 {
782     for (auto& constantRegister : m_linkTimeConstantRegisters)
783         constantRegister = nullptr;
784
785     allocateCalleeSaveSpace();
786
787     m_codeBlock->setNumParameters(1);
788
789     pushTDZVariables(*parentScopeTDZVariables, TDZCheckOptimization::DoNotOptimize, TDZRequirement::UnderTDZ);
790
791     emitEnter();
792
793     allocateAndEmitScope();
794
795     emitCheckTraps();
796     
797     for (FunctionMetadataNode* function : evalNode->functionStack()) {
798         m_codeBlock->addFunctionDecl(makeFunction(function));
799         m_functionsToInitialize.append(std::make_pair(function, TopLevelFunctionVariable));
800     }
801
802     const VariableEnvironment& varDeclarations = evalNode->varDeclarations();
803     Vector<Identifier, 0, UnsafeVectorOverflow> variables;
804     Vector<Identifier, 0, UnsafeVectorOverflow> hoistedFunctions;
805     for (auto& entry : varDeclarations) {
806         ASSERT(entry.value.isVar());
807         ASSERT(entry.key->isAtomic() || entry.key->isSymbol());
808         if (entry.value.isSloppyModeHoistingCandidate())
809             hoistedFunctions.append(Identifier::fromUid(m_vm, entry.key.get()));
810         else
811             variables.append(Identifier::fromUid(m_vm, entry.key.get()));
812     }
813     codeBlock->adoptVariables(variables);
814     codeBlock->adoptFunctionHoistingCandidates(WTFMove(hoistedFunctions));
815     
816     if (evalNode->usesSuperCall() || evalNode->usesNewTarget())
817         m_newTargetRegister = addVar();
818
819     if (codeBlock->isArrowFunctionContext() && (evalNode->usesThis() || evalNode->usesSuperProperty()))
820         emitLoadThisFromArrowFunctionLexicalEnvironment();
821
822     if (evalNode->usesSuperCall() || evalNode->usesNewTarget())
823         emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
824
825     if (needsToUpdateArrowFunctionContext() && !codeBlock->isArrowFunctionContext() && !isDerivedConstructorContext()) {
826         initializeArrowFunctionContextScopeIfNeeded();
827         emitPutThisToArrowFunctionContextScope();
828     }
829     
830     bool shouldInitializeBlockScopedFunctions = false; // We generate top-level function declarations in ::generate().
831     pushLexicalScope(m_scopeNode, TDZCheckOptimization::Optimize, NestedScopeType::IsNotNested, nullptr, shouldInitializeBlockScopedFunctions);
832 }
833
834 BytecodeGenerator::BytecodeGenerator(VM& vm, ModuleProgramNode* moduleProgramNode, UnlinkedModuleProgramCodeBlock* codeBlock, DebuggerMode debuggerMode, const VariableEnvironment* parentScopeTDZVariables)
835     : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
836     , m_scopeNode(moduleProgramNode)
837     , m_codeBlock(vm, codeBlock)
838     , m_thisRegister(CallFrame::thisArgumentOffset())
839     , m_codeType(ModuleCode)
840     , m_vm(&vm)
841     , m_usesNonStrictEval(false)
842     , m_needsToUpdateArrowFunctionContext(moduleProgramNode->usesArrowFunction() || moduleProgramNode->usesEval())
843 {
844     ASSERT_UNUSED(parentScopeTDZVariables, !parentScopeTDZVariables->size());
845
846     for (auto& constantRegister : m_linkTimeConstantRegisters)
847         constantRegister = nullptr;
848
849     if (m_isBuiltinFunction)
850         m_shouldEmitDebugHooks = false;
851
852     allocateCalleeSaveSpace();
853
854     SymbolTable* moduleEnvironmentSymbolTable = SymbolTable::create(*m_vm);
855     moduleEnvironmentSymbolTable->setUsesNonStrictEval(m_usesNonStrictEval);
856     moduleEnvironmentSymbolTable->setScopeType(SymbolTable::ScopeType::LexicalScope);
857
858     bool shouldCaptureAllOfTheThings = m_shouldEmitDebugHooks || codeBlock->usesEval();
859     if (shouldCaptureAllOfTheThings)
860         moduleProgramNode->varDeclarations().markAllVariablesAsCaptured();
861
862     auto captures = [&] (UniquedStringImpl* uid) -> bool {
863         return moduleProgramNode->captures(uid);
864     };
865     auto lookUpVarKind = [&] (UniquedStringImpl* uid, const VariableEnvironmentEntry& entry) -> VarKind {
866         // Allocate the exported variables in the module environment.
867         if (entry.isExported())
868             return VarKind::Scope;
869
870         // Allocate the namespace variables in the module environment to instantiate
871         // it from the outside of the module code.
872         if (entry.isImportedNamespace())
873             return VarKind::Scope;
874
875         if (entry.isCaptured())
876             return VarKind::Scope;
877         return captures(uid) ? VarKind::Scope : VarKind::Stack;
878     };
879
880     emitEnter();
881
882     allocateAndEmitScope();
883
884     emitCheckTraps();
885     
886     m_calleeRegister.setIndex(CallFrameSlot::callee);
887
888     m_codeBlock->setNumParameters(1); // Allocate space for "this"
889
890     // Now declare all variables.
891
892     createVariable(m_vm->propertyNames->builtinNames().metaPrivateName(), VarKind::Scope, moduleEnvironmentSymbolTable, VerifyExisting);
893
894     for (auto& entry : moduleProgramNode->varDeclarations()) {
895         ASSERT(!entry.value.isLet() && !entry.value.isConst());
896         if (!entry.value.isVar()) // This is either a parameter or callee.
897             continue;
898         // Imported bindings are not allocated in the module environment as usual variables' way.
899         // These references remain the "Dynamic" in the unlinked code block. Later, when linking
900         // the code block, we resolve the reference to the "ModuleVar".
901         if (entry.value.isImported() && !entry.value.isImportedNamespace())
902             continue;
903         createVariable(Identifier::fromUid(m_vm, entry.key.get()), lookUpVarKind(entry.key.get(), entry.value), moduleEnvironmentSymbolTable, IgnoreExisting);
904     }
905
906     VariableEnvironment& lexicalVariables = moduleProgramNode->lexicalVariables();
907     instantiateLexicalVariables(lexicalVariables, moduleEnvironmentSymbolTable, ScopeRegisterType::Block, lookUpVarKind);
908
909     // We keep the symbol table in the constant pool.
910     RegisterID* constantSymbolTable = nullptr;
911     if (vm.typeProfiler())
912         constantSymbolTable = addConstantValue(moduleEnvironmentSymbolTable);
913     else
914         constantSymbolTable = addConstantValue(moduleEnvironmentSymbolTable->cloneScopePart(*m_vm));
915
916     pushTDZVariables(lexicalVariables, TDZCheckOptimization::Optimize, TDZRequirement::UnderTDZ);
917     bool isWithScope = false;
918     m_lexicalScopeStack.append({ moduleEnvironmentSymbolTable, m_topMostScope, isWithScope, constantSymbolTable->index() });
919     emitPrefillStackTDZVariables(lexicalVariables, moduleEnvironmentSymbolTable);
920
921     // makeFunction assumes that there's correct TDZ stack entries.
922     // So it should be called after putting our lexical environment to the TDZ stack correctly.
923
924     for (FunctionMetadataNode* function : moduleProgramNode->functionStack()) {
925         const auto& iterator = moduleProgramNode->varDeclarations().find(function->ident().impl());
926         RELEASE_ASSERT(iterator != moduleProgramNode->varDeclarations().end());
927         RELEASE_ASSERT(!iterator->value.isImported());
928
929         VarKind varKind = lookUpVarKind(iterator->key.get(), iterator->value);
930         if (varKind == VarKind::Scope) {
931             // http://www.ecma-international.org/ecma-262/6.0/#sec-moduledeclarationinstantiation
932             // Section 15.2.1.16.4, step 16-a-iv-1.
933             // All heap allocated function declarations should be instantiated when the module environment
934             // is created. They include the exported function declarations and not-exported-but-heap-allocated
935             // function declarations. This is required because exported function should be instantiated before
936             // executing the any module in the dependency graph. This enables the modules to link the imported
937             // bindings before executing the any module code.
938             //
939             // And since function declarations are instantiated before executing the module body code, the spec
940             // allows the functions inside the module to be executed before its module body is executed under
941             // the circular dependencies. The following is the example.
942             //
943             // Module A (executed first):
944             //    import { b } from "B";
945             //    // Here, the module "B" is not executed yet, but the function declaration is already instantiated.
946             //    // So we can call the function exported from "B".
947             //    b();
948             //
949             //    export function a() {
950             //    }
951             //
952             // Module B (executed second):
953             //    import { a } from "A";
954             //
955             //    export function b() {
956             //        c();
957             //    }
958             //
959             //    // c is not exported, but since it is referenced from the b, we should instantiate it before
960             //    // executing the "B" module code.
961             //    function c() {
962             //        a();
963             //    }
964             //
965             // Module EntryPoint (executed last):
966             //    import "B";
967             //    import "A";
968             //
969             m_codeBlock->addFunctionDecl(makeFunction(function));
970         } else {
971             // Stack allocated functions can be allocated when executing the module's body.
972             m_functionsToInitialize.append(std::make_pair(function, NormalFunctionVariable));
973         }
974     }
975
976     // Remember the constant register offset to the top-most symbol table. This symbol table will be
977     // cloned in the code block linking. After that, to create the module environment, we retrieve
978     // the cloned symbol table from the linked code block by using this offset.
979     codeBlock->setModuleEnvironmentSymbolTableConstantRegisterOffset(constantSymbolTable->index());
980 }
981
982 BytecodeGenerator::~BytecodeGenerator()
983 {
984 }
985
986 void BytecodeGenerator::initializeDefaultParameterValuesAndSetupFunctionScopeStack(
987     FunctionParameters& parameters, bool isSimpleParameterList, FunctionNode* functionNode, SymbolTable* functionSymbolTable, 
988     int symbolTableConstantIndex, const std::function<bool (UniquedStringImpl*)>& captures, bool shouldCreateArgumentsVariableInParameterScope)
989 {
990     Vector<std::pair<Identifier, RefPtr<RegisterID>>> valuesToMoveIntoVars;
991     ASSERT(!(isSimpleParameterList && shouldCreateArgumentsVariableInParameterScope));
992     if (!isSimpleParameterList) {
993         // Refer to the ES6 spec section 9.2.12: http://www.ecma-international.org/ecma-262/6.0/index.html#sec-functiondeclarationinstantiation
994         // This implements step 21.
995         VariableEnvironment environment;
996         Vector<Identifier> allParameterNames; 
997         for (unsigned i = 0; i < parameters.size(); i++)
998             parameters.at(i).first->collectBoundIdentifiers(allParameterNames);
999         if (shouldCreateArgumentsVariableInParameterScope)
1000             allParameterNames.append(propertyNames().arguments);
1001         IdentifierSet parameterSet;
1002         for (auto& ident : allParameterNames) {
1003             parameterSet.add(ident.impl());
1004             auto addResult = environment.add(ident);
1005             addResult.iterator->value.setIsLet(); // When we have default parameter expressions, parameters act like "let" variables.
1006             if (captures(ident.impl()))
1007                 addResult.iterator->value.setIsCaptured();
1008         }
1009         // This implements step 25 of section 9.2.12.
1010         pushLexicalScopeInternal(environment, TDZCheckOptimization::Optimize, NestedScopeType::IsNotNested, nullptr, TDZRequirement::UnderTDZ, ScopeType::LetConstScope, ScopeRegisterType::Block);
1011
1012         if (shouldCreateArgumentsVariableInParameterScope) {
1013             Variable argumentsVariable = variable(propertyNames().arguments); 
1014             initializeVariable(argumentsVariable, m_argumentsRegister);
1015             liftTDZCheckIfPossible(argumentsVariable);
1016         }
1017
1018         RefPtr<RegisterID> temp = newTemporary();
1019         for (unsigned i = 0; i < parameters.size(); i++) {
1020             std::pair<DestructuringPatternNode*, ExpressionNode*> parameter = parameters.at(i);
1021             if (parameter.first->isRestParameter())
1022                 continue;
1023             if ((i + 1) < m_parameters.size())
1024                 emitMove(temp.get(), &m_parameters[i + 1]);
1025             else
1026                 emitGetArgument(temp.get(), i);
1027             if (parameter.second) {
1028                 RefPtr<RegisterID> condition = emitIsUndefined(newTemporary(), temp.get());
1029                 Ref<Label> skipDefaultParameterBecauseNotUndefined = newLabel();
1030                 emitJumpIfFalse(condition.get(), skipDefaultParameterBecauseNotUndefined.get());
1031                 emitNode(temp.get(), parameter.second);
1032                 emitLabel(skipDefaultParameterBecauseNotUndefined.get());
1033             }
1034
1035             parameter.first->bindValue(*this, temp.get());
1036         }
1037
1038         // Final act of weirdness for default parameters. If a "var" also
1039         // has the same name as a parameter, it should start out as the
1040         // value of that parameter. Note, though, that they will be distinct
1041         // bindings.
1042         // This is step 28 of section 9.2.12. 
1043         for (auto& entry : functionNode->varDeclarations()) {
1044             if (!entry.value.isVar()) // This is either a parameter or callee.
1045                 continue;
1046
1047             if (parameterSet.contains(entry.key)) {
1048                 Identifier ident = Identifier::fromUid(m_vm, entry.key.get());
1049                 Variable var = variable(ident);
1050                 RegisterID* scope = emitResolveScope(nullptr, var);
1051                 RefPtr<RegisterID> value = emitGetFromScope(newTemporary(), scope, var, DoNotThrowIfNotFound);
1052                 valuesToMoveIntoVars.append(std::make_pair(ident, value));
1053             }
1054         }
1055
1056         // Functions with default parameter expressions must have a separate environment
1057         // record for parameters and "var"s. The "var" environment record must have the
1058         // parameter environment record as its parent.
1059         // See step 28 of section 9.2.12.
1060         bool hasCapturedVariables = !!m_lexicalEnvironmentRegister; 
1061         initializeVarLexicalEnvironment(symbolTableConstantIndex, functionSymbolTable, hasCapturedVariables);
1062     }
1063
1064     // This completes step 28 of section 9.2.12.
1065     for (unsigned i = 0; i < valuesToMoveIntoVars.size(); i++) {
1066         ASSERT(!isSimpleParameterList);
1067         Variable var = variable(valuesToMoveIntoVars[i].first);
1068         RegisterID* scope = emitResolveScope(nullptr, var);
1069         emitPutToScope(scope, var, valuesToMoveIntoVars[i].second.get(), DoNotThrowIfNotFound, InitializationMode::NotInitialization);
1070     }
1071 }
1072
1073 bool BytecodeGenerator::needsDerivedConstructorInArrowFunctionLexicalEnvironment()
1074 {
1075     ASSERT(m_codeBlock->isClassContext() || !(isConstructor() && constructorKind() == ConstructorKind::Extends));
1076     return m_codeBlock->isClassContext() && isSuperUsedInInnerArrowFunction();
1077 }
1078
1079 void BytecodeGenerator::initializeArrowFunctionContextScopeIfNeeded(SymbolTable* functionSymbolTable, bool canReuseLexicalEnvironment)
1080 {
1081     ASSERT(!m_arrowFunctionContextLexicalEnvironmentRegister);
1082
1083     if (canReuseLexicalEnvironment && m_lexicalEnvironmentRegister) {
1084         RELEASE_ASSERT(!m_codeBlock->isArrowFunction());
1085         RELEASE_ASSERT(functionSymbolTable);
1086
1087         m_arrowFunctionContextLexicalEnvironmentRegister = m_lexicalEnvironmentRegister;
1088         
1089         ScopeOffset offset;
1090         
1091         if (isThisUsedInInnerArrowFunction()) {
1092             offset = functionSymbolTable->takeNextScopeOffset(NoLockingNecessary);
1093             functionSymbolTable->set(NoLockingNecessary, propertyNames().thisIdentifier.impl(), SymbolTableEntry(VarOffset(offset)));
1094         }
1095
1096         if (m_codeType == FunctionCode && isNewTargetUsedInInnerArrowFunction()) {
1097             offset = functionSymbolTable->takeNextScopeOffset();
1098             functionSymbolTable->set(NoLockingNecessary, propertyNames().builtinNames().newTargetLocalPrivateName().impl(), SymbolTableEntry(VarOffset(offset)));
1099         }
1100         
1101         if (needsDerivedConstructorInArrowFunctionLexicalEnvironment()) {
1102             offset = functionSymbolTable->takeNextScopeOffset(NoLockingNecessary);
1103             functionSymbolTable->set(NoLockingNecessary, propertyNames().builtinNames().derivedConstructorPrivateName().impl(), SymbolTableEntry(VarOffset(offset)));
1104         }
1105
1106         return;
1107     }
1108
1109     VariableEnvironment environment;
1110
1111     if (isThisUsedInInnerArrowFunction()) {
1112         auto addResult = environment.add(propertyNames().thisIdentifier);
1113         addResult.iterator->value.setIsCaptured();
1114         addResult.iterator->value.setIsLet();
1115     }
1116     
1117     if (m_codeType == FunctionCode && isNewTargetUsedInInnerArrowFunction()) {
1118         auto addTarget = environment.add(propertyNames().builtinNames().newTargetLocalPrivateName());
1119         addTarget.iterator->value.setIsCaptured();
1120         addTarget.iterator->value.setIsLet();
1121     }
1122
1123     if (needsDerivedConstructorInArrowFunctionLexicalEnvironment()) {
1124         auto derivedConstructor = environment.add(propertyNames().builtinNames().derivedConstructorPrivateName());
1125         derivedConstructor.iterator->value.setIsCaptured();
1126         derivedConstructor.iterator->value.setIsLet();
1127     }
1128
1129     if (environment.size() > 0) {
1130         size_t size = m_lexicalScopeStack.size();
1131         pushLexicalScopeInternal(environment, TDZCheckOptimization::Optimize, NestedScopeType::IsNotNested, nullptr, TDZRequirement::UnderTDZ, ScopeType::LetConstScope, ScopeRegisterType::Block);
1132
1133         ASSERT_UNUSED(size, m_lexicalScopeStack.size() == size + 1);
1134
1135         m_arrowFunctionContextLexicalEnvironmentRegister = m_lexicalScopeStack.last().m_scope;
1136     }
1137 }
1138
1139 RegisterID* BytecodeGenerator::initializeNextParameter()
1140 {
1141     VirtualRegister reg = virtualRegisterForArgument(m_codeBlock->numParameters());
1142     m_parameters.grow(m_parameters.size() + 1);
1143     auto& parameter = registerFor(reg);
1144     parameter.setIndex(reg.offset());
1145     m_codeBlock->addParameter();
1146     return &parameter;
1147 }
1148
1149 void BytecodeGenerator::initializeParameters(FunctionParameters& parameters)
1150 {
1151     // Make sure the code block knows about all of our parameters, and make sure that parameters
1152     // needing destructuring are noted.
1153     m_thisRegister.setIndex(initializeNextParameter()->index()); // this
1154
1155     bool nonSimpleArguments = false;
1156     for (unsigned i = 0; i < parameters.size(); ++i) {
1157         auto parameter = parameters.at(i);
1158         auto pattern = parameter.first;
1159         if (pattern->isRestParameter()) {
1160             RELEASE_ASSERT(!m_restParameter);
1161             m_restParameter = static_cast<RestParameterNode*>(pattern);
1162             nonSimpleArguments = true;
1163             continue;
1164         }
1165         if (parameter.second) {
1166             nonSimpleArguments = true;
1167             continue;
1168         }
1169         if (!nonSimpleArguments)
1170             initializeNextParameter();
1171     }
1172 }
1173
1174 void BytecodeGenerator::initializeVarLexicalEnvironment(int symbolTableConstantIndex, SymbolTable* functionSymbolTable, bool hasCapturedVariables)
1175 {
1176     if (hasCapturedVariables) {
1177         RELEASE_ASSERT(m_lexicalEnvironmentRegister);
1178         emitOpcode(op_create_lexical_environment);
1179         instructions().append(m_lexicalEnvironmentRegister->index());
1180         instructions().append(scopeRegister()->index());
1181         instructions().append(symbolTableConstantIndex);
1182         instructions().append(addConstantValue(jsUndefined())->index());
1183
1184         emitOpcode(op_mov);
1185         instructions().append(scopeRegister()->index());
1186         instructions().append(m_lexicalEnvironmentRegister->index());
1187
1188         pushLocalControlFlowScope();
1189     }
1190     bool isWithScope = false;
1191     m_lexicalScopeStack.append({ functionSymbolTable, m_lexicalEnvironmentRegister, isWithScope, symbolTableConstantIndex });
1192     m_varScopeLexicalScopeStackIndex = m_lexicalScopeStack.size() - 1;
1193 }
1194
1195 UniquedStringImpl* BytecodeGenerator::visibleNameForParameter(DestructuringPatternNode* pattern)
1196 {
1197     if (pattern->isBindingNode()) {
1198         const Identifier& ident = static_cast<const BindingNode*>(pattern)->boundProperty();
1199         if (!m_functions.contains(ident.impl()))
1200             return ident.impl();
1201     }
1202     return nullptr;
1203 }
1204
1205 RegisterID* BytecodeGenerator::newRegister()
1206 {
1207     m_calleeLocals.append(virtualRegisterForLocal(m_calleeLocals.size()));
1208     int numCalleeLocals = max<int>(m_codeBlock->m_numCalleeLocals, m_calleeLocals.size());
1209     numCalleeLocals = WTF::roundUpToMultipleOf(stackAlignmentRegisters(), numCalleeLocals);
1210     m_codeBlock->m_numCalleeLocals = numCalleeLocals;
1211     return &m_calleeLocals.last();
1212 }
1213
1214 void BytecodeGenerator::reclaimFreeRegisters()
1215 {
1216     shrinkToFit(m_calleeLocals);
1217 }
1218
1219 RegisterID* BytecodeGenerator::newBlockScopeVariable()
1220 {
1221     reclaimFreeRegisters();
1222
1223     return newRegister();
1224 }
1225
1226 RegisterID* BytecodeGenerator::newTemporary()
1227 {
1228     reclaimFreeRegisters();
1229
1230     RegisterID* result = newRegister();
1231     result->setTemporary();
1232     return result;
1233 }
1234
1235 Ref<LabelScope> BytecodeGenerator::newLabelScope(LabelScope::Type type, const Identifier* name)
1236 {
1237     shrinkToFit(m_labelScopes);
1238
1239     // Allocate new label scope.
1240     m_labelScopes.append(type, name, labelScopeDepth(), newLabel(), type == LabelScope::Loop ? RefPtr<Label>(newLabel()) : RefPtr<Label>()); // Only loops have continue targets.
1241     return m_labelScopes.last();
1242 }
1243
1244 Ref<Label> BytecodeGenerator::newLabel()
1245 {
1246     shrinkToFit(m_labels);
1247
1248     // Allocate new label ID.
1249     m_labels.append();
1250     return m_labels.last();
1251 }
1252
1253 Ref<Label> BytecodeGenerator::newEmittedLabel()
1254 {
1255     Ref<Label> label = newLabel();
1256     emitLabel(label.get());
1257     return label;
1258 }
1259
1260 void BytecodeGenerator::emitLabel(Label& l0)
1261 {
1262     unsigned newLabelIndex = instructions().size();
1263     l0.setLocation(*this, newLabelIndex);
1264
1265     if (m_codeBlock->numberOfJumpTargets()) {
1266         unsigned lastLabelIndex = m_codeBlock->lastJumpTarget();
1267         ASSERT(lastLabelIndex <= newLabelIndex);
1268         if (newLabelIndex == lastLabelIndex) {
1269             // Peephole optimizations have already been disabled by emitting the last label
1270             return;
1271         }
1272     }
1273
1274     m_codeBlock->addJumpTarget(newLabelIndex);
1275
1276     // This disables peephole optimizations when an instruction is a jump target
1277     m_lastOpcodeID = op_end;
1278 }
1279
1280 void BytecodeGenerator::emitOpcode(OpcodeID opcodeID)
1281 {
1282 #ifndef NDEBUG
1283     size_t opcodePosition = instructions().size();
1284     ASSERT(opcodePosition - m_lastOpcodePosition == opcodeLength(m_lastOpcodeID) || m_lastOpcodeID == op_end);
1285     m_lastOpcodePosition = opcodePosition;
1286 #endif
1287     instructions().append(opcodeID);
1288     m_lastOpcodeID = opcodeID;
1289 }
1290
1291 UnlinkedArrayProfile BytecodeGenerator::newArrayProfile()
1292 {
1293     return m_codeBlock->addArrayProfile();
1294 }
1295
1296 UnlinkedArrayAllocationProfile BytecodeGenerator::newArrayAllocationProfile()
1297 {
1298     return m_codeBlock->addArrayAllocationProfile();
1299 }
1300
1301 UnlinkedObjectAllocationProfile BytecodeGenerator::newObjectAllocationProfile()
1302 {
1303     return m_codeBlock->addObjectAllocationProfile();
1304 }
1305
1306 UnlinkedValueProfile BytecodeGenerator::emitProfiledOpcode(OpcodeID opcodeID)
1307 {
1308     UnlinkedValueProfile result = m_codeBlock->addValueProfile();
1309     emitOpcode(opcodeID);
1310     return result;
1311 }
1312
1313 void BytecodeGenerator::emitEnter()
1314 {
1315     emitOpcode(op_enter);
1316 }
1317
1318 void BytecodeGenerator::emitLoopHint()
1319 {
1320     emitOpcode(op_loop_hint);
1321     emitCheckTraps();
1322 }
1323
1324 void BytecodeGenerator::emitCheckTraps()
1325 {
1326     emitOpcode(op_check_traps);
1327 }
1328
1329 void BytecodeGenerator::retrieveLastBinaryOp(int& dstIndex, int& src1Index, int& src2Index)
1330 {
1331     ASSERT(instructions().size() >= 4);
1332     size_t size = instructions().size();
1333     dstIndex = instructions().at(size - 3).u.operand;
1334     src1Index = instructions().at(size - 2).u.operand;
1335     src2Index = instructions().at(size - 1).u.operand;
1336 }
1337
1338 void BytecodeGenerator::retrieveLastUnaryOp(int& dstIndex, int& srcIndex)
1339 {
1340     ASSERT(instructions().size() >= 3);
1341     size_t size = instructions().size();
1342     dstIndex = instructions().at(size - 2).u.operand;
1343     srcIndex = instructions().at(size - 1).u.operand;
1344 }
1345
1346 void ALWAYS_INLINE BytecodeGenerator::rewindBinaryOp()
1347 {
1348     ASSERT(instructions().size() >= 4);
1349     instructions().shrink(instructions().size() - 4);
1350     m_lastOpcodeID = op_end;
1351 }
1352
1353 void ALWAYS_INLINE BytecodeGenerator::rewindUnaryOp()
1354 {
1355     ASSERT(instructions().size() >= 3);
1356     instructions().shrink(instructions().size() - 3);
1357     m_lastOpcodeID = op_end;
1358 }
1359
1360 void BytecodeGenerator::emitJump(Label& target)
1361 {
1362     size_t begin = instructions().size();
1363     emitOpcode(op_jmp);
1364     instructions().append(target.bind(begin, instructions().size()));
1365 }
1366
1367 void BytecodeGenerator::emitJumpIfTrue(RegisterID* cond, Label& target)
1368 {
1369     auto fuseCompareAndJump = [&] (OpcodeID jumpID) {
1370         int dstIndex;
1371         int src1Index;
1372         int src2Index;
1373
1374         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1375
1376         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1377             rewindBinaryOp();
1378
1379             size_t begin = instructions().size();
1380             emitOpcode(jumpID);
1381             instructions().append(src1Index);
1382             instructions().append(src2Index);
1383             instructions().append(target.bind(begin, instructions().size()));
1384             return true;
1385         }
1386         return false;
1387     };
1388
1389     if (m_lastOpcodeID == op_less) {
1390         if (fuseCompareAndJump(op_jless))
1391             return;
1392     } else if (m_lastOpcodeID == op_lesseq) {
1393         if (fuseCompareAndJump(op_jlesseq))
1394             return;
1395     } else if (m_lastOpcodeID == op_greater) {
1396         if (fuseCompareAndJump(op_jgreater))
1397             return;
1398     } else if (m_lastOpcodeID == op_greatereq) {
1399         if (fuseCompareAndJump(op_jgreatereq))
1400             return;
1401     } else if (m_lastOpcodeID == op_below) {
1402         if (fuseCompareAndJump(op_jbelow))
1403             return;
1404     } else if (m_lastOpcodeID == op_beloweq) {
1405         if (fuseCompareAndJump(op_jbeloweq))
1406             return;
1407     } else if (m_lastOpcodeID == op_eq_null && target.isForward()) {
1408         int dstIndex;
1409         int srcIndex;
1410
1411         retrieveLastUnaryOp(dstIndex, srcIndex);
1412
1413         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1414             rewindUnaryOp();
1415
1416             size_t begin = instructions().size();
1417             emitOpcode(op_jeq_null);
1418             instructions().append(srcIndex);
1419             instructions().append(target.bind(begin, instructions().size()));
1420             return;
1421         }
1422     } else if (m_lastOpcodeID == op_neq_null && target.isForward()) {
1423         int dstIndex;
1424         int srcIndex;
1425
1426         retrieveLastUnaryOp(dstIndex, srcIndex);
1427
1428         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1429             rewindUnaryOp();
1430
1431             size_t begin = instructions().size();
1432             emitOpcode(op_jneq_null);
1433             instructions().append(srcIndex);
1434             instructions().append(target.bind(begin, instructions().size()));
1435             return;
1436         }
1437     }
1438
1439     size_t begin = instructions().size();
1440
1441     emitOpcode(op_jtrue);
1442     instructions().append(cond->index());
1443     instructions().append(target.bind(begin, instructions().size()));
1444 }
1445
1446 void BytecodeGenerator::emitJumpIfFalse(RegisterID* cond, Label& target)
1447 {
1448     auto fuseCompareAndJump = [&] (OpcodeID jumpID, bool replaceOperands) {
1449         int dstIndex;
1450         int src1Index;
1451         int src2Index;
1452
1453         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1454
1455         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1456             rewindBinaryOp();
1457
1458             size_t begin = instructions().size();
1459             emitOpcode(jumpID);
1460             // Since op_below and op_beloweq only accepts Int32, replacing operands is not observable to users.
1461             if (replaceOperands)
1462                 std::swap(src1Index, src2Index);
1463             instructions().append(src1Index);
1464             instructions().append(src2Index);
1465             instructions().append(target.bind(begin, instructions().size()));
1466             return true;
1467         }
1468         return false;
1469     };
1470
1471     if (m_lastOpcodeID == op_less && target.isForward()) {
1472         if (fuseCompareAndJump(op_jnless, false))
1473             return;
1474     } else if (m_lastOpcodeID == op_lesseq && target.isForward()) {
1475         if (fuseCompareAndJump(op_jnlesseq, false))
1476             return;
1477     } else if (m_lastOpcodeID == op_greater && target.isForward()) {
1478         if (fuseCompareAndJump(op_jngreater, false))
1479             return;
1480     } else if (m_lastOpcodeID == op_greatereq && target.isForward()) {
1481         if (fuseCompareAndJump(op_jngreatereq, false))
1482             return;
1483     } else if (m_lastOpcodeID == op_below && target.isForward()) {
1484         if (fuseCompareAndJump(op_jbeloweq, true))
1485             return;
1486     } else if (m_lastOpcodeID == op_beloweq && target.isForward()) {
1487         if (fuseCompareAndJump(op_jbelow, true))
1488             return;
1489     } else if (m_lastOpcodeID == op_not) {
1490         int dstIndex;
1491         int srcIndex;
1492
1493         retrieveLastUnaryOp(dstIndex, srcIndex);
1494
1495         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1496             rewindUnaryOp();
1497
1498             size_t begin = instructions().size();
1499             emitOpcode(op_jtrue);
1500             instructions().append(srcIndex);
1501             instructions().append(target.bind(begin, instructions().size()));
1502             return;
1503         }
1504     } else if (m_lastOpcodeID == op_eq_null && target.isForward()) {
1505         int dstIndex;
1506         int srcIndex;
1507
1508         retrieveLastUnaryOp(dstIndex, srcIndex);
1509
1510         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1511             rewindUnaryOp();
1512
1513             size_t begin = instructions().size();
1514             emitOpcode(op_jneq_null);
1515             instructions().append(srcIndex);
1516             instructions().append(target.bind(begin, instructions().size()));
1517             return;
1518         }
1519     } else if (m_lastOpcodeID == op_neq_null && target.isForward()) {
1520         int dstIndex;
1521         int srcIndex;
1522
1523         retrieveLastUnaryOp(dstIndex, srcIndex);
1524
1525         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1526             rewindUnaryOp();
1527
1528             size_t begin = instructions().size();
1529             emitOpcode(op_jeq_null);
1530             instructions().append(srcIndex);
1531             instructions().append(target.bind(begin, instructions().size()));
1532             return;
1533         }
1534     }
1535
1536     size_t begin = instructions().size();
1537     emitOpcode(op_jfalse);
1538     instructions().append(cond->index());
1539     instructions().append(target.bind(begin, instructions().size()));
1540 }
1541
1542 void BytecodeGenerator::emitJumpIfNotFunctionCall(RegisterID* cond, Label& target)
1543 {
1544     size_t begin = instructions().size();
1545
1546     emitOpcode(op_jneq_ptr);
1547     instructions().append(cond->index());
1548     instructions().append(Special::CallFunction);
1549     instructions().append(target.bind(begin, instructions().size()));
1550     instructions().append(0);
1551 }
1552
1553 void BytecodeGenerator::emitJumpIfNotFunctionApply(RegisterID* cond, Label& target)
1554 {
1555     size_t begin = instructions().size();
1556
1557     emitOpcode(op_jneq_ptr);
1558     instructions().append(cond->index());
1559     instructions().append(Special::ApplyFunction);
1560     instructions().append(target.bind(begin, instructions().size()));
1561     instructions().append(0);
1562 }
1563
1564 bool BytecodeGenerator::hasConstant(const Identifier& ident) const
1565 {
1566     UniquedStringImpl* rep = ident.impl();
1567     return m_identifierMap.contains(rep);
1568 }
1569
1570 unsigned BytecodeGenerator::addConstant(const Identifier& ident)
1571 {
1572     UniquedStringImpl* rep = ident.impl();
1573     IdentifierMap::AddResult result = m_identifierMap.add(rep, m_codeBlock->numberOfIdentifiers());
1574     if (result.isNewEntry)
1575         m_codeBlock->addIdentifier(ident);
1576
1577     return result.iterator->value;
1578 }
1579
1580 // We can't hash JSValue(), so we use a dedicated data member to cache it.
1581 RegisterID* BytecodeGenerator::addConstantEmptyValue()
1582 {
1583     if (!m_emptyValueRegister) {
1584         int index = addConstantIndex();
1585         m_codeBlock->addConstant(JSValue());
1586         m_emptyValueRegister = &m_constantPoolRegisters[index];
1587     }
1588
1589     return m_emptyValueRegister;
1590 }
1591
1592 RegisterID* BytecodeGenerator::addConstantValue(JSValue v, SourceCodeRepresentation sourceCodeRepresentation)
1593 {
1594     if (!v)
1595         return addConstantEmptyValue();
1596
1597     int index = m_nextConstantOffset;
1598
1599     if (sourceCodeRepresentation == SourceCodeRepresentation::Double && v.isInt32())
1600         v = jsDoubleNumber(v.asNumber());
1601     EncodedJSValueWithRepresentation valueMapKey { JSValue::encode(v), sourceCodeRepresentation };
1602     JSValueMap::AddResult result = m_jsValueMap.add(valueMapKey, m_nextConstantOffset);
1603     if (result.isNewEntry) {
1604         addConstantIndex();
1605         m_codeBlock->addConstant(v, sourceCodeRepresentation);
1606     } else
1607         index = result.iterator->value;
1608     return &m_constantPoolRegisters[index];
1609 }
1610
1611 RegisterID* BytecodeGenerator::emitMoveLinkTimeConstant(RegisterID* dst, LinkTimeConstant type)
1612 {
1613     unsigned constantIndex = static_cast<unsigned>(type);
1614     if (!m_linkTimeConstantRegisters[constantIndex]) {
1615         int index = addConstantIndex();
1616         m_codeBlock->addConstant(type);
1617         m_linkTimeConstantRegisters[constantIndex] = &m_constantPoolRegisters[index];
1618     }
1619
1620     if (!dst)
1621         return m_linkTimeConstantRegisters[constantIndex];
1622
1623     emitOpcode(op_mov);
1624     instructions().append(dst->index());
1625     instructions().append(m_linkTimeConstantRegisters[constantIndex]->index());
1626
1627     return dst;
1628 }
1629
1630 unsigned BytecodeGenerator::addRegExp(RegExp* r)
1631 {
1632     return m_codeBlock->addRegExp(r);
1633 }
1634
1635 RegisterID* BytecodeGenerator::emitMoveEmptyValue(RegisterID* dst)
1636 {
1637     RefPtr<RegisterID> emptyValue = addConstantEmptyValue();
1638
1639     emitOpcode(op_mov);
1640     instructions().append(dst->index());
1641     instructions().append(emptyValue->index());
1642     return dst;
1643 }
1644
1645 RegisterID* BytecodeGenerator::emitMove(RegisterID* dst, RegisterID* src)
1646 {
1647     ASSERT(src != m_emptyValueRegister);
1648
1649     m_staticPropertyAnalyzer.mov(dst->index(), src->index());
1650     emitOpcode(op_mov);
1651     instructions().append(dst->index());
1652     instructions().append(src->index());
1653
1654     return dst;
1655 }
1656
1657 RegisterID* BytecodeGenerator::emitUnaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src)
1658 {
1659     ASSERT_WITH_MESSAGE(op_to_number != opcodeID, "op_to_number has a Value Profile.");
1660     ASSERT_WITH_MESSAGE(op_negate != opcodeID, "op_negate has an Arith Profile.");
1661     emitOpcode(opcodeID);
1662     instructions().append(dst->index());
1663     instructions().append(src->index());
1664
1665     return dst;
1666 }
1667
1668 RegisterID* BytecodeGenerator::emitUnaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src, OperandTypes types)
1669 {
1670     ASSERT_WITH_MESSAGE(op_to_number != opcodeID, "op_to_number has a Value Profile.");
1671     emitOpcode(opcodeID);
1672     instructions().append(dst->index());
1673     instructions().append(src->index());
1674
1675     if (opcodeID == op_negate)
1676         instructions().append(ArithProfile(types.first()).bits());
1677     return dst;
1678 }
1679
1680 RegisterID* BytecodeGenerator::emitUnaryOpProfiled(OpcodeID opcodeID, RegisterID* dst, RegisterID* src)
1681 {
1682     UnlinkedValueProfile profile = emitProfiledOpcode(opcodeID);
1683     instructions().append(dst->index());
1684     instructions().append(src->index());
1685     instructions().append(profile);
1686     return dst;
1687 }
1688
1689 RegisterID* BytecodeGenerator::emitInc(RegisterID* srcDst)
1690 {
1691     emitOpcode(op_inc);
1692     instructions().append(srcDst->index());
1693     return srcDst;
1694 }
1695
1696 RegisterID* BytecodeGenerator::emitDec(RegisterID* srcDst)
1697 {
1698     emitOpcode(op_dec);
1699     instructions().append(srcDst->index());
1700     return srcDst;
1701 }
1702
1703 RegisterID* BytecodeGenerator::emitBinaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2, OperandTypes types)
1704 {
1705     emitOpcode(opcodeID);
1706     instructions().append(dst->index());
1707     instructions().append(src1->index());
1708     instructions().append(src2->index());
1709
1710     if (opcodeID == op_bitor || opcodeID == op_bitand || opcodeID == op_bitxor ||
1711         opcodeID == op_add || opcodeID == op_mul || opcodeID == op_sub || opcodeID == op_div)
1712         instructions().append(ArithProfile(types.first(), types.second()).bits());
1713
1714     return dst;
1715 }
1716
1717 RegisterID* BytecodeGenerator::emitEqualityOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2)
1718 {
1719     if (m_lastOpcodeID == op_typeof) {
1720         int dstIndex;
1721         int srcIndex;
1722
1723         retrieveLastUnaryOp(dstIndex, srcIndex);
1724
1725         if (src1->index() == dstIndex
1726             && src1->isTemporary()
1727             && m_codeBlock->isConstantRegisterIndex(src2->index())
1728             && m_codeBlock->constantRegister(src2->index()).get().isString()) {
1729             const String& value = asString(m_codeBlock->constantRegister(src2->index()).get())->tryGetValue();
1730             if (value == "undefined") {
1731                 rewindUnaryOp();
1732                 emitOpcode(op_is_undefined);
1733                 instructions().append(dst->index());
1734                 instructions().append(srcIndex);
1735                 return dst;
1736             }
1737             if (value == "boolean") {
1738                 rewindUnaryOp();
1739                 emitOpcode(op_is_boolean);
1740                 instructions().append(dst->index());
1741                 instructions().append(srcIndex);
1742                 return dst;
1743             }
1744             if (value == "number") {
1745                 rewindUnaryOp();
1746                 emitOpcode(op_is_number);
1747                 instructions().append(dst->index());
1748                 instructions().append(srcIndex);
1749                 return dst;
1750             }
1751             if (value == "string") {
1752                 rewindUnaryOp();
1753                 emitOpcode(op_is_cell_with_type);
1754                 instructions().append(dst->index());
1755                 instructions().append(srcIndex);
1756                 instructions().append(StringType);
1757                 return dst;
1758             }
1759             if (value == "symbol") {
1760                 rewindUnaryOp();
1761                 emitOpcode(op_is_cell_with_type);
1762                 instructions().append(dst->index());
1763                 instructions().append(srcIndex);
1764                 instructions().append(SymbolType);
1765                 return dst;
1766             }
1767             if (value == "object") {
1768                 rewindUnaryOp();
1769                 emitOpcode(op_is_object_or_null);
1770                 instructions().append(dst->index());
1771                 instructions().append(srcIndex);
1772                 return dst;
1773             }
1774             if (value == "function") {
1775                 rewindUnaryOp();
1776                 emitOpcode(op_is_function);
1777                 instructions().append(dst->index());
1778                 instructions().append(srcIndex);
1779                 return dst;
1780             }
1781         }
1782     }
1783
1784     emitOpcode(opcodeID);
1785     instructions().append(dst->index());
1786     instructions().append(src1->index());
1787     instructions().append(src2->index());
1788     return dst;
1789 }
1790
1791 void BytecodeGenerator::emitTypeProfilerExpressionInfo(const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1792 {
1793     ASSERT(vm()->typeProfiler());
1794
1795     unsigned start = startDivot.offset; // Ranges are inclusive of their endpoints, AND 0 indexed.
1796     unsigned end = endDivot.offset - 1; // End Ranges already go one past the inclusive range, so subtract 1.
1797     unsigned instructionOffset = instructions().size() - 1;
1798     m_codeBlock->addTypeProfilerExpressionInfo(instructionOffset, start, end);
1799 }
1800
1801 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag flag)
1802 {
1803     if (!vm()->typeProfiler())
1804         return;
1805
1806     if (!registerToProfile)
1807         return;
1808
1809     emitOpcode(op_profile_type);
1810     instructions().append(registerToProfile->index());
1811     instructions().append(0);
1812     instructions().append(flag);
1813     instructions().append(0);
1814     instructions().append(resolveType());
1815
1816     // Don't emit expression info for this version of profile type. This generally means
1817     // we're profiling information for something that isn't in the actual text of a JavaScript
1818     // program. For example, implicit return undefined from a function call.
1819 }
1820
1821 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1822 {
1823     emitProfileType(registerToProfile, ProfileTypeBytecodeDoesNotHaveGlobalID, startDivot, endDivot);
1824 }
1825
1826 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag flag, const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1827 {
1828     if (!vm()->typeProfiler())
1829         return;
1830
1831     if (!registerToProfile)
1832         return;
1833
1834     // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType?
1835     emitOpcode(op_profile_type);
1836     instructions().append(registerToProfile->index());
1837     instructions().append(0);
1838     instructions().append(flag);
1839     instructions().append(0);
1840     instructions().append(resolveType());
1841
1842     emitTypeProfilerExpressionInfo(startDivot, endDivot);
1843 }
1844
1845 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, const Variable& var, const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1846 {
1847     if (!vm()->typeProfiler())
1848         return;
1849
1850     if (!registerToProfile)
1851         return;
1852
1853     ProfileTypeBytecodeFlag flag;
1854     int symbolTableOrScopeDepth;
1855     if (var.local() || var.offset().isScope()) {
1856         flag = ProfileTypeBytecodeLocallyResolved;
1857         ASSERT(var.symbolTableConstantIndex());
1858         symbolTableOrScopeDepth = var.symbolTableConstantIndex();
1859     } else {
1860         flag = ProfileTypeBytecodeClosureVar;
1861         symbolTableOrScopeDepth = localScopeDepth();
1862     }
1863
1864     // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType?
1865     emitOpcode(op_profile_type);
1866     instructions().append(registerToProfile->index());
1867     instructions().append(symbolTableOrScopeDepth);
1868     instructions().append(flag);
1869     instructions().append(addConstant(var.ident()));
1870     instructions().append(resolveType());
1871
1872     emitTypeProfilerExpressionInfo(startDivot, endDivot);
1873 }
1874
1875 void BytecodeGenerator::emitProfileControlFlow(int textOffset)
1876 {
1877     if (vm()->controlFlowProfiler()) {
1878         RELEASE_ASSERT(textOffset >= 0);
1879         size_t bytecodeOffset = instructions().size();
1880         m_codeBlock->addOpProfileControlFlowBytecodeOffset(bytecodeOffset);
1881
1882         emitOpcode(op_profile_control_flow);
1883         instructions().append(textOffset);
1884     }
1885 }
1886
1887 unsigned BytecodeGenerator::addConstantIndex()
1888 {
1889     unsigned index = m_nextConstantOffset;
1890     m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
1891     ++m_nextConstantOffset;
1892     return index;
1893 }
1894
1895 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, bool b)
1896 {
1897     return emitLoad(dst, jsBoolean(b));
1898 }
1899
1900 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, const Identifier& identifier)
1901 {
1902     ASSERT(!identifier.isSymbol());
1903     JSString*& stringInMap = m_stringMap.add(identifier.impl(), nullptr).iterator->value;
1904     if (!stringInMap)
1905         stringInMap = jsOwnedString(vm(), identifier.string());
1906
1907     return emitLoad(dst, JSValue(stringInMap));
1908 }
1909
1910 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, JSValue v, SourceCodeRepresentation sourceCodeRepresentation)
1911 {
1912     RegisterID* constantID = addConstantValue(v, sourceCodeRepresentation);
1913     if (dst)
1914         return emitMove(dst, constantID);
1915     return constantID;
1916 }
1917
1918 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, IdentifierSet& set)
1919 {
1920     for (const auto& entry : m_codeBlock->constantIdentifierSets()) {
1921         if (entry.first != set)
1922             continue;
1923         
1924         return &m_constantPoolRegisters[entry.second];
1925     }
1926     
1927     unsigned index = addConstantIndex();
1928     m_codeBlock->addSetConstant(set);
1929     RegisterID* m_setRegister = &m_constantPoolRegisters[index];
1930     
1931     if (dst)
1932         return emitMove(dst, m_setRegister);
1933     
1934     return m_setRegister;
1935 }
1936
1937 RegisterID* BytecodeGenerator::emitLoadGlobalObject(RegisterID* dst)
1938 {
1939     if (!m_globalObjectRegister) {
1940         int index = addConstantIndex();
1941         m_codeBlock->addConstant(JSValue());
1942         m_globalObjectRegister = &m_constantPoolRegisters[index];
1943         m_codeBlock->setGlobalObjectRegister(VirtualRegister(index));
1944     }
1945     if (dst)
1946         emitMove(dst, m_globalObjectRegister);
1947     return m_globalObjectRegister;
1948 }
1949
1950 template<typename LookUpVarKindFunctor>
1951 bool BytecodeGenerator::instantiateLexicalVariables(const VariableEnvironment& lexicalVariables, SymbolTable* symbolTable, ScopeRegisterType scopeRegisterType, LookUpVarKindFunctor lookUpVarKind)
1952 {
1953     bool hasCapturedVariables = false;
1954     {
1955         for (auto& entry : lexicalVariables) {
1956             ASSERT(entry.value.isLet() || entry.value.isConst() || entry.value.isFunction());
1957             ASSERT(!entry.value.isVar());
1958             SymbolTableEntry symbolTableEntry = symbolTable->get(NoLockingNecessary, entry.key.get());
1959             ASSERT(symbolTableEntry.isNull());
1960
1961             // Imported bindings which are not the namespace bindings are not allocated
1962             // in the module environment as usual variables' way.
1963             // And since these types of the variables only seen in the module environment,
1964             // other lexical environment need not to take care this.
1965             if (entry.value.isImported() && !entry.value.isImportedNamespace())
1966                 continue;
1967
1968             VarKind varKind = lookUpVarKind(entry.key.get(), entry.value);
1969             VarOffset varOffset;
1970             if (varKind == VarKind::Scope) {
1971                 varOffset = VarOffset(symbolTable->takeNextScopeOffset(NoLockingNecessary));
1972                 hasCapturedVariables = true;
1973             } else {
1974                 ASSERT(varKind == VarKind::Stack);
1975                 RegisterID* local;
1976                 if (scopeRegisterType == ScopeRegisterType::Block) {
1977                     local = newBlockScopeVariable();
1978                     local->ref();
1979                 } else
1980                     local = addVar();
1981                 varOffset = VarOffset(local->virtualRegister());
1982             }
1983
1984             SymbolTableEntry newEntry(varOffset, static_cast<unsigned>(entry.value.isConst() ? PropertyAttribute::ReadOnly : PropertyAttribute::None));
1985             symbolTable->add(NoLockingNecessary, entry.key.get(), newEntry);
1986         }
1987     }
1988     return hasCapturedVariables;
1989 }
1990
1991 void BytecodeGenerator::emitPrefillStackTDZVariables(const VariableEnvironment& lexicalVariables, SymbolTable* symbolTable)
1992 {
1993     // Prefill stack variables with the TDZ empty value.
1994     // Scope variables will be initialized to the TDZ empty value when JSLexicalEnvironment is allocated.
1995     for (auto& entry : lexicalVariables) {
1996         // Imported bindings which are not the namespace bindings are not allocated
1997         // in the module environment as usual variables' way.
1998         // And since these types of the variables only seen in the module environment,
1999         // other lexical environment need not to take care this.
2000         if (entry.value.isImported() && !entry.value.isImportedNamespace())
2001             continue;
2002
2003         if (entry.value.isFunction())
2004             continue;
2005
2006         SymbolTableEntry symbolTableEntry = symbolTable->get(NoLockingNecessary, entry.key.get());
2007         ASSERT(!symbolTableEntry.isNull());
2008         VarOffset offset = symbolTableEntry.varOffset();
2009         if (offset.isScope())
2010             continue;
2011
2012         ASSERT(offset.isStack());
2013         emitMoveEmptyValue(&registerFor(offset.stackOffset()));
2014     }
2015 }
2016
2017 void BytecodeGenerator::pushLexicalScope(VariableEnvironmentNode* node, TDZCheckOptimization tdzCheckOptimization, NestedScopeType nestedScopeType, RegisterID** constantSymbolTableResult, bool shouldInitializeBlockScopedFunctions)
2018 {
2019     VariableEnvironment& environment = node->lexicalVariables();
2020     RegisterID* constantSymbolTableResultTemp = nullptr;
2021     pushLexicalScopeInternal(environment, tdzCheckOptimization, nestedScopeType, &constantSymbolTableResultTemp, TDZRequirement::UnderTDZ, ScopeType::LetConstScope, ScopeRegisterType::Block);
2022
2023     if (shouldInitializeBlockScopedFunctions)
2024         initializeBlockScopedFunctions(environment, node->functionStack(), constantSymbolTableResultTemp);
2025
2026     if (constantSymbolTableResult && constantSymbolTableResultTemp)
2027         *constantSymbolTableResult = constantSymbolTableResultTemp;
2028 }
2029
2030 void BytecodeGenerator::pushLexicalScopeInternal(VariableEnvironment& environment, TDZCheckOptimization tdzCheckOptimization, NestedScopeType nestedScopeType,
2031     RegisterID** constantSymbolTableResult, TDZRequirement tdzRequirement, ScopeType scopeType, ScopeRegisterType scopeRegisterType)
2032 {
2033     if (!environment.size())
2034         return;
2035
2036     if (m_shouldEmitDebugHooks)
2037         environment.markAllVariablesAsCaptured();
2038
2039     SymbolTable* symbolTable = SymbolTable::create(*m_vm);
2040     switch (scopeType) {
2041     case ScopeType::CatchScope:
2042         symbolTable->setScopeType(SymbolTable::ScopeType::CatchScope);
2043         break;
2044     case ScopeType::LetConstScope:
2045         symbolTable->setScopeType(SymbolTable::ScopeType::LexicalScope);
2046         break;
2047     case ScopeType::FunctionNameScope:
2048         symbolTable->setScopeType(SymbolTable::ScopeType::FunctionNameScope);
2049         break;
2050     }
2051
2052     if (nestedScopeType == NestedScopeType::IsNested)
2053         symbolTable->markIsNestedLexicalScope();
2054
2055     auto lookUpVarKind = [] (UniquedStringImpl*, const VariableEnvironmentEntry& entry) -> VarKind {
2056         return entry.isCaptured() ? VarKind::Scope : VarKind::Stack;
2057     };
2058
2059     bool hasCapturedVariables = instantiateLexicalVariables(environment, symbolTable, scopeRegisterType, lookUpVarKind);
2060
2061     RegisterID* newScope = nullptr;
2062     RegisterID* constantSymbolTable = nullptr;
2063     int symbolTableConstantIndex = 0;
2064     if (vm()->typeProfiler()) {
2065         constantSymbolTable = addConstantValue(symbolTable);
2066         symbolTableConstantIndex = constantSymbolTable->index();
2067     }
2068     if (hasCapturedVariables) {
2069         if (scopeRegisterType == ScopeRegisterType::Block) {
2070             newScope = newBlockScopeVariable();
2071             newScope->ref();
2072         } else
2073             newScope = addVar();
2074         if (!constantSymbolTable) {
2075             ASSERT(!vm()->typeProfiler());
2076             constantSymbolTable = addConstantValue(symbolTable->cloneScopePart(*m_vm));
2077             symbolTableConstantIndex = constantSymbolTable->index();
2078         }
2079         if (constantSymbolTableResult)
2080             *constantSymbolTableResult = constantSymbolTable;
2081
2082         emitOpcode(op_create_lexical_environment);
2083         instructions().append(newScope->index());
2084         instructions().append(scopeRegister()->index());
2085         instructions().append(constantSymbolTable->index());
2086         instructions().append(addConstantValue(tdzRequirement == TDZRequirement::UnderTDZ ? jsTDZValue() : jsUndefined())->index());
2087
2088         emitMove(scopeRegister(), newScope);
2089
2090         pushLocalControlFlowScope();
2091     }
2092
2093     bool isWithScope = false;
2094     m_lexicalScopeStack.append({ symbolTable, newScope, isWithScope, symbolTableConstantIndex });
2095     pushTDZVariables(environment, tdzCheckOptimization, tdzRequirement);
2096
2097     if (tdzRequirement == TDZRequirement::UnderTDZ)
2098         emitPrefillStackTDZVariables(environment, symbolTable);
2099 }
2100
2101 void BytecodeGenerator::initializeBlockScopedFunctions(VariableEnvironment& environment, FunctionStack& functionStack, RegisterID* constantSymbolTable)
2102 {
2103     /*
2104      * We must transform block scoped function declarations in strict mode like so:
2105      *
2106      * function foo() {
2107      *     if (c) {
2108      *           function foo() { ... }
2109      *           if (bar) { ... }
2110      *           else { ... }
2111      *           function baz() { ... }
2112      *     }
2113      * }
2114      *
2115      * to:
2116      *
2117      * function foo() {
2118      *     if (c) {
2119      *         let foo = function foo() { ... }
2120      *         let baz = function baz() { ... }
2121      *         if (bar) { ... }
2122      *         else { ... }
2123      *     }
2124      * }
2125      * 
2126      * But without the TDZ checks.
2127     */
2128
2129     if (!environment.size()) {
2130         RELEASE_ASSERT(!functionStack.size());
2131         return;
2132     }
2133
2134     if (!functionStack.size())
2135         return;
2136
2137     SymbolTable* symbolTable = m_lexicalScopeStack.last().m_symbolTable;
2138     RegisterID* scope = m_lexicalScopeStack.last().m_scope;
2139     RefPtr<RegisterID> temp = newTemporary();
2140     int symbolTableIndex = constantSymbolTable ? constantSymbolTable->index() : 0;
2141     for (FunctionMetadataNode* function : functionStack) {
2142         const Identifier& name = function->ident();
2143         auto iter = environment.find(name.impl());
2144         RELEASE_ASSERT(iter != environment.end());
2145         RELEASE_ASSERT(iter->value.isFunction());
2146         // We purposefully don't hold the symbol table lock around this loop because emitNewFunctionExpressionCommon may GC.
2147         SymbolTableEntry entry = symbolTable->get(NoLockingNecessary, name.impl()); 
2148         RELEASE_ASSERT(!entry.isNull());
2149         emitNewFunctionExpressionCommon(temp.get(), function);
2150         bool isLexicallyScoped = true;
2151         emitPutToScope(scope, variableForLocalEntry(name, entry, symbolTableIndex, isLexicallyScoped), temp.get(), DoNotThrowIfNotFound, InitializationMode::Initialization);
2152     }
2153 }
2154
2155 void BytecodeGenerator::hoistSloppyModeFunctionIfNecessary(const Identifier& functionName)
2156 {
2157     if (m_scopeNode->hasSloppyModeHoistedFunction(functionName.impl())) {
2158         if (codeType() != EvalCode) {
2159             Variable currentFunctionVariable = variable(functionName);
2160             RefPtr<RegisterID> currentValue;
2161             if (RegisterID* local = currentFunctionVariable.local())
2162                 currentValue = local;
2163             else {
2164                 RefPtr<RegisterID> scope = emitResolveScope(nullptr, currentFunctionVariable);
2165                 currentValue = emitGetFromScope(newTemporary(), scope.get(), currentFunctionVariable, DoNotThrowIfNotFound);
2166             }
2167
2168             ASSERT(m_varScopeLexicalScopeStackIndex);
2169             ASSERT(*m_varScopeLexicalScopeStackIndex < m_lexicalScopeStack.size());
2170             LexicalScopeStackEntry varScope = m_lexicalScopeStack[*m_varScopeLexicalScopeStackIndex];
2171             SymbolTable* varSymbolTable = varScope.m_symbolTable;
2172             ASSERT(varSymbolTable->scopeType() == SymbolTable::ScopeType::VarScope);
2173             SymbolTableEntry entry = varSymbolTable->get(NoLockingNecessary, functionName.impl());
2174             if (functionName == propertyNames().arguments && entry.isNull()) {
2175                 // "arguments" might be put in the parameter scope when we have a non-simple
2176                 // parameter list since "arguments" is visible to expressions inside the
2177                 // parameter evaluation list.
2178                 // e.g:
2179                 // function foo(x = arguments) { { function arguments() { } } }
2180                 RELEASE_ASSERT(*m_varScopeLexicalScopeStackIndex > 0);
2181                 varScope = m_lexicalScopeStack[*m_varScopeLexicalScopeStackIndex - 1];
2182                 SymbolTable* parameterSymbolTable = varScope.m_symbolTable;
2183                 entry = parameterSymbolTable->get(NoLockingNecessary, functionName.impl());
2184             }
2185             RELEASE_ASSERT(!entry.isNull());
2186             bool isLexicallyScoped = false;
2187             emitPutToScope(varScope.m_scope, variableForLocalEntry(functionName, entry, varScope.m_symbolTableConstantIndex, isLexicallyScoped), currentValue.get(), DoNotThrowIfNotFound, InitializationMode::NotInitialization);
2188         } else {
2189             Variable currentFunctionVariable = variable(functionName);
2190             RefPtr<RegisterID> currentValue;
2191             if (RegisterID* local = currentFunctionVariable.local())
2192                 currentValue = local;
2193             else {
2194                 RefPtr<RegisterID> scope = emitResolveScope(nullptr, currentFunctionVariable);
2195                 currentValue = emitGetFromScope(newTemporary(), scope.get(), currentFunctionVariable, DoNotThrowIfNotFound);
2196             }
2197
2198             RefPtr<RegisterID> scopeId = emitResolveScopeForHoistingFuncDeclInEval(nullptr, functionName);
2199             RefPtr<RegisterID> checkResult = emitIsUndefined(newTemporary(), scopeId.get());
2200             
2201             Ref<Label> isNotVarScopeLabel = newLabel();
2202             emitJumpIfTrue(checkResult.get(), isNotVarScopeLabel.get());
2203
2204             // Put to outer scope
2205             emitPutToScope(scopeId.get(), functionName, currentValue.get(), DoNotThrowIfNotFound, InitializationMode::NotInitialization);
2206             emitLabel(isNotVarScopeLabel.get());
2207
2208         }
2209     }
2210 }
2211
2212 RegisterID* BytecodeGenerator::emitResolveScopeForHoistingFuncDeclInEval(RegisterID* dst, const Identifier& property)
2213 {
2214     ASSERT(m_codeType == EvalCode);
2215
2216     dst = finalDestination(dst);
2217     emitOpcode(op_resolve_scope_for_hoisting_func_decl_in_eval);
2218     instructions().append(kill(dst));
2219     instructions().append(m_topMostScope->index());
2220     instructions().append(addConstant(property));
2221     return dst;
2222 }
2223
2224 void BytecodeGenerator::popLexicalScope(VariableEnvironmentNode* node)
2225 {
2226     VariableEnvironment& environment = node->lexicalVariables();
2227     popLexicalScopeInternal(environment);
2228 }
2229
2230 void BytecodeGenerator::popLexicalScopeInternal(VariableEnvironment& environment)
2231 {
2232     // NOTE: This function only makes sense for scopes that aren't ScopeRegisterType::Var (only function name scope right now is ScopeRegisterType::Var).
2233     // This doesn't make sense for ScopeRegisterType::Var because we deref RegisterIDs here.
2234     if (!environment.size())
2235         return;
2236
2237     if (m_shouldEmitDebugHooks)
2238         environment.markAllVariablesAsCaptured();
2239
2240     auto stackEntry = m_lexicalScopeStack.takeLast();
2241     SymbolTable* symbolTable = stackEntry.m_symbolTable;
2242     bool hasCapturedVariables = false;
2243     for (auto& entry : environment) {
2244         if (entry.value.isCaptured()) {
2245             hasCapturedVariables = true;
2246             continue;
2247         }
2248         SymbolTableEntry symbolTableEntry = symbolTable->get(NoLockingNecessary, entry.key.get());
2249         ASSERT(!symbolTableEntry.isNull());
2250         VarOffset offset = symbolTableEntry.varOffset();
2251         ASSERT(offset.isStack());
2252         RegisterID* local = &registerFor(offset.stackOffset());
2253         local->deref();
2254     }
2255
2256     if (hasCapturedVariables) {
2257         RELEASE_ASSERT(stackEntry.m_scope);
2258         emitPopScope(scopeRegister(), stackEntry.m_scope);
2259         popLocalControlFlowScope();
2260         stackEntry.m_scope->deref();
2261     }
2262
2263     m_TDZStack.removeLast();
2264 }
2265
2266 void BytecodeGenerator::prepareLexicalScopeForNextForLoopIteration(VariableEnvironmentNode* node, RegisterID* loopSymbolTable)
2267 {
2268     VariableEnvironment& environment = node->lexicalVariables();
2269     if (!environment.size())
2270         return;
2271     if (m_shouldEmitDebugHooks)
2272         environment.markAllVariablesAsCaptured();
2273     if (!environment.hasCapturedVariables())
2274         return;
2275
2276     RELEASE_ASSERT(loopSymbolTable);
2277
2278     // This function needs to do setup for a for loop's activation if any of
2279     // the for loop's lexically declared variables are captured (that is, variables
2280     // declared in the loop header, not the loop body). This function needs to
2281     // make a copy of the current activation and copy the values from the previous
2282     // activation into the new activation because each iteration of a for loop
2283     // gets a new activation.
2284
2285     auto stackEntry = m_lexicalScopeStack.last();
2286     SymbolTable* symbolTable = stackEntry.m_symbolTable;
2287     RegisterID* loopScope = stackEntry.m_scope;
2288     ASSERT(symbolTable->scopeSize());
2289     ASSERT(loopScope);
2290     Vector<std::pair<RegisterID*, Identifier>> activationValuesToCopyOver;
2291
2292     {
2293         activationValuesToCopyOver.reserveInitialCapacity(symbolTable->scopeSize());
2294
2295         for (auto end = symbolTable->end(NoLockingNecessary), ptr = symbolTable->begin(NoLockingNecessary); ptr != end; ++ptr) {
2296             if (!ptr->value.varOffset().isScope())
2297                 continue;
2298
2299             RefPtr<UniquedStringImpl> ident = ptr->key;
2300             Identifier identifier = Identifier::fromUid(m_vm, ident.get());
2301
2302             RegisterID* transitionValue = newBlockScopeVariable();
2303             transitionValue->ref();
2304             emitGetFromScope(transitionValue, loopScope, variableForLocalEntry(identifier, ptr->value, loopSymbolTable->index(), true), DoNotThrowIfNotFound);
2305             activationValuesToCopyOver.uncheckedAppend(std::make_pair(transitionValue, identifier));
2306         }
2307     }
2308
2309     // We need this dynamic behavior of the executing code to ensure
2310     // each loop iteration has a new activation object. (It's pretty ugly).
2311     // Also, this new activation needs to be assigned to the same register
2312     // as the previous scope because the loop body is compiled under
2313     // the assumption that the scope's register index is constant even
2314     // though the value in that register will change on each loop iteration.
2315     RefPtr<RegisterID> parentScope = emitGetParentScope(newTemporary(), loopScope);
2316     emitMove(scopeRegister(), parentScope.get());
2317
2318     emitOpcode(op_create_lexical_environment);
2319     instructions().append(loopScope->index());
2320     instructions().append(scopeRegister()->index());
2321     instructions().append(loopSymbolTable->index());
2322     instructions().append(addConstantValue(jsTDZValue())->index());
2323
2324     emitMove(scopeRegister(), loopScope);
2325
2326     {
2327         for (auto pair : activationValuesToCopyOver) {
2328             const Identifier& identifier = pair.second;
2329             SymbolTableEntry entry = symbolTable->get(NoLockingNecessary, identifier.impl());
2330             RELEASE_ASSERT(!entry.isNull());
2331             RegisterID* transitionValue = pair.first;
2332             emitPutToScope(loopScope, variableForLocalEntry(identifier, entry, loopSymbolTable->index(), true), transitionValue, DoNotThrowIfNotFound, InitializationMode::NotInitialization);
2333             transitionValue->deref();
2334         }
2335     }
2336 }
2337
2338 Variable BytecodeGenerator::variable(const Identifier& property, ThisResolutionType thisResolutionType)
2339 {
2340     if (property == propertyNames().thisIdentifier && thisResolutionType == ThisResolutionType::Local)
2341         return Variable(property, VarOffset(thisRegister()->virtualRegister()), thisRegister(), static_cast<unsigned>(PropertyAttribute::ReadOnly), Variable::SpecialVariable, 0, false);
2342     
2343     // We can optimize lookups if the lexical variable is found before a "with" or "catch"
2344     // scope because we're guaranteed static resolution. If we have to pass through
2345     // a "with" or "catch" scope we loose this guarantee.
2346     // We can't optimize cases like this:
2347     // {
2348     //     let x = ...;
2349     //     with (o) {
2350     //         doSomethingWith(x);
2351     //     }
2352     // }
2353     // Because we can't gaurantee static resolution on x.
2354     // But, in this case, we are guaranteed static resolution:
2355     // {
2356     //     let x = ...;
2357     //     with (o) {
2358     //         let x = ...;
2359     //         doSomethingWith(x);
2360     //     }
2361     // }
2362     for (unsigned i = m_lexicalScopeStack.size(); i--; ) {
2363         auto& stackEntry = m_lexicalScopeStack[i];
2364         if (stackEntry.m_isWithScope)
2365             return Variable(property);
2366         SymbolTable* symbolTable = stackEntry.m_symbolTable;
2367         SymbolTableEntry symbolTableEntry = symbolTable->get(NoLockingNecessary, property.impl());
2368         if (symbolTableEntry.isNull())
2369             continue;
2370         bool resultIsCallee = false;
2371         if (symbolTable->scopeType() == SymbolTable::ScopeType::FunctionNameScope) {
2372             if (m_usesNonStrictEval) {
2373                 // We don't know if an eval has introduced a "var" named the same thing as the function name scope variable name.
2374                 // We resort to dynamic lookup to answer this question.
2375                 Variable result = Variable(property);
2376                 return result;
2377             }
2378             resultIsCallee = true;
2379         }
2380         Variable result = variableForLocalEntry(property, symbolTableEntry, stackEntry.m_symbolTableConstantIndex, symbolTable->scopeType() == SymbolTable::ScopeType::LexicalScope);
2381         if (resultIsCallee)
2382             result.setIsReadOnly();
2383         return result;
2384     }
2385     
2386     return Variable(property);
2387 }
2388
2389 Variable BytecodeGenerator::variableForLocalEntry(
2390     const Identifier& property, const SymbolTableEntry& entry, int symbolTableConstantIndex, bool isLexicallyScoped)
2391 {
2392     VarOffset offset = entry.varOffset();
2393     
2394     RegisterID* local;
2395     if (offset.isStack())
2396         local = &registerFor(offset.stackOffset());
2397     else
2398         local = nullptr;
2399     
2400     return Variable(property, offset, local, entry.getAttributes(), Variable::NormalVariable, symbolTableConstantIndex, isLexicallyScoped);
2401 }
2402
2403 void BytecodeGenerator::createVariable(
2404     const Identifier& property, VarKind varKind, SymbolTable* symbolTable, ExistingVariableMode existingVariableMode)
2405 {
2406     ASSERT(property != propertyNames().thisIdentifier);
2407     SymbolTableEntry entry = symbolTable->get(NoLockingNecessary, property.impl());
2408     
2409     if (!entry.isNull()) {
2410         if (existingVariableMode == IgnoreExisting)
2411             return;
2412         
2413         // Do some checks to ensure that the variable we're being asked to create is sufficiently
2414         // compatible with the one we have already created.
2415
2416         VarOffset offset = entry.varOffset();
2417         
2418         // We can't change our minds about whether it's captured.
2419         if (offset.kind() != varKind) {
2420             dataLog(
2421                 "Trying to add variable called ", property, " as ", varKind,
2422                 " but it was already added as ", offset, ".\n");
2423             RELEASE_ASSERT_NOT_REACHED();
2424         }
2425
2426         return;
2427     }
2428     
2429     VarOffset varOffset;
2430     if (varKind == VarKind::Scope)
2431         varOffset = VarOffset(symbolTable->takeNextScopeOffset(NoLockingNecessary));
2432     else {
2433         ASSERT(varKind == VarKind::Stack);
2434         varOffset = VarOffset(virtualRegisterForLocal(m_calleeLocals.size()));
2435     }
2436     SymbolTableEntry newEntry(varOffset, 0);
2437     symbolTable->add(NoLockingNecessary, property.impl(), newEntry);
2438     
2439     if (varKind == VarKind::Stack) {
2440         RegisterID* local = addVar();
2441         RELEASE_ASSERT(local->index() == varOffset.stackOffset().offset());
2442     }
2443 }
2444
2445 RegisterID* BytecodeGenerator::emitOverridesHasInstance(RegisterID* dst, RegisterID* constructor, RegisterID* hasInstanceValue)
2446 {
2447     emitOpcode(op_overrides_has_instance);
2448     instructions().append(dst->index());
2449     instructions().append(constructor->index());
2450     instructions().append(hasInstanceValue->index());
2451     return dst;
2452 }
2453
2454 // Indicates the least upper bound of resolve type based on local scope. The bytecode linker
2455 // will start with this ResolveType and compute the least upper bound including intercepting scopes.
2456 ResolveType BytecodeGenerator::resolveType()
2457 {
2458     for (unsigned i = m_lexicalScopeStack.size(); i--; ) {
2459         if (m_lexicalScopeStack[i].m_isWithScope)
2460             return Dynamic;
2461         if (m_usesNonStrictEval && m_lexicalScopeStack[i].m_symbolTable->scopeType() == SymbolTable::ScopeType::FunctionNameScope) {
2462             // We never want to assign to a FunctionNameScope. Returning Dynamic here achieves this goal.
2463             // If we aren't in non-strict eval mode, then NodesCodeGen needs to take care not to emit
2464             // a put_to_scope with the destination being the function name scope variable.
2465             return Dynamic;
2466         }
2467     }
2468
2469     if (m_usesNonStrictEval)
2470         return GlobalPropertyWithVarInjectionChecks;
2471     return GlobalProperty;
2472 }
2473
2474 RegisterID* BytecodeGenerator::emitResolveScope(RegisterID* dst, const Variable& variable)
2475 {
2476     switch (variable.offset().kind()) {
2477     case VarKind::Stack:
2478         return nullptr;
2479         
2480     case VarKind::DirectArgument:
2481         return argumentsRegister();
2482         
2483     case VarKind::Scope: {
2484         // This always refers to the activation that *we* allocated, and not the current scope that code
2485         // lives in. Note that this will change once we have proper support for block scoping. Once that
2486         // changes, it will be correct for this code to return scopeRegister(). The only reason why we
2487         // don't do that already is that m_lexicalEnvironment is required by ConstDeclNode. ConstDeclNode
2488         // requires weird things because it is a shameful pile of nonsense, but block scoping would make
2489         // that code sensible and obviate the need for us to do bad things.
2490         for (unsigned i = m_lexicalScopeStack.size(); i--; ) {
2491             auto& stackEntry = m_lexicalScopeStack[i];
2492             // We should not resolve a variable to VarKind::Scope if a "with" scope lies in between the current
2493             // scope and the resolved scope.
2494             RELEASE_ASSERT(!stackEntry.m_isWithScope);
2495
2496             if (stackEntry.m_symbolTable->get(NoLockingNecessary, variable.ident().impl()).isNull())
2497                 continue;
2498             
2499             RegisterID* scope = stackEntry.m_scope;
2500             RELEASE_ASSERT(scope);
2501             return scope;
2502         }
2503
2504         RELEASE_ASSERT_NOT_REACHED();
2505         return nullptr;
2506         
2507     }
2508     case VarKind::Invalid:
2509         // Indicates non-local resolution.
2510         
2511         m_codeBlock->addPropertyAccessInstruction(instructions().size());
2512         
2513         // resolve_scope dst, id, ResolveType, depth
2514         dst = tempDestination(dst);
2515         emitOpcode(op_resolve_scope);
2516         instructions().append(kill(dst));
2517         instructions().append(scopeRegister()->index());
2518         instructions().append(addConstant(variable.ident()));
2519         instructions().append(resolveType());
2520         instructions().append(localScopeDepth());
2521         instructions().append(0);
2522         return dst;
2523     }
2524     
2525     RELEASE_ASSERT_NOT_REACHED();
2526     return nullptr;
2527 }
2528
2529 RegisterID* BytecodeGenerator::emitGetFromScope(RegisterID* dst, RegisterID* scope, const Variable& variable, ResolveMode resolveMode)
2530 {
2531     switch (variable.offset().kind()) {
2532     case VarKind::Stack:
2533         return emitMove(dst, variable.local());
2534         
2535     case VarKind::DirectArgument: {
2536         UnlinkedValueProfile profile = emitProfiledOpcode(op_get_from_arguments);
2537         instructions().append(kill(dst));
2538         instructions().append(scope->index());
2539         instructions().append(variable.offset().capturedArgumentsOffset().offset());
2540         instructions().append(profile);
2541         return dst;
2542     }
2543         
2544     case VarKind::Scope:
2545     case VarKind::Invalid: {
2546         m_codeBlock->addPropertyAccessInstruction(instructions().size());
2547         
2548         // get_from_scope dst, scope, id, GetPutInfo, Structure, Operand
2549         UnlinkedValueProfile profile = emitProfiledOpcode(op_get_from_scope);
2550         instructions().append(kill(dst));
2551         instructions().append(scope->index());
2552         instructions().append(addConstant(variable.ident()));
2553         instructions().append(GetPutInfo(resolveMode, variable.offset().isScope() ? LocalClosureVar : resolveType(), InitializationMode::NotInitialization).operand());
2554         instructions().append(localScopeDepth());
2555         instructions().append(variable.offset().isScope() ? variable.offset().scopeOffset().offset() : 0);
2556         instructions().append(profile);
2557         return dst;
2558     } }
2559     
2560     RELEASE_ASSERT_NOT_REACHED();
2561 }
2562
2563 RegisterID* BytecodeGenerator::emitPutToScope(RegisterID* scope, const Variable& variable, RegisterID* value, ResolveMode resolveMode, InitializationMode initializationMode)
2564 {
2565     switch (variable.offset().kind()) {
2566     case VarKind::Stack:
2567         emitMove(variable.local(), value);
2568         return value;
2569         
2570     case VarKind::DirectArgument:
2571         emitOpcode(op_put_to_arguments);
2572         instructions().append(scope->index());
2573         instructions().append(variable.offset().capturedArgumentsOffset().offset());
2574         instructions().append(value->index());
2575         return value;
2576         
2577     case VarKind::Scope:
2578     case VarKind::Invalid: {
2579         m_codeBlock->addPropertyAccessInstruction(instructions().size());
2580         
2581         // put_to_scope scope, id, value, GetPutInfo, Structure, Operand
2582         emitOpcode(op_put_to_scope);
2583         instructions().append(scope->index());
2584         instructions().append(addConstant(variable.ident()));
2585         instructions().append(value->index());
2586         ScopeOffset offset;
2587         if (variable.offset().isScope()) {
2588             offset = variable.offset().scopeOffset();
2589             instructions().append(GetPutInfo(resolveMode, LocalClosureVar, initializationMode).operand());
2590             instructions().append(variable.symbolTableConstantIndex());
2591         } else {
2592             ASSERT(resolveType() != LocalClosureVar);
2593             instructions().append(GetPutInfo(resolveMode, resolveType(), initializationMode).operand());
2594             instructions().append(localScopeDepth());
2595         }
2596         instructions().append(!!offset ? offset.offset() : 0);
2597         return value;
2598     } }
2599     
2600     RELEASE_ASSERT_NOT_REACHED();
2601 }
2602
2603 RegisterID* BytecodeGenerator::initializeVariable(const Variable& variable, RegisterID* value)
2604 {
2605     RELEASE_ASSERT(variable.offset().kind() != VarKind::Invalid);
2606     RegisterID* scope = emitResolveScope(nullptr, variable);
2607     return emitPutToScope(scope, variable, value, ThrowIfNotFound, InitializationMode::NotInitialization);
2608 }
2609
2610 RegisterID* BytecodeGenerator::emitInstanceOf(RegisterID* dst, RegisterID* value, RegisterID* basePrototype)
2611 {
2612     emitOpcode(op_instanceof);
2613     instructions().append(dst->index());
2614     instructions().append(value->index());
2615     instructions().append(basePrototype->index());
2616     return dst;
2617 }
2618
2619 RegisterID* BytecodeGenerator::emitInstanceOfCustom(RegisterID* dst, RegisterID* value, RegisterID* constructor, RegisterID* hasInstanceValue)
2620 {
2621     emitOpcode(op_instanceof_custom);
2622     instructions().append(dst->index());
2623     instructions().append(value->index());
2624     instructions().append(constructor->index());
2625     instructions().append(hasInstanceValue->index());
2626     return dst;
2627 }
2628
2629 RegisterID* BytecodeGenerator::emitIn(RegisterID* dst, RegisterID* property, RegisterID* base)
2630 {
2631     UnlinkedArrayProfile arrayProfile = newArrayProfile();
2632     emitOpcode(op_in);
2633     instructions().append(dst->index());
2634     instructions().append(base->index());
2635     instructions().append(property->index());
2636     instructions().append(arrayProfile);
2637     return dst;
2638 }
2639
2640 RegisterID* BytecodeGenerator::emitTryGetById(RegisterID* dst, RegisterID* base, const Identifier& property)
2641 {
2642     ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties are not supported with tryGetById.");
2643
2644     UnlinkedValueProfile profile = emitProfiledOpcode(op_try_get_by_id);
2645     instructions().append(kill(dst));
2646     instructions().append(base->index());
2647     instructions().append(addConstant(property));
2648     instructions().append(profile);
2649     return dst;
2650 }
2651
2652 RegisterID* BytecodeGenerator::emitGetById(RegisterID* dst, RegisterID* base, const Identifier& property)
2653 {
2654     ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with get_by_val.");
2655
2656     m_codeBlock->addPropertyAccessInstruction(instructions().size());
2657
2658     UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_id);
2659     instructions().append(kill(dst));
2660     instructions().append(base->index());
2661     instructions().append(addConstant(property));
2662     instructions().append(0);
2663     instructions().append(0);
2664     instructions().append(0);
2665     instructions().append(Options::prototypeHitCountForLLIntCaching());
2666     instructions().append(profile);
2667     return dst;
2668 }
2669
2670 RegisterID* BytecodeGenerator::emitGetById(RegisterID* dst, RegisterID* base, RegisterID* thisVal, const Identifier& property)
2671 {
2672     ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with get_by_val.");
2673
2674     UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_id_with_this);
2675     instructions().append(kill(dst));
2676     instructions().append(base->index());
2677     instructions().append(thisVal->index());
2678     instructions().append(addConstant(property));
2679     instructions().append(profile);
2680     return dst;
2681 }
2682
2683 RegisterID* BytecodeGenerator::emitPutById(RegisterID* base, const Identifier& property, RegisterID* value)
2684 {
2685     ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with put_by_val.");
2686
2687     unsigned propertyIndex = addConstant(property);
2688
2689     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2690
2691     m_codeBlock->addPropertyAccessInstruction(instructions().size());
2692
2693     emitOpcode(op_put_by_id);
2694     instructions().append(base->index());
2695     instructions().append(propertyIndex);
2696     instructions().append(value->index());
2697     instructions().append(0); // old structure
2698     instructions().append(0); // offset
2699     instructions().append(0); // new structure
2700     instructions().append(0); // structure chain
2701     instructions().append(static_cast<int>(PutByIdNone)); // is not direct
2702
2703     return value;
2704 }
2705
2706 RegisterID* BytecodeGenerator::emitPutById(RegisterID* base, RegisterID* thisValue, const Identifier& property, RegisterID* value)
2707 {
2708     ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with put_by_val.");
2709
2710     unsigned propertyIndex = addConstant(property);
2711
2712     emitOpcode(op_put_by_id_with_this);
2713     instructions().append(base->index());
2714     instructions().append(thisValue->index());
2715     instructions().append(propertyIndex);
2716     instructions().append(value->index());
2717
2718     return value;
2719 }
2720
2721 RegisterID* BytecodeGenerator::emitDirectPutById(RegisterID* base, const Identifier& property, RegisterID* value, PropertyNode::PutType putType)
2722 {
2723     ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with put_by_val(direct).");
2724
2725     unsigned propertyIndex = addConstant(property);
2726
2727     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2728
2729     m_codeBlock->addPropertyAccessInstruction(instructions().size());
2730     
2731     emitOpcode(op_put_by_id);
2732     instructions().append(base->index());
2733     instructions().append(propertyIndex);
2734     instructions().append(value->index());
2735     instructions().append(0); // old structure
2736     instructions().append(0); // offset
2737     instructions().append(0); // new structure
2738     instructions().append(0); // structure chain (unused if direct)
2739     instructions().append(static_cast<int>((putType == PropertyNode::KnownDirect || property != m_vm->propertyNames->underscoreProto) ? PutByIdIsDirect : PutByIdNone));
2740     return value;
2741 }
2742
2743 void BytecodeGenerator::emitPutGetterById(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* getter)
2744 {
2745     unsigned propertyIndex = addConstant(property);
2746     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2747
2748     emitOpcode(op_put_getter_by_id);
2749     instructions().append(base->index());
2750     instructions().append(propertyIndex);
2751     instructions().append(attributes);
2752     instructions().append(getter->index());
2753 }
2754
2755 void BytecodeGenerator::emitPutSetterById(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* setter)
2756 {
2757     unsigned propertyIndex = addConstant(property);
2758     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2759
2760     emitOpcode(op_put_setter_by_id);
2761     instructions().append(base->index());
2762     instructions().append(propertyIndex);
2763     instructions().append(attributes);
2764     instructions().append(setter->index());
2765 }
2766
2767 void BytecodeGenerator::emitPutGetterSetter(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* getter, RegisterID* setter)
2768 {
2769     unsigned propertyIndex = addConstant(property);
2770
2771     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2772
2773     emitOpcode(op_put_getter_setter_by_id);
2774     instructions().append(base->index());
2775     instructions().append(propertyIndex);
2776     instructions().append(attributes);
2777     instructions().append(getter->index());
2778     instructions().append(setter->index());
2779 }
2780
2781 void BytecodeGenerator::emitPutGetterByVal(RegisterID* base, RegisterID* property, unsigned attributes, RegisterID* getter)
2782 {
2783     emitOpcode(op_put_getter_by_val);
2784     instructions().append(base->index());
2785     instructions().append(property->index());
2786     instructions().append(attributes);
2787     instructions().append(getter->index());
2788 }
2789
2790 void BytecodeGenerator::emitPutSetterByVal(RegisterID* base, RegisterID* property, unsigned attributes, RegisterID* setter)
2791 {
2792     emitOpcode(op_put_setter_by_val);
2793     instructions().append(base->index());
2794     instructions().append(property->index());
2795     instructions().append(attributes);
2796     instructions().append(setter->index());
2797 }
2798
2799 void BytecodeGenerator::emitPutGeneratorFields(RegisterID* nextFunction)
2800 {
2801     // FIXME: Currently, we just create an object and store generator related fields as its properties for ease.
2802     // But to make it efficient, we will introduce JSGenerator class, add opcode new_generator and use its C++ fields instead of these private properties.
2803     // https://bugs.webkit.org/show_bug.cgi?id=151545
2804
2805     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorNextPrivateName(), nextFunction, PropertyNode::KnownDirect);
2806
2807     // We do not store 'this' in arrow function within constructor,
2808     // because it might be not initialized, if super is called later.
2809     if (!(isDerivedConstructorContext() && m_codeBlock->parseMode() == SourceParseMode::AsyncArrowFunctionMode))
2810         emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorThisPrivateName(), &m_thisRegister, PropertyNode::KnownDirect);
2811
2812     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorStatePrivateName(), emitLoad(nullptr, jsNumber(0)), PropertyNode::KnownDirect);
2813
2814     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorFramePrivateName(), emitLoad(nullptr, jsNull()), PropertyNode::KnownDirect);
2815 }
2816
2817 void BytecodeGenerator::emitPutAsyncGeneratorFields(RegisterID* nextFunction)
2818 {
2819     ASSERT(isAsyncGeneratorFunctionParseMode(parseMode()));
2820
2821     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorNextPrivateName(), nextFunction, PropertyNode::KnownDirect);
2822         
2823     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorThisPrivateName(), &m_thisRegister, PropertyNode::KnownDirect);
2824         
2825     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorStatePrivateName(), emitLoad(nullptr, jsNumber(static_cast<int32_t>(JSAsyncGeneratorFunction::AsyncGeneratorState::SuspendedStart))), PropertyNode::KnownDirect);
2826         
2827     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorFramePrivateName(), emitLoad(nullptr, jsNull()), PropertyNode::KnownDirect);
2828
2829     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().asyncGeneratorSuspendReasonPrivateName(), emitLoad(nullptr, jsNumber(static_cast<int32_t>(JSAsyncGeneratorFunction::AsyncGeneratorSuspendReason::None))), PropertyNode::KnownDirect);
2830
2831     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().asyncGeneratorQueueFirstPrivateName(), emitLoad(nullptr, jsNull()), PropertyNode::KnownDirect);
2832     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().asyncGeneratorQueueLastPrivateName(), emitLoad(nullptr, jsNull()), PropertyNode::KnownDirect);
2833 }
2834
2835 RegisterID* BytecodeGenerator::emitDeleteById(RegisterID* dst, RegisterID* base, const Identifier& property)
2836 {
2837     emitOpcode(op_del_by_id);
2838     instructions().append(dst->index());
2839     instructions().append(base->index());
2840     instructions().append(addConstant(property));
2841     return dst;
2842 }
2843
2844 RegisterID* BytecodeGenerator::emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* property)
2845 {
2846     for (size_t i = m_forInContextStack.size(); i--; ) {
2847         ForInContext& context = m_forInContextStack[i].get();
2848         if (context.local() != property)
2849             continue;
2850
2851         unsigned instIndex = instructions().size();
2852
2853         if (context.type() == ForInContext::IndexedForInContextType) {
2854             static_cast<IndexedForInContext&>(context).addGetInst(instIndex, property->index());
2855             property = static_cast<IndexedForInContext&>(context).index();
2856             break;
2857         }
2858
2859         ASSERT(context.type() == ForInContext::StructureForInContextType);
2860         StructureForInContext& structureContext = static_cast<StructureForInContext&>(context);
2861         UnlinkedValueProfile profile = emitProfiledOpcode(op_get_direct_pname);
2862         instructions().append(kill(dst));
2863         instructions().append(base->index());
2864         instructions().append(property->index());
2865         instructions().append(structureContext.index()->index());
2866         instructions().append(structureContext.enumerator()->index());
2867         instructions().append(profile);
2868
2869         structureContext.addGetInst(instIndex, property->index(), profile);
2870         return dst;
2871     }
2872
2873     UnlinkedArrayProfile arrayProfile = newArrayProfile();
2874     UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_val);
2875     instructions().append(kill(dst));
2876     instructions().append(base->index());
2877     instructions().append(property->index());
2878     instructions().append(arrayProfile);
2879     instructions().append(profile);
2880     return dst;
2881 }
2882
2883 RegisterID* BytecodeGenerator::emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* thisValue, RegisterID* property)
2884 {
2885     UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_val_with_this);
2886     instructions().append(kill(dst));
2887     instructions().append(base->index());
2888     instructions().append(thisValue->index());
2889     instructions().append(property->index());
2890     instructions().append(profile);
2891     return dst;
2892 }
2893
2894 RegisterID* BytecodeGenerator::emitPutByVal(RegisterID* base, RegisterID* property, RegisterID* value)
2895 {
2896     UnlinkedArrayProfile arrayProfile = newArrayProfile();
2897     emitOpcode(op_put_by_val);
2898     instructions().append(base->index());
2899     instructions().append(property->index());
2900     instructions().append(value->index());
2901     instructions().append(arrayProfile);
2902
2903     return value;
2904 }
2905
2906 RegisterID* BytecodeGenerator::emitPutByVal(RegisterID* base, RegisterID* thisValue, RegisterID* property, RegisterID* value)
2907 {
2908     emitOpcode(op_put_by_val_with_this);
2909     instructions().append(base->index());
2910     instructions().append(thisValue->index());
2911     instructions().append(property->index());
2912     instructions().append(value->index());
2913
2914     return value;
2915 }
2916
2917 RegisterID* BytecodeGenerator::emitDirectPutByVal(RegisterID* base, RegisterID* property, RegisterID* value)
2918 {
2919     UnlinkedArrayProfile arrayProfile = newArrayProfile();
2920     emitOpcode(op_put_by_val_direct);
2921     instructions().append(base->index());
2922     instructions().append(property->index());
2923     instructions().append(value->index());
2924     instructions().append(arrayProfile);
2925     return value;
2926 }
2927
2928 RegisterID* BytecodeGenerator::emitDeleteByVal(RegisterID* dst, RegisterID* base, RegisterID* property)
2929 {
2930     emitOpcode(op_del_by_val);
2931     instructions().append(dst->index());
2932     instructions().append(base->index());
2933     instructions().append(property->index());
2934     return dst;
2935 }
2936
2937 RegisterID* BytecodeGenerator::emitPutByIndex(RegisterID* base, unsigned index, RegisterID* value)
2938 {
2939     emitOpcode(op_put_by_index);
2940     instructions().append(base->index());
2941     instructions().append(index);
2942     instructions().append(value->index());
2943     return value;
2944 }
2945
2946 RegisterID* BytecodeGenerator::emitAssert(RegisterID* condition, int line)
2947 {
2948     emitOpcode(op_assert);
2949     instructions().append(condition->index());
2950     instructions().append(line);
2951     return condition;
2952 }
2953
2954 RegisterID* BytecodeGenerator::emitIdWithProfile(RegisterID* src, SpeculatedType profile)
2955 {
2956     emitOpcode(op_identity_with_profile);
2957     instructions().append(src->index());
2958     instructions().append(static_cast<uint32_t>(profile >> 32));
2959     instructions().append(static_cast<uint32_t>(profile));
2960     return src;
2961 }
2962
2963 void BytecodeGenerator::emitUnreachable()
2964 {
2965     emitOpcode(op_unreachable);
2966 }
2967
2968 RegisterID* BytecodeGenerator::emitGetArgument(RegisterID* dst, int32_t index)
2969 {
2970     UnlinkedValueProfile profile = emitProfiledOpcode(op_get_argument);
2971     instructions().append(dst->index());
2972     instructions().append(index + 1); // Including |this|.
2973     instructions().append(profile);
2974     return dst;
2975 }
2976
2977 RegisterID* BytecodeGenerator::emitCreateThis(RegisterID* dst)
2978 {
2979     size_t begin = instructions().size();
2980     m_staticPropertyAnalyzer.createThis(dst->index(), begin + 3);
2981
2982     m_codeBlock->addPropertyAccessInstruction(instructions().size());
2983     emitOpcode(op_create_this); 
2984     instructions().append(dst->index());
2985     instructions().append(dst->index());
2986     instructions().append(0);
2987     instructions().append(0);
2988     return dst;
2989 }
2990
2991 void BytecodeGenerator::emitTDZCheck(RegisterID* target)
2992 {
2993     emitOpcode(op_check_tdz);
2994     instructions().append(target->index());
2995 }
2996
2997 bool BytecodeGenerator::needsTDZCheck(const Variable& variable)
2998 {
2999     for (unsigned i = m_TDZStack.size(); i--;) {
3000         auto iter = m_TDZStack[i].find(variable.ident().impl());
3001         if (iter == m_TDZStack[i].end())
3002             continue;
3003         return iter->value != TDZNecessityLevel::NotNeeded;
3004     }
3005
3006     return false;
3007 }
3008
3009 void BytecodeGenerator::emitTDZCheckIfNecessary(const Variable& variable, RegisterID* target, RegisterID* scope)
3010 {
3011     if (needsTDZCheck(variable)) {
3012         if (target)
3013             emitTDZCheck(target);
3014         else {
3015             RELEASE_ASSERT(!variable.isLocal() && scope);
3016             RefPtr<RegisterID> result = emitGetFromScope(newTemporary(), scope, variable, DoNotThrowIfNotFound);
3017             emitTDZCheck(result.get());
3018         }
3019     }
3020 }
3021
3022 void BytecodeGenerator::liftTDZCheckIfPossible(const Variable& variable)
3023 {
3024     RefPtr<UniquedStringImpl> identifier(variable.ident().impl());
3025     for (unsigned i = m_TDZStack.size(); i--;) {
3026         auto iter = m_TDZStack[i].find(identifier);
3027         if (iter != m_TDZStack[i].end()) {
3028             if (iter->value == TDZNecessityLevel::Optimize)
3029                 iter->value = TDZNecessityLevel::NotNeeded;
3030             break;
3031         }
3032     }
3033 }
3034
3035 void BytecodeGenerator::pushTDZVariables(const VariableEnvironment& environment, TDZCheckOptimization optimization, TDZRequirement requirement)
3036 {
3037     if (!environment.size())
3038         return;
3039     
3040     TDZNecessityLevel level;
3041     if (requirement == TDZRequirement::UnderTDZ) {
3042         if (optimization == TDZCheckOptimization::Optimize)
3043             level = TDZNecessityLevel::Optimize;
3044         else
3045             level = TDZNecessityLevel::DoNotOptimize;
3046     } else
3047         level = TDZNecessityLevel::NotNeeded;
3048     
3049     TDZMap map;
3050     for (const auto& entry : environment)
3051         map.add(entry.key, entry.value.isFunction() ? TDZNecessityLevel::NotNeeded : level);
3052
3053     m_TDZStack.append(WTFMove(map));
3054 }
3055
3056 void BytecodeGenerator::getVariablesUnderTDZ(VariableEnvironment& result)
3057 {
3058     // We keep track of variablesThatDontNeedTDZ in this algorithm to prevent
3059     // reporting that "x" is under TDZ if this function is called at "...".
3060     //
3061     //     {
3062     //         {
3063     //             let x;
3064     //             ...
3065     //         }
3066     //         let x;
3067     //     }
3068     //
3069     SmallPtrSet<UniquedStringImpl*, 16> variablesThatDontNeedTDZ;
3070     for (unsigned i = m_TDZStack.size(); i--; ) {
3071         auto& map = m_TDZStack[i];
3072         for (auto& entry : map)  {
3073             if (entry.value != TDZNecessityLevel::NotNeeded) {
3074                 if (!variablesThatDontNeedTDZ.contains(entry.key.get()))
3075                     result.add(entry.key.get());
3076             } else
3077                 variablesThatDontNeedTDZ.add(entry.key.get());
3078         }
3079     }
3080 }
3081
3082 RegisterID* BytecodeGenerator::emitNewObject(RegisterID* dst)
3083 {
3084     size_t begin = instructions().size();
3085     m_staticPropertyAnalyzer.newObject(dst->index(), begin + 2);
3086
3087     emitOpcode(op_new_object);
3088     instructions().append(dst->index());
3089     instructions().append(0);
3090     instructions().append(newObjectAllocationProfile());
3091     return dst;
3092 }
3093
3094 unsigned BytecodeGenerator::addConstantBuffer(unsigned length)
3095 {
3096     return m_codeBlock->addConstantBuffer(length);
3097 }
3098
3099 JSString* BytecodeGenerator::addStringConstant(const Identifier& identifier)
3100 {
3101     JSString*& stringInMap = m_stringMap.add(identifier.impl(), nullptr).iterator->value;
3102     if (!stringInMap) {
3103         stringInMap = jsString(vm(), identifier.string());
3104         addConstantValue(stringInMap);
3105     }
3106     return stringInMap;
3107 }
3108
3109 RegisterID* BytecodeGenerator::addTemplateRegistryKeyConstant(Ref<TemplateRegistryKey>&& templateRegistryKey)
3110 {
3111     return m_templateRegistryKeyMap.ensure(templateRegistryKey.copyRef(), [&] {
3112         auto* result = JSTemplateRegistryKey::create(*vm(), WTFMove(templateRegistryKey));
3113         unsigned index = addConstantIndex();
3114         m_codeBlock->addConstant(result);
3115         return &m_constantPoolRegisters[index];
3116     }).iterator->value;
3117 }
3118
3119 RegisterID* BytecodeGenerator::emitNewArray(RegisterID* dst, ElementNode* elements, unsigned length)
3120 {
3121 #if !ASSERT_DISABLED
3122     unsigned checkLength = 0;
3123 #endif
3124     bool hadVariableExpression = false;
3125     if (length) {
3126         for (ElementNode* n = elements; n; n = n->next()) {
3127             if (!n->value()->isConstant()) {
3128                 hadVariableExpression = true;
3129                 break;
3130             }
3131             if (n->elision())
3132                 break;
3133 #if !ASSERT_DISABLED
3134             checkLength++;
3135 #endif
3136         }
3137         if (!hadVariableExpression) {
3138             ASSERT(length == checkLength);
3139             unsigned constantBufferIndex = addConstantBuffer(length);
3140             JSValue* constantBuffer = m_codeBlock->constantBuffer(constantBufferIndex).data();
3141             unsigned index = 0;
3142             for (ElementNode* n = elements; index < length; n = n->next()) {
3143                 ASSERT(n->value()->isConstant());
3144                 constantBuffer[index++] = static_cast<ConstantNode*>(n->value())->jsValue(*this);
3145             }
3146             emitOpcode(op_new_array_buffer);
3147             instructions().append(dst->index());
3148             instructions().append(constantBufferIndex);
3149             instructions().append(length);
3150             instructions().append(newArrayAllocationProfile());
3151             return dst;
3152         }
3153     }
3154
3155     Vector<RefPtr<RegisterID>, 16, UnsafeVectorOverflow> argv;
3156     for (ElementNode* n = elements; n; n = n->next()) {
3157         if (!length)
3158           &nbs