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