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