b9370c8d284a384f21e0e789268545c92b19823b
[WebKit-https.git] / Source / JavaScriptCore / bytecompiler / BytecodeGenerator.cpp
1 /*
2  * Copyright (C) 2008, 2009, 2012-2015 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 "Interpreter.h"
36 #include "JSFunction.h"
37 #include "JSLexicalEnvironment.h"
38 #include "JSTemplateRegistryKey.h"
39 #include "LowLevelInterpreter.h"
40 #include "JSCInlines.h"
41 #include "Options.h"
42 #include "StackAlignment.h"
43 #include "StrongInlines.h"
44 #include "UnlinkedCodeBlock.h"
45 #include "UnlinkedInstructionStream.h"
46 #include <wtf/StdLibExtras.h>
47 #include <wtf/text/WTFString.h>
48
49 using namespace std;
50
51 namespace JSC {
52
53 void Label::setLocation(unsigned location)
54 {
55     m_location = location;
56     
57     unsigned size = m_unresolvedJumps.size();
58     for (unsigned i = 0; i < size; ++i)
59         m_generator.instructions()[m_unresolvedJumps[i].second].u.operand = m_location - m_unresolvedJumps[i].first;
60 }
61
62 ParserError BytecodeGenerator::generate()
63 {
64     SamplingRegion samplingRegion("Bytecode Generation");
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 {
159     ASSERT_UNUSED(parentScopeTDZVariables, !parentScopeTDZVariables->size());
160
161     for (auto& constantRegister : m_linkTimeConstantRegisters)
162         constantRegister = nullptr;
163
164     allocateCalleeSaveSpace();
165
166     m_codeBlock->setNumParameters(1); // Allocate space for "this"
167
168     emitOpcode(op_enter);
169
170     allocateAndEmitScope();
171
172     const FunctionStack& functionStack = programNode->functionStack();
173
174     for (size_t i = 0; i < functionStack.size(); ++i) {
175         FunctionMetadataNode* function = functionStack[i];
176         m_functionsToInitialize.append(std::make_pair(function, GlobalFunctionVariable));
177     }
178     if (Options::validateBytecode()) {
179         for (auto& entry : programNode->varDeclarations())
180             RELEASE_ASSERT(entry.value.isVar());
181     }
182     codeBlock->setVariableDeclarations(programNode->varDeclarations());
183     codeBlock->setLexicalDeclarations(programNode->lexicalVariables());
184     // Even though this program may have lexical variables that go under TDZ, when linking the get_from_scope/put_to_scope
185     // operations we emit we will have ResolveTypes that implictly do TDZ checks. Therefore, we don't need
186     // additional TDZ checks on top of those. This is why we can omit pushing programNode->lexicalVariables()
187     // to the TDZ stack.
188 }
189
190 BytecodeGenerator::BytecodeGenerator(VM& vm, FunctionNode* functionNode, UnlinkedFunctionCodeBlock* codeBlock, DebuggerMode debuggerMode, ProfilerMode profilerMode, const VariableEnvironment* parentScopeTDZVariables)
191     : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
192     , m_shouldEmitProfileHooks(Options::forceProfilerBytecodeGeneration() || profilerMode == ProfilerOn)
193     , m_scopeNode(functionNode)
194     , m_codeBlock(vm, codeBlock)
195     , m_codeType(FunctionCode)
196     , m_vm(&vm)
197     , m_isBuiltinFunction(codeBlock->isBuiltinFunction())
198     , m_usesNonStrictEval(codeBlock->usesEval() && !codeBlock->isStrictMode())
199     // FIXME: We should be able to have tail call elimination with the profiler
200     // enabled. This is currently not possible because the profiler expects
201     // op_will_call / op_did_call pairs before and after a call, which are not
202     // compatible with tail calls (we have no way of emitting op_did_call).
203     // https://bugs.webkit.org/show_bug.cgi?id=148819
204     , m_inTailPosition(Options::useTailCalls() && !isConstructor() && constructorKind() == ConstructorKind::None && isStrictMode() && !m_shouldEmitProfileHooks)
205 {
206     for (auto& constantRegister : m_linkTimeConstantRegisters)
207         constantRegister = nullptr;
208
209     if (m_isBuiltinFunction)
210         m_shouldEmitDebugHooks = false;
211
212     allocateCalleeSaveSpace();
213     
214     SymbolTable* functionSymbolTable = SymbolTable::create(*m_vm);
215     functionSymbolTable->setUsesNonStrictEval(m_usesNonStrictEval);
216     int symbolTableConstantIndex = addConstantValue(functionSymbolTable)->index();
217
218     Vector<Identifier> boundParameterProperties;
219     FunctionParameters& parameters = *functionNode->parameters(); 
220     if (!parameters.hasDefaultParameterValues()) { 
221         // If we do have default parameters, they will be allocated in a separate scope.
222         for (size_t i = 0; i < parameters.size(); i++) {
223             auto pattern = parameters.at(i).first;
224             if (pattern->isBindingNode())
225                 continue;
226             pattern->collectBoundIdentifiers(boundParameterProperties);
227         }
228     }
229
230     bool shouldCaptureSomeOfTheThings = m_shouldEmitDebugHooks || m_codeBlock->needsFullScopeChain();
231     bool shouldCaptureAllOfTheThings = m_shouldEmitDebugHooks || codeBlock->usesEval();
232     bool needsArguments = functionNode->usesArguments() || codeBlock->usesEval();
233     if (shouldCaptureAllOfTheThings)
234         functionNode->varDeclarations().markAllVariablesAsCaptured();
235     
236     auto captures = [&] (UniquedStringImpl* uid) -> bool {
237         if (!shouldCaptureSomeOfTheThings)
238             return false;
239         if (needsArguments && uid == propertyNames().arguments.impl()) {
240             // Actually, we only need to capture the arguments object when we "need full activation"
241             // because of name scopes. But historically we did it this way, so for now we just preserve
242             // the old behavior.
243             // FIXME: https://bugs.webkit.org/show_bug.cgi?id=143072
244             return true;
245         }
246         return functionNode->captures(uid);
247     };
248     auto varKind = [&] (UniquedStringImpl* uid) -> VarKind {
249         return captures(uid) ? VarKind::Scope : VarKind::Stack;
250     };
251
252     emitOpcode(op_enter);
253
254     allocateAndEmitScope();
255     
256     m_calleeRegister.setIndex(JSStack::Callee);
257     
258     if (functionNameIsInScope(functionNode->ident(), functionNode->functionMode())) {
259         bool isDynamicScope = functionNameScopeIsDynamic(codeBlock->usesEval(), codeBlock->isStrictMode());
260         bool isFunctionNameCaptured = captures(functionNode->ident().impl());
261         bool markAsCaptured = isDynamicScope || isFunctionNameCaptured;
262         emitPushFunctionNameScope(functionNode->ident(), &m_calleeRegister, markAsCaptured);
263     }
264     
265     if (shouldCaptureSomeOfTheThings) {
266         m_lexicalEnvironmentRegister = addVar();
267         // We can allocate the "var" environment if we don't have default parameter expressions. If we have
268         // default parameter expressions, we have to hold off on allocating the "var" environment because
269         // the parent scope of the "var" environment is the parameter environment.
270         if (!parameters.hasDefaultParameterValues())
271             initializeVarLexicalEnvironment(symbolTableConstantIndex);
272     }
273
274     // Make sure the code block knows about all of our parameters, and make sure that parameters
275     // needing destructuring are noted.
276     m_parameters.grow(parameters.size() + 1); // reserve space for "this"
277     m_thisRegister.setIndex(initializeNextParameter()->index()); // this
278     for (unsigned i = 0; i < parameters.size(); ++i) {
279         auto pattern = parameters.at(i).first;
280         if (pattern->isRestParameter()) {
281             RELEASE_ASSERT(!m_restParameter);
282             m_restParameter = static_cast<RestParameterNode*>(pattern);
283         } else
284             initializeNextParameter();
285     }
286     
287     // Figure out some interesting facts about our arguments.
288     bool capturesAnyArgumentByName = false;
289     if (functionNode->hasCapturedVariables()) {
290         FunctionParameters& parameters = *functionNode->parameters();
291         for (size_t i = 0; i < parameters.size(); ++i) {
292             auto pattern = parameters.at(i).first;
293             if (!pattern->isBindingNode())
294                 continue;
295             const Identifier& ident = static_cast<const BindingNode*>(pattern)->boundProperty();
296             capturesAnyArgumentByName |= captures(ident.impl());
297         }
298     }
299     
300     if (capturesAnyArgumentByName)
301         ASSERT(m_lexicalEnvironmentRegister);
302
303     // Need to know what our functions are called. Parameters have some goofy behaviors when it
304     // comes to functions of the same name.
305     for (FunctionMetadataNode* function : functionNode->functionStack())
306         m_functions.add(function->ident().impl());
307     
308     if (needsArguments) {
309         // Create the arguments object now. We may put the arguments object into the activation if
310         // it is captured. Either way, we create two arguments object variables: one is our
311         // private variable that is immutable, and another that is the user-visible variable. The
312         // immutable one is only used here, or during formal parameter resolutions if we opt for
313         // DirectArguments.
314         
315         m_argumentsRegister = addVar();
316         m_argumentsRegister->ref();
317     }
318     
319     // http://www.ecma-international.org/ecma-262/6.0/index.html#sec-functiondeclarationinstantiation
320     // This implements IsSimpleParameterList in the Ecma 2015 spec.
321     // If IsSimpleParameterList is false, we will create a strict-mode like arguments object.
322     // IsSimpleParameterList is false if the argument list contains any default parameter values,
323     // a rest parameter, or any destructuring patterns.
324     // FIXME: Take into account destructuring to make isSimpleParameterList false. https://bugs.webkit.org/show_bug.cgi?id=151450
325     bool isSimpleParameterList = !parameters.hasDefaultParameterValues() && !m_restParameter;
326     if (needsArguments && !codeBlock->isStrictMode() && isSimpleParameterList) {
327         // If we captured any formal parameter by name, then we use ScopedArguments. Otherwise we
328         // use DirectArguments. With ScopedArguments, we lift all of our arguments into the
329         // activation.
330         
331         if (capturesAnyArgumentByName) {
332             functionSymbolTable->setArgumentsLength(vm, parameters.size());
333             
334             // For each parameter, we have two possibilities:
335             // Either it's a binding node with no function overlap, in which case it gets a name
336             // in the symbol table - or it just gets space reserved in the symbol table. Either
337             // way we lift the value into the scope.
338             for (unsigned i = 0; i < parameters.size(); ++i) {
339                 ScopeOffset offset = functionSymbolTable->takeNextScopeOffset();
340                 functionSymbolTable->setArgumentOffset(vm, i, offset);
341                 if (UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first)) {
342                     VarOffset varOffset(offset);
343                     SymbolTableEntry entry(varOffset);
344                     // Stores to these variables via the ScopedArguments object will not do
345                     // notifyWrite(), since that would be cumbersome. Also, watching formal
346                     // parameters when "arguments" is in play is unlikely to be super profitable.
347                     // So, we just disable it.
348                     entry.disableWatching();
349                     functionSymbolTable->set(name, entry);
350                 }
351                 emitOpcode(op_put_to_scope);
352                 instructions().append(m_lexicalEnvironmentRegister->index());
353                 instructions().append(UINT_MAX);
354                 instructions().append(virtualRegisterForArgument(1 + i).offset());
355                 instructions().append(GetPutInfo(ThrowIfNotFound, LocalClosureVar, NotInitialization).operand());
356                 instructions().append(symbolTableConstantIndex);
357                 instructions().append(offset.offset());
358             }
359             
360             // This creates a scoped arguments object and copies the overflow arguments into the
361             // scope. It's the equivalent of calling ScopedArguments::createByCopying().
362             emitOpcode(op_create_scoped_arguments);
363             instructions().append(m_argumentsRegister->index());
364             instructions().append(m_lexicalEnvironmentRegister->index());
365         } else {
366             // We're going to put all parameters into the DirectArguments object. First ensure
367             // that the symbol table knows that this is happening.
368             for (unsigned i = 0; i < parameters.size(); ++i) {
369                 if (UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first))
370                     functionSymbolTable->set(name, SymbolTableEntry(VarOffset(DirectArgumentsOffset(i))));
371             }
372             
373             emitOpcode(op_create_direct_arguments);
374             instructions().append(m_argumentsRegister->index());
375         }
376     } else if (!parameters.hasDefaultParameterValues()) {
377         // Create the formal parameters the normal way. Any of them could be captured, or not. If
378         // captured, lift them into the scope. We can not do this if we have default parameter expressions
379         // because when default parameter expressions exist, they belong in their own lexical environment
380         // separate from the "var" lexical environment.
381         for (unsigned i = 0; i < parameters.size(); ++i) {
382             UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first);
383             if (!name)
384                 continue;
385             
386             if (!captures(name)) {
387                 // This is the easy case - just tell the symbol table about the argument. It will
388                 // be accessed directly.
389                 functionSymbolTable->set(name, SymbolTableEntry(VarOffset(virtualRegisterForArgument(1 + i))));
390                 continue;
391             }
392             
393             ScopeOffset offset = functionSymbolTable->takeNextScopeOffset();
394             const Identifier& ident =
395                 static_cast<const BindingNode*>(parameters.at(i).first)->boundProperty();
396             functionSymbolTable->set(name, SymbolTableEntry(VarOffset(offset)));
397             
398             emitOpcode(op_put_to_scope);
399             instructions().append(m_lexicalEnvironmentRegister->index());
400             instructions().append(addConstant(ident));
401             instructions().append(virtualRegisterForArgument(1 + i).offset());
402             instructions().append(GetPutInfo(ThrowIfNotFound, LocalClosureVar, NotInitialization).operand());
403             instructions().append(symbolTableConstantIndex);
404             instructions().append(offset.offset());
405         }
406     }
407     
408     if (needsArguments && (codeBlock->isStrictMode() || !isSimpleParameterList)) {
409         // Allocate an out-of-bands arguments object.
410         emitOpcode(op_create_out_of_band_arguments);
411         instructions().append(m_argumentsRegister->index());
412     }
413     
414     // Now declare all variables.
415     for (const Identifier& ident : boundParameterProperties) {
416         ASSERT(!parameters.hasDefaultParameterValues());
417         createVariable(ident, varKind(ident.impl()), functionSymbolTable);
418     }
419     for (FunctionMetadataNode* function : functionNode->functionStack()) {
420         const Identifier& ident = function->ident();
421         createVariable(ident, varKind(ident.impl()), functionSymbolTable);
422         m_functionsToInitialize.append(std::make_pair(function, NormalFunctionVariable));
423     }
424     for (auto& entry : functionNode->varDeclarations()) {
425         ASSERT(!entry.value.isLet() && !entry.value.isConst());
426         if (!entry.value.isVar()) // This is either a parameter or callee.
427             continue;
428         // Variables named "arguments" are never const.
429         createVariable(Identifier::fromUid(m_vm, entry.key.get()), varKind(entry.key.get()), functionSymbolTable, IgnoreExisting);
430     }
431
432     // There are some variables that need to be preinitialized to something other than Undefined:
433     //
434     // - "arguments": unless it's used as a function or parameter, this should refer to the
435     //   arguments object.
436     //
437     // - functions: these always override everything else.
438     //
439     // The most logical way to do all of this is to initialize none of the variables until now,
440     // and then initialize them in BytecodeGenerator::generate() in such an order that the rules
441     // for how these things override each other end up holding. We would initialize "arguments" first, 
442     // then all arguments, then the functions.
443     //
444     // But some arguments are already initialized by default, since if they aren't captured and we
445     // don't have "arguments" then we just point the symbol table at the stack slot of those
446     // arguments. We end up initializing the rest of the arguments that have an uncomplicated
447     // binding (i.e. don't involve destructuring) above when figuring out how to lay them out,
448     // because that's just the simplest thing. This means that when we initialize them, we have to
449     // watch out for the things that override arguments (namely, functions).
450     
451     // This is our final act of weirdness. "arguments" is overridden by everything except the
452     // callee. We add it to the symbol table if it's not already there and it's not an argument.
453     if (needsArguments) {
454         // If "arguments" is overridden by a function or destructuring parameter name, then it's
455         // OK for us to call createVariable() because it won't change anything. It's also OK for
456         // us to them tell BytecodeGenerator::generate() to write to it because it will do so
457         // before it initializes functions and destructuring parameters. But if "arguments" is
458         // overridden by a "simple" function parameter, then we have to bail: createVariable()
459         // would assert and BytecodeGenerator::generate() would write the "arguments" after the
460         // argument value had already been properly initialized.
461         
462         bool haveParameterNamedArguments = false;
463         for (unsigned i = 0; i < parameters.size(); ++i) {
464             UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first);
465             if (name == propertyNames().arguments.impl()) {
466                 haveParameterNamedArguments = true;
467                 break;
468             }
469         }
470         
471         if (!haveParameterNamedArguments) {
472             createVariable(
473                 propertyNames().arguments, varKind(propertyNames().arguments.impl()), functionSymbolTable);
474             m_needToInitializeArguments = true;
475         }
476     }
477
478     m_newTargetRegister = addVar();
479     if (!codeBlock->isArrowFunction()) {
480         if (isConstructor()) {
481             emitMove(m_newTargetRegister, &m_thisRegister);
482             if (constructorKind() == ConstructorKind::Derived)
483                 emitMoveEmptyValue(&m_thisRegister);
484             else
485                 emitCreateThis(&m_thisRegister);
486         } else if (constructorKind() != ConstructorKind::None) {
487             emitThrowTypeError("Cannot call a class constructor");
488         } else if (functionNode->usesThis() || codeBlock->usesEval()) {
489             m_codeBlock->addPropertyAccessInstruction(instructions().size());
490             emitOpcode(op_to_this);
491             instructions().append(kill(&m_thisRegister));
492             instructions().append(0);
493             instructions().append(0);
494         }
495     } else {
496         if (functionNode->usesThis() || codeBlock->usesEval())
497             emitLoadArrowFunctionThis(&m_thisRegister);
498     }
499
500     // All "addVar()"s needs to happen before "initializeDefaultParameterValuesAndSetupFunctionScopeStack()" is called
501     // because a function's default parameter ExpressionNodes will use temporary registers.
502     m_TDZStack.append(std::make_pair(*parentScopeTDZVariables, false));
503     initializeDefaultParameterValuesAndSetupFunctionScopeStack(parameters, functionNode, functionSymbolTable, symbolTableConstantIndex, captures);
504
505     pushLexicalScope(m_scopeNode, true);
506 }
507
508 BytecodeGenerator::BytecodeGenerator(VM& vm, EvalNode* evalNode, UnlinkedEvalCodeBlock* codeBlock, DebuggerMode debuggerMode, ProfilerMode profilerMode, const VariableEnvironment* parentScopeTDZVariables)
509     : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
510     , m_shouldEmitProfileHooks(Options::forceProfilerBytecodeGeneration() || profilerMode == ProfilerOn)
511     , m_scopeNode(evalNode)
512     , m_codeBlock(vm, codeBlock)
513     , m_thisRegister(CallFrame::thisArgumentOffset())
514     , m_codeType(EvalCode)
515     , m_vm(&vm)
516     , m_usesNonStrictEval(codeBlock->usesEval() && !codeBlock->isStrictMode())
517 {
518     for (auto& constantRegister : m_linkTimeConstantRegisters)
519         constantRegister = nullptr;
520
521     allocateCalleeSaveSpace();
522
523     m_codeBlock->setNumParameters(1);
524
525     emitOpcode(op_enter);
526
527     allocateAndEmitScope();
528
529     const DeclarationStacks::FunctionStack& functionStack = evalNode->functionStack();
530     for (size_t i = 0; i < functionStack.size(); ++i)
531         m_codeBlock->addFunctionDecl(makeFunction(functionStack[i]));
532
533     const VariableEnvironment& varDeclarations = evalNode->varDeclarations();
534     unsigned numVariables = varDeclarations.size();
535     Vector<Identifier, 0, UnsafeVectorOverflow> variables;
536     variables.reserveCapacity(numVariables);
537     for (auto& entry : varDeclarations) {
538         ASSERT(entry.value.isVar());
539         ASSERT(entry.key->isAtomic() || entry.key->isSymbol());
540         variables.append(Identifier::fromUid(m_vm, entry.key.get()));
541     }
542     codeBlock->adoptVariables(variables);
543
544     m_TDZStack.append(std::make_pair(*parentScopeTDZVariables, false));
545
546     pushLexicalScope(m_scopeNode, true);
547 }
548
549 BytecodeGenerator::BytecodeGenerator(VM& vm, ModuleProgramNode* moduleProgramNode, UnlinkedModuleProgramCodeBlock* codeBlock, DebuggerMode debuggerMode, ProfilerMode profilerMode, const VariableEnvironment* parentScopeTDZVariables)
550     : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
551     , m_shouldEmitProfileHooks(Options::forceProfilerBytecodeGeneration() || profilerMode == ProfilerOn)
552     , m_scopeNode(moduleProgramNode)
553     , m_codeBlock(vm, codeBlock)
554     , m_thisRegister(CallFrame::thisArgumentOffset())
555     , m_codeType(ModuleCode)
556     , m_vm(&vm)
557     , m_usesNonStrictEval(false)
558 {
559     ASSERT_UNUSED(parentScopeTDZVariables, !parentScopeTDZVariables->size());
560
561     for (auto& constantRegister : m_linkTimeConstantRegisters)
562         constantRegister = nullptr;
563
564     if (m_isBuiltinFunction)
565         m_shouldEmitDebugHooks = false;
566
567     allocateCalleeSaveSpace();
568
569     SymbolTable* moduleEnvironmentSymbolTable = SymbolTable::create(*m_vm);
570     moduleEnvironmentSymbolTable->setUsesNonStrictEval(m_usesNonStrictEval);
571     moduleEnvironmentSymbolTable->setScopeType(SymbolTable::ScopeType::LexicalScope);
572
573     bool shouldCaptureSomeOfTheThings = m_shouldEmitDebugHooks || m_codeBlock->needsFullScopeChain();
574     bool shouldCaptureAllOfTheThings = m_shouldEmitDebugHooks || codeBlock->usesEval();
575     if (shouldCaptureAllOfTheThings)
576         moduleProgramNode->varDeclarations().markAllVariablesAsCaptured();
577
578     auto captures = [&] (UniquedStringImpl* uid) -> bool {
579         if (!shouldCaptureSomeOfTheThings)
580             return false;
581         return moduleProgramNode->captures(uid);
582     };
583     auto lookUpVarKind = [&] (UniquedStringImpl* uid, const VariableEnvironmentEntry& entry) -> VarKind {
584         // Allocate the exported variables in the module environment.
585         if (entry.isExported())
586             return VarKind::Scope;
587
588         // Allocate the namespace variables in the module environment to instantiate
589         // it from the outside of the module code.
590         if (entry.isImportedNamespace())
591             return VarKind::Scope;
592
593         if (entry.isCaptured())
594             return VarKind::Scope;
595         return captures(uid) ? VarKind::Scope : VarKind::Stack;
596     };
597
598     emitOpcode(op_enter);
599
600     allocateAndEmitScope();
601
602     m_calleeRegister.setIndex(JSStack::Callee);
603
604     m_codeBlock->setNumParameters(1); // Allocate space for "this"
605
606     // Now declare all variables.
607
608     for (auto& entry : moduleProgramNode->varDeclarations()) {
609         ASSERT(!entry.value.isLet() && !entry.value.isConst());
610         if (!entry.value.isVar()) // This is either a parameter or callee.
611             continue;
612         // Imported bindings are not allocated in the module environment as usual variables' way.
613         // These references remain the "Dynamic" in the unlinked code block. Later, when linking
614         // the code block, we resolve the reference to the "ModuleVar".
615         if (entry.value.isImported() && !entry.value.isImportedNamespace())
616             continue;
617         createVariable(Identifier::fromUid(m_vm, entry.key.get()), lookUpVarKind(entry.key.get(), entry.value), moduleEnvironmentSymbolTable, IgnoreExisting);
618     }
619
620     VariableEnvironment& lexicalVariables = moduleProgramNode->lexicalVariables();
621     instantiateLexicalVariables(lexicalVariables, moduleEnvironmentSymbolTable, ScopeRegisterType::Block, lookUpVarKind);
622
623     // We keep the symbol table in the constant pool.
624     RegisterID* constantSymbolTable = nullptr;
625     if (vm.typeProfiler())
626         constantSymbolTable = addConstantValue(moduleEnvironmentSymbolTable);
627     else
628         constantSymbolTable = addConstantValue(moduleEnvironmentSymbolTable->cloneScopePart(*m_vm));
629
630     m_TDZStack.append(std::make_pair(lexicalVariables, true));
631     m_symbolTableStack.append(SymbolTableStackEntry { Strong<SymbolTable>(*m_vm, moduleEnvironmentSymbolTable), m_topMostScope, false, constantSymbolTable->index() });
632     emitPrefillStackTDZVariables(lexicalVariables, moduleEnvironmentSymbolTable);
633
634     // makeFunction assumes that there's correct TDZ stack entries.
635     // So it should be called after putting our lexical environment to the TDZ stack correctly.
636
637     for (FunctionMetadataNode* function : moduleProgramNode->functionStack()) {
638         const auto& iterator = moduleProgramNode->varDeclarations().find(function->ident().impl());
639         RELEASE_ASSERT(iterator != moduleProgramNode->varDeclarations().end());
640         RELEASE_ASSERT(!iterator->value.isImported());
641
642         VarKind varKind = lookUpVarKind(iterator->key.get(), iterator->value);
643         if (varKind == VarKind::Scope) {
644             // http://www.ecma-international.org/ecma-262/6.0/#sec-moduledeclarationinstantiation
645             // Section 15.2.1.16.4, step 16-a-iv-1.
646             // All heap allocated function declarations should be instantiated when the module environment
647             // is created. They include the exported function declarations and not-exported-but-heap-allocated
648             // function declarations. This is required because exported function should be instantiated before
649             // executing the any module in the dependency graph. This enables the modules to link the imported
650             // bindings before executing the any module code.
651             //
652             // And since function declarations are instantiated before executing the module body code, the spec
653             // allows the functions inside the module to be executed before its module body is executed under
654             // the circular dependencies. The following is the example.
655             //
656             // Module A (executed first):
657             //    import { b } from "B";
658             //    // Here, the module "B" is not executed yet, but the function declaration is already instantiated.
659             //    // So we can call the function exported from "B".
660             //    b();
661             //
662             //    export function a() {
663             //    }
664             //
665             // Module B (executed second):
666             //    import { a } from "A";
667             //
668             //    export function b() {
669             //        c();
670             //    }
671             //
672             //    // c is not exported, but since it is referenced from the b, we should instantiate it before
673             //    // executing the "B" module code.
674             //    function c() {
675             //        a();
676             //    }
677             //
678             // Module EntryPoint (executed last):
679             //    import "B";
680             //    import "A";
681             //
682             m_codeBlock->addFunctionDecl(makeFunction(function));
683         } else {
684             // Stack allocated functions can be allocated when executing the module's body.
685             m_functionsToInitialize.append(std::make_pair(function, NormalFunctionVariable));
686         }
687     }
688
689     // Remember the constant register offset to the top-most symbol table. This symbol table will be
690     // cloned in the code block linking. After that, to create the module environment, we retrieve
691     // the cloned symbol table from the linked code block by using this offset.
692     codeBlock->setModuleEnvironmentSymbolTableConstantRegisterOffset(constantSymbolTable->index());
693 }
694
695 BytecodeGenerator::~BytecodeGenerator()
696 {
697 }
698
699 void BytecodeGenerator::initializeDefaultParameterValuesAndSetupFunctionScopeStack(
700     FunctionParameters& parameters, FunctionNode* functionNode, SymbolTable* functionSymbolTable, 
701     int symbolTableConstantIndex, const std::function<bool (UniquedStringImpl*)>& captures)
702 {
703     Vector<std::pair<Identifier, RefPtr<RegisterID>>> valuesToMoveIntoVars;
704     if (parameters.hasDefaultParameterValues()) {
705         // Refer to the ES6 spec section 9.2.12: http://www.ecma-international.org/ecma-262/6.0/index.html#sec-functiondeclarationinstantiation
706         // This implements step 21.
707         VariableEnvironment environment;
708         Vector<Identifier> allParameterNames; 
709         for (unsigned i = 0; i < parameters.size(); i++)
710             parameters.at(i).first->collectBoundIdentifiers(allParameterNames);
711         IdentifierSet parameterSet;
712         for (auto& ident : allParameterNames) {
713             parameterSet.add(ident.impl());
714             auto addResult = environment.add(ident);
715             addResult.iterator->value.setIsLet(); // When we have default parameter expressions, parameters act like "let" variables.
716             if (captures(ident.impl()))
717                 addResult.iterator->value.setIsCaptured();
718         }
719         
720         // This implements step 25 of section 9.2.12.
721         pushLexicalScopeInternal(environment, true, nullptr, TDZRequirement::UnderTDZ, ScopeType::LetConstScope, ScopeRegisterType::Block);
722
723         RefPtr<RegisterID> temp = newTemporary();
724         for (unsigned i = 0; i < parameters.size(); i++) {
725             std::pair<DestructuringPatternNode*, ExpressionNode*> parameter = parameters.at(i);
726             if (parameter.first->isRestParameter())
727                 continue;
728             RefPtr<RegisterID> parameterValue = &registerFor(virtualRegisterForArgument(1 + i));
729             emitMove(temp.get(), parameterValue.get());
730             if (parameter.second) {
731                 RefPtr<RegisterID> condition = emitIsUndefined(newTemporary(), parameterValue.get());
732                 RefPtr<Label> skipDefaultParameterBecauseNotUndefined = newLabel();
733                 emitJumpIfFalse(condition.get(), skipDefaultParameterBecauseNotUndefined.get());
734                 emitNode(temp.get(), parameter.second);
735                 emitLabel(skipDefaultParameterBecauseNotUndefined.get());
736             }
737
738             parameter.first->bindValue(*this, temp.get());
739         }
740
741         // Final act of weirdness for default parameters. If a "var" also
742         // has the same name as a parameter, it should start out as the
743         // value of that parameter. Note, though, that they will be distinct
744         // bindings.
745         // This is step 28 of section 9.2.12. 
746         for (auto& entry : functionNode->varDeclarations()) {
747             if (!entry.value.isVar()) // This is either a parameter or callee.
748                 continue;
749
750             if (parameterSet.contains(entry.key)) {
751                 Identifier ident = Identifier::fromUid(m_vm, entry.key.get());
752                 Variable var = variable(ident);
753                 RegisterID* scope = emitResolveScope(nullptr, var);
754                 RefPtr<RegisterID> value = emitGetFromScope(newTemporary(), scope, var, DoNotThrowIfNotFound);
755                 valuesToMoveIntoVars.append(std::make_pair(ident, value));
756             }
757         }
758
759         // Functions with default parameter expressions must have a separate environment
760         // record for parameters and "var"s. The "var" environment record must have the
761         // parameter environment record as its parent.
762         // See step 28 of section 9.2.12.
763         if (m_lexicalEnvironmentRegister)
764             initializeVarLexicalEnvironment(symbolTableConstantIndex);
765     }
766
767     if (m_lexicalEnvironmentRegister)
768         pushScopedControlFlowContext();
769     m_symbolTableStack.append(SymbolTableStackEntry{ Strong<SymbolTable>(*m_vm, functionSymbolTable), m_lexicalEnvironmentRegister, false, symbolTableConstantIndex });
770
771     // This completes step 28 of section 9.2.12.
772     for (unsigned i = 0; i < valuesToMoveIntoVars.size(); i++) {
773         ASSERT(parameters.hasDefaultParameterValues());
774         Variable var = variable(valuesToMoveIntoVars[i].first);
775         RegisterID* scope = emitResolveScope(nullptr, var);
776         emitPutToScope(scope, var, valuesToMoveIntoVars[i].second.get(), DoNotThrowIfNotFound, NotInitialization);
777     }
778
779     if (!parameters.hasDefaultParameterValues()) {
780         ASSERT(!valuesToMoveIntoVars.size());
781         // Initialize destructuring parameters the old way as if we don't have any default parameter values.
782         // If we have default parameter values, we handle this case above.
783         for (unsigned i = 0; i < parameters.size(); i++) {
784             DestructuringPatternNode* pattern = parameters.at(i).first;
785             if (!pattern->isBindingNode() && !pattern->isRestParameter()) {
786                 RefPtr<RegisterID> parameterValue = &registerFor(virtualRegisterForArgument(1 + i));
787                 pattern->bindValue(*this, parameterValue.get());
788             }
789         }
790     }
791 }
792
793 RegisterID* BytecodeGenerator::initializeNextParameter()
794 {
795     VirtualRegister reg = virtualRegisterForArgument(m_codeBlock->numParameters());
796     RegisterID& parameter = registerFor(reg);
797     parameter.setIndex(reg.offset());
798     m_codeBlock->addParameter();
799     return &parameter;
800 }
801
802 void BytecodeGenerator::initializeVarLexicalEnvironment(int symbolTableConstantIndex)
803 {
804     RELEASE_ASSERT(m_lexicalEnvironmentRegister);
805     m_codeBlock->setActivationRegister(m_lexicalEnvironmentRegister->virtualRegister());
806     emitOpcode(op_create_lexical_environment);
807     instructions().append(m_lexicalEnvironmentRegister->index());
808     instructions().append(scopeRegister()->index());
809     instructions().append(symbolTableConstantIndex);
810     instructions().append(addConstantValue(jsUndefined())->index());
811
812     emitOpcode(op_mov);
813     instructions().append(scopeRegister()->index());
814     instructions().append(m_lexicalEnvironmentRegister->index());
815 }
816
817 UniquedStringImpl* BytecodeGenerator::visibleNameForParameter(DestructuringPatternNode* pattern)
818 {
819     if (pattern->isBindingNode()) {
820         const Identifier& ident = static_cast<const BindingNode*>(pattern)->boundProperty();
821         if (!m_functions.contains(ident.impl()))
822             return ident.impl();
823     }
824     return nullptr;
825 }
826
827 RegisterID* BytecodeGenerator::newRegister()
828 {
829     m_calleeRegisters.append(virtualRegisterForLocal(m_calleeRegisters.size()));
830     int numCalleeRegisters = max<int>(m_codeBlock->m_numCalleeRegisters, m_calleeRegisters.size());
831     numCalleeRegisters = WTF::roundUpToMultipleOf(stackAlignmentRegisters(), numCalleeRegisters);
832     m_codeBlock->m_numCalleeRegisters = numCalleeRegisters;
833     return &m_calleeRegisters.last();
834 }
835
836 void BytecodeGenerator::reclaimFreeRegisters()
837 {
838     while (m_calleeRegisters.size() && !m_calleeRegisters.last().refCount())
839         m_calleeRegisters.removeLast();
840 }
841
842 RegisterID* BytecodeGenerator::newBlockScopeVariable()
843 {
844     reclaimFreeRegisters();
845
846     return newRegister();
847 }
848
849 RegisterID* BytecodeGenerator::newTemporary()
850 {
851     reclaimFreeRegisters();
852
853     RegisterID* result = newRegister();
854     result->setTemporary();
855     return result;
856 }
857
858 LabelScopePtr BytecodeGenerator::newLabelScope(LabelScope::Type type, const Identifier* name)
859 {
860     // Reclaim free label scopes.
861     while (m_labelScopes.size() && !m_labelScopes.last().refCount())
862         m_labelScopes.removeLast();
863
864     // Allocate new label scope.
865     LabelScope scope(type, name, labelScopeDepth(), newLabel(), type == LabelScope::Loop ? newLabel() : PassRefPtr<Label>()); // Only loops have continue targets.
866     m_labelScopes.append(scope);
867     return LabelScopePtr(m_labelScopes, m_labelScopes.size() - 1);
868 }
869
870 PassRefPtr<Label> BytecodeGenerator::newLabel()
871 {
872     // Reclaim free label IDs.
873     while (m_labels.size() && !m_labels.last().refCount())
874         m_labels.removeLast();
875
876     // Allocate new label ID.
877     m_labels.append(*this);
878     return &m_labels.last();
879 }
880
881 PassRefPtr<Label> BytecodeGenerator::emitLabel(Label* l0)
882 {
883     unsigned newLabelIndex = instructions().size();
884     l0->setLocation(newLabelIndex);
885
886     if (m_codeBlock->numberOfJumpTargets()) {
887         unsigned lastLabelIndex = m_codeBlock->lastJumpTarget();
888         ASSERT(lastLabelIndex <= newLabelIndex);
889         if (newLabelIndex == lastLabelIndex) {
890             // Peephole optimizations have already been disabled by emitting the last label
891             return l0;
892         }
893     }
894
895     m_codeBlock->addJumpTarget(newLabelIndex);
896
897     // This disables peephole optimizations when an instruction is a jump target
898     m_lastOpcodeID = op_end;
899     return l0;
900 }
901
902 void BytecodeGenerator::emitOpcode(OpcodeID opcodeID)
903 {
904 #ifndef NDEBUG
905     size_t opcodePosition = instructions().size();
906     ASSERT(opcodePosition - m_lastOpcodePosition == opcodeLength(m_lastOpcodeID) || m_lastOpcodeID == op_end);
907     m_lastOpcodePosition = opcodePosition;
908 #endif
909     instructions().append(opcodeID);
910     m_lastOpcodeID = opcodeID;
911 }
912
913 UnlinkedArrayProfile BytecodeGenerator::newArrayProfile()
914 {
915     return m_codeBlock->addArrayProfile();
916 }
917
918 UnlinkedArrayAllocationProfile BytecodeGenerator::newArrayAllocationProfile()
919 {
920     return m_codeBlock->addArrayAllocationProfile();
921 }
922
923 UnlinkedObjectAllocationProfile BytecodeGenerator::newObjectAllocationProfile()
924 {
925     return m_codeBlock->addObjectAllocationProfile();
926 }
927
928 UnlinkedValueProfile BytecodeGenerator::emitProfiledOpcode(OpcodeID opcodeID)
929 {
930     UnlinkedValueProfile result = m_codeBlock->addValueProfile();
931     emitOpcode(opcodeID);
932     return result;
933 }
934
935 void BytecodeGenerator::emitLoopHint()
936 {
937     emitOpcode(op_loop_hint);
938 }
939
940 void BytecodeGenerator::retrieveLastBinaryOp(int& dstIndex, int& src1Index, int& src2Index)
941 {
942     ASSERT(instructions().size() >= 4);
943     size_t size = instructions().size();
944     dstIndex = instructions().at(size - 3).u.operand;
945     src1Index = instructions().at(size - 2).u.operand;
946     src2Index = instructions().at(size - 1).u.operand;
947 }
948
949 void BytecodeGenerator::retrieveLastUnaryOp(int& dstIndex, int& srcIndex)
950 {
951     ASSERT(instructions().size() >= 3);
952     size_t size = instructions().size();
953     dstIndex = instructions().at(size - 2).u.operand;
954     srcIndex = instructions().at(size - 1).u.operand;
955 }
956
957 void ALWAYS_INLINE BytecodeGenerator::rewindBinaryOp()
958 {
959     ASSERT(instructions().size() >= 4);
960     instructions().shrink(instructions().size() - 4);
961     m_lastOpcodeID = op_end;
962 }
963
964 void ALWAYS_INLINE BytecodeGenerator::rewindUnaryOp()
965 {
966     ASSERT(instructions().size() >= 3);
967     instructions().shrink(instructions().size() - 3);
968     m_lastOpcodeID = op_end;
969 }
970
971 PassRefPtr<Label> BytecodeGenerator::emitJump(Label* target)
972 {
973     size_t begin = instructions().size();
974     emitOpcode(op_jmp);
975     instructions().append(target->bind(begin, instructions().size()));
976     return target;
977 }
978
979 PassRefPtr<Label> BytecodeGenerator::emitJumpIfTrue(RegisterID* cond, Label* target)
980 {
981     if (m_lastOpcodeID == op_less) {
982         int dstIndex;
983         int src1Index;
984         int src2Index;
985
986         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
987
988         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
989             rewindBinaryOp();
990
991             size_t begin = instructions().size();
992             emitOpcode(op_jless);
993             instructions().append(src1Index);
994             instructions().append(src2Index);
995             instructions().append(target->bind(begin, instructions().size()));
996             return target;
997         }
998     } else if (m_lastOpcodeID == op_lesseq) {
999         int dstIndex;
1000         int src1Index;
1001         int src2Index;
1002
1003         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1004
1005         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1006             rewindBinaryOp();
1007
1008             size_t begin = instructions().size();
1009             emitOpcode(op_jlesseq);
1010             instructions().append(src1Index);
1011             instructions().append(src2Index);
1012             instructions().append(target->bind(begin, instructions().size()));
1013             return target;
1014         }
1015     } else if (m_lastOpcodeID == op_greater) {
1016         int dstIndex;
1017         int src1Index;
1018         int src2Index;
1019
1020         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1021
1022         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1023             rewindBinaryOp();
1024
1025             size_t begin = instructions().size();
1026             emitOpcode(op_jgreater);
1027             instructions().append(src1Index);
1028             instructions().append(src2Index);
1029             instructions().append(target->bind(begin, instructions().size()));
1030             return target;
1031         }
1032     } else if (m_lastOpcodeID == op_greatereq) {
1033         int dstIndex;
1034         int src1Index;
1035         int src2Index;
1036
1037         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1038
1039         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1040             rewindBinaryOp();
1041
1042             size_t begin = instructions().size();
1043             emitOpcode(op_jgreatereq);
1044             instructions().append(src1Index);
1045             instructions().append(src2Index);
1046             instructions().append(target->bind(begin, instructions().size()));
1047             return target;
1048         }
1049     } else if (m_lastOpcodeID == op_eq_null && target->isForward()) {
1050         int dstIndex;
1051         int srcIndex;
1052
1053         retrieveLastUnaryOp(dstIndex, srcIndex);
1054
1055         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1056             rewindUnaryOp();
1057
1058             size_t begin = instructions().size();
1059             emitOpcode(op_jeq_null);
1060             instructions().append(srcIndex);
1061             instructions().append(target->bind(begin, instructions().size()));
1062             return target;
1063         }
1064     } else if (m_lastOpcodeID == op_neq_null && target->isForward()) {
1065         int dstIndex;
1066         int srcIndex;
1067
1068         retrieveLastUnaryOp(dstIndex, srcIndex);
1069
1070         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1071             rewindUnaryOp();
1072
1073             size_t begin = instructions().size();
1074             emitOpcode(op_jneq_null);
1075             instructions().append(srcIndex);
1076             instructions().append(target->bind(begin, instructions().size()));
1077             return target;
1078         }
1079     }
1080
1081     size_t begin = instructions().size();
1082
1083     emitOpcode(op_jtrue);
1084     instructions().append(cond->index());
1085     instructions().append(target->bind(begin, instructions().size()));
1086     return target;
1087 }
1088
1089 PassRefPtr<Label> BytecodeGenerator::emitJumpIfFalse(RegisterID* cond, Label* target)
1090 {
1091     if (m_lastOpcodeID == op_less && target->isForward()) {
1092         int dstIndex;
1093         int src1Index;
1094         int src2Index;
1095
1096         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1097
1098         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1099             rewindBinaryOp();
1100
1101             size_t begin = instructions().size();
1102             emitOpcode(op_jnless);
1103             instructions().append(src1Index);
1104             instructions().append(src2Index);
1105             instructions().append(target->bind(begin, instructions().size()));
1106             return target;
1107         }
1108     } else if (m_lastOpcodeID == op_lesseq && target->isForward()) {
1109         int dstIndex;
1110         int src1Index;
1111         int src2Index;
1112
1113         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1114
1115         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1116             rewindBinaryOp();
1117
1118             size_t begin = instructions().size();
1119             emitOpcode(op_jnlesseq);
1120             instructions().append(src1Index);
1121             instructions().append(src2Index);
1122             instructions().append(target->bind(begin, instructions().size()));
1123             return target;
1124         }
1125     } else if (m_lastOpcodeID == op_greater && target->isForward()) {
1126         int dstIndex;
1127         int src1Index;
1128         int src2Index;
1129
1130         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1131
1132         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1133             rewindBinaryOp();
1134
1135             size_t begin = instructions().size();
1136             emitOpcode(op_jngreater);
1137             instructions().append(src1Index);
1138             instructions().append(src2Index);
1139             instructions().append(target->bind(begin, instructions().size()));
1140             return target;
1141         }
1142     } else if (m_lastOpcodeID == op_greatereq && target->isForward()) {
1143         int dstIndex;
1144         int src1Index;
1145         int src2Index;
1146
1147         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1148
1149         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1150             rewindBinaryOp();
1151
1152             size_t begin = instructions().size();
1153             emitOpcode(op_jngreatereq);
1154             instructions().append(src1Index);
1155             instructions().append(src2Index);
1156             instructions().append(target->bind(begin, instructions().size()));
1157             return target;
1158         }
1159     } else if (m_lastOpcodeID == op_not) {
1160         int dstIndex;
1161         int srcIndex;
1162
1163         retrieveLastUnaryOp(dstIndex, srcIndex);
1164
1165         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1166             rewindUnaryOp();
1167
1168             size_t begin = instructions().size();
1169             emitOpcode(op_jtrue);
1170             instructions().append(srcIndex);
1171             instructions().append(target->bind(begin, instructions().size()));
1172             return target;
1173         }
1174     } else if (m_lastOpcodeID == op_eq_null && target->isForward()) {
1175         int dstIndex;
1176         int srcIndex;
1177
1178         retrieveLastUnaryOp(dstIndex, srcIndex);
1179
1180         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1181             rewindUnaryOp();
1182
1183             size_t begin = instructions().size();
1184             emitOpcode(op_jneq_null);
1185             instructions().append(srcIndex);
1186             instructions().append(target->bind(begin, instructions().size()));
1187             return target;
1188         }
1189     } else if (m_lastOpcodeID == op_neq_null && target->isForward()) {
1190         int dstIndex;
1191         int srcIndex;
1192
1193         retrieveLastUnaryOp(dstIndex, srcIndex);
1194
1195         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1196             rewindUnaryOp();
1197
1198             size_t begin = instructions().size();
1199             emitOpcode(op_jeq_null);
1200             instructions().append(srcIndex);
1201             instructions().append(target->bind(begin, instructions().size()));
1202             return target;
1203         }
1204     }
1205
1206     size_t begin = instructions().size();
1207     emitOpcode(op_jfalse);
1208     instructions().append(cond->index());
1209     instructions().append(target->bind(begin, instructions().size()));
1210     return target;
1211 }
1212
1213 PassRefPtr<Label> BytecodeGenerator::emitJumpIfNotFunctionCall(RegisterID* cond, Label* target)
1214 {
1215     size_t begin = instructions().size();
1216
1217     emitOpcode(op_jneq_ptr);
1218     instructions().append(cond->index());
1219     instructions().append(Special::CallFunction);
1220     instructions().append(target->bind(begin, instructions().size()));
1221     return target;
1222 }
1223
1224 PassRefPtr<Label> BytecodeGenerator::emitJumpIfNotFunctionApply(RegisterID* cond, Label* target)
1225 {
1226     size_t begin = instructions().size();
1227
1228     emitOpcode(op_jneq_ptr);
1229     instructions().append(cond->index());
1230     instructions().append(Special::ApplyFunction);
1231     instructions().append(target->bind(begin, instructions().size()));
1232     return target;
1233 }
1234
1235 bool BytecodeGenerator::hasConstant(const Identifier& ident) const
1236 {
1237     UniquedStringImpl* rep = ident.impl();
1238     return m_identifierMap.contains(rep);
1239 }
1240
1241 unsigned BytecodeGenerator::addConstant(const Identifier& ident)
1242 {
1243     UniquedStringImpl* rep = ident.impl();
1244     IdentifierMap::AddResult result = m_identifierMap.add(rep, m_codeBlock->numberOfIdentifiers());
1245     if (result.isNewEntry)
1246         m_codeBlock->addIdentifier(ident);
1247
1248     return result.iterator->value;
1249 }
1250
1251 // We can't hash JSValue(), so we use a dedicated data member to cache it.
1252 RegisterID* BytecodeGenerator::addConstantEmptyValue()
1253 {
1254     if (!m_emptyValueRegister) {
1255         int index = m_nextConstantOffset;
1256         m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
1257         ++m_nextConstantOffset;
1258         m_codeBlock->addConstant(JSValue());
1259         m_emptyValueRegister = &m_constantPoolRegisters[index];
1260     }
1261
1262     return m_emptyValueRegister;
1263 }
1264
1265 RegisterID* BytecodeGenerator::addConstantValue(JSValue v, SourceCodeRepresentation sourceCodeRepresentation)
1266 {
1267     if (!v)
1268         return addConstantEmptyValue();
1269
1270     int index = m_nextConstantOffset;
1271
1272     if (sourceCodeRepresentation == SourceCodeRepresentation::Double && v.isInt32())
1273         v = jsDoubleNumber(v.asNumber());
1274     EncodedJSValueWithRepresentation valueMapKey { JSValue::encode(v), sourceCodeRepresentation };
1275     JSValueMap::AddResult result = m_jsValueMap.add(valueMapKey, m_nextConstantOffset);
1276     if (result.isNewEntry) {
1277         m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
1278         ++m_nextConstantOffset;
1279         m_codeBlock->addConstant(v, sourceCodeRepresentation);
1280     } else
1281         index = result.iterator->value;
1282     return &m_constantPoolRegisters[index];
1283 }
1284
1285 RegisterID* BytecodeGenerator::emitMoveLinkTimeConstant(RegisterID* dst, LinkTimeConstant type)
1286 {
1287     unsigned constantIndex = static_cast<unsigned>(type);
1288     if (!m_linkTimeConstantRegisters[constantIndex]) {
1289         int index = m_nextConstantOffset;
1290         m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
1291         ++m_nextConstantOffset;
1292         m_codeBlock->addConstant(type);
1293         m_linkTimeConstantRegisters[constantIndex] = &m_constantPoolRegisters[index];
1294     }
1295
1296     emitOpcode(op_mov);
1297     instructions().append(dst->index());
1298     instructions().append(m_linkTimeConstantRegisters[constantIndex]->index());
1299
1300     return dst;
1301 }
1302
1303 unsigned BytecodeGenerator::addRegExp(RegExp* r)
1304 {
1305     return m_codeBlock->addRegExp(r);
1306 }
1307
1308 RegisterID* BytecodeGenerator::emitMoveEmptyValue(RegisterID* dst)
1309 {
1310     RefPtr<RegisterID> emptyValue = addConstantEmptyValue();
1311
1312     emitOpcode(op_mov);
1313     instructions().append(dst->index());
1314     instructions().append(emptyValue->index());
1315     return dst;
1316 }
1317
1318 RegisterID* BytecodeGenerator::emitMove(RegisterID* dst, RegisterID* src)
1319 {
1320     ASSERT(src != m_emptyValueRegister);
1321
1322     m_staticPropertyAnalyzer.mov(dst->index(), src->index());
1323     emitOpcode(op_mov);
1324     instructions().append(dst->index());
1325     instructions().append(src->index());
1326
1327     return dst;
1328 }
1329
1330 RegisterID* BytecodeGenerator::emitUnaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src)
1331 {
1332     emitOpcode(opcodeID);
1333     instructions().append(dst->index());
1334     instructions().append(src->index());
1335     return dst;
1336 }
1337
1338 RegisterID* BytecodeGenerator::emitInc(RegisterID* srcDst)
1339 {
1340     emitOpcode(op_inc);
1341     instructions().append(srcDst->index());
1342     return srcDst;
1343 }
1344
1345 RegisterID* BytecodeGenerator::emitDec(RegisterID* srcDst)
1346 {
1347     emitOpcode(op_dec);
1348     instructions().append(srcDst->index());
1349     return srcDst;
1350 }
1351
1352 RegisterID* BytecodeGenerator::emitBinaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2, OperandTypes types)
1353 {
1354     emitOpcode(opcodeID);
1355     instructions().append(dst->index());
1356     instructions().append(src1->index());
1357     instructions().append(src2->index());
1358
1359     if (opcodeID == op_bitor || opcodeID == op_bitand || opcodeID == op_bitxor ||
1360         opcodeID == op_add || opcodeID == op_mul || opcodeID == op_sub || opcodeID == op_div)
1361         instructions().append(types.toInt());
1362
1363     return dst;
1364 }
1365
1366 RegisterID* BytecodeGenerator::emitEqualityOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2)
1367 {
1368     if (m_lastOpcodeID == op_typeof) {
1369         int dstIndex;
1370         int srcIndex;
1371
1372         retrieveLastUnaryOp(dstIndex, srcIndex);
1373
1374         if (src1->index() == dstIndex
1375             && src1->isTemporary()
1376             && m_codeBlock->isConstantRegisterIndex(src2->index())
1377             && m_codeBlock->constantRegister(src2->index()).get().isString()) {
1378             const String& value = asString(m_codeBlock->constantRegister(src2->index()).get())->tryGetValue();
1379             if (value == "undefined") {
1380                 rewindUnaryOp();
1381                 emitOpcode(op_is_undefined);
1382                 instructions().append(dst->index());
1383                 instructions().append(srcIndex);
1384                 return dst;
1385             }
1386             if (value == "boolean") {
1387                 rewindUnaryOp();
1388                 emitOpcode(op_is_boolean);
1389                 instructions().append(dst->index());
1390                 instructions().append(srcIndex);
1391                 return dst;
1392             }
1393             if (value == "number") {
1394                 rewindUnaryOp();
1395                 emitOpcode(op_is_number);
1396                 instructions().append(dst->index());
1397                 instructions().append(srcIndex);
1398                 return dst;
1399             }
1400             if (value == "string") {
1401                 rewindUnaryOp();
1402                 emitOpcode(op_is_string);
1403                 instructions().append(dst->index());
1404                 instructions().append(srcIndex);
1405                 return dst;
1406             }
1407             if (value == "object") {
1408                 rewindUnaryOp();
1409                 emitOpcode(op_is_object_or_null);
1410                 instructions().append(dst->index());
1411                 instructions().append(srcIndex);
1412                 return dst;
1413             }
1414             if (value == "function") {
1415                 rewindUnaryOp();
1416                 emitOpcode(op_is_function);
1417                 instructions().append(dst->index());
1418                 instructions().append(srcIndex);
1419                 return dst;
1420             }
1421         }
1422     }
1423
1424     emitOpcode(opcodeID);
1425     instructions().append(dst->index());
1426     instructions().append(src1->index());
1427     instructions().append(src2->index());
1428     return dst;
1429 }
1430
1431 void BytecodeGenerator::emitTypeProfilerExpressionInfo(const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1432 {
1433     ASSERT(vm()->typeProfiler());
1434
1435     unsigned start = startDivot.offset; // Ranges are inclusive of their endpoints, AND 0 indexed.
1436     unsigned end = endDivot.offset - 1; // End Ranges already go one past the inclusive range, so subtract 1.
1437     unsigned instructionOffset = instructions().size() - 1;
1438     m_codeBlock->addTypeProfilerExpressionInfo(instructionOffset, start, end);
1439 }
1440
1441 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag flag)
1442 {
1443     if (!vm()->typeProfiler())
1444         return;
1445
1446     if (!registerToProfile)
1447         return;
1448
1449     emitOpcode(op_profile_type);
1450     instructions().append(registerToProfile->index());
1451     instructions().append(0);
1452     instructions().append(flag);
1453     instructions().append(0);
1454     instructions().append(resolveType());
1455
1456     // Don't emit expression info for this version of profile type. This generally means
1457     // we're profiling information for something that isn't in the actual text of a JavaScript
1458     // program. For example, implicit return undefined from a function call.
1459 }
1460
1461 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1462 {
1463     emitProfileType(registerToProfile, ProfileTypeBytecodeDoesNotHaveGlobalID, startDivot, endDivot);
1464 }
1465
1466 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag flag, const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1467 {
1468     if (!vm()->typeProfiler())
1469         return;
1470
1471     if (!registerToProfile)
1472         return;
1473
1474     // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType?
1475     emitOpcode(op_profile_type);
1476     instructions().append(registerToProfile->index());
1477     instructions().append(0);
1478     instructions().append(flag);
1479     instructions().append(0);
1480     instructions().append(resolveType());
1481
1482     emitTypeProfilerExpressionInfo(startDivot, endDivot);
1483 }
1484
1485 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, const Variable& var, const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1486 {
1487     if (!vm()->typeProfiler())
1488         return;
1489
1490     if (!registerToProfile)
1491         return;
1492
1493     ProfileTypeBytecodeFlag flag;
1494     int symbolTableOrScopeDepth;
1495     if (var.local() || var.offset().isScope()) {
1496         flag = ProfileTypeBytecodeLocallyResolved;
1497         symbolTableOrScopeDepth = var.symbolTableConstantIndex();
1498     } else {
1499         flag = ProfileTypeBytecodeClosureVar;
1500         symbolTableOrScopeDepth = localScopeDepth();
1501     }
1502
1503     // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType?
1504     emitOpcode(op_profile_type);
1505     instructions().append(registerToProfile->index());
1506     instructions().append(symbolTableOrScopeDepth);
1507     instructions().append(flag);
1508     instructions().append(addConstant(var.ident()));
1509     instructions().append(resolveType());
1510
1511     emitTypeProfilerExpressionInfo(startDivot, endDivot);
1512 }
1513
1514 void BytecodeGenerator::emitProfileControlFlow(int textOffset)
1515 {
1516     if (vm()->controlFlowProfiler()) {
1517         RELEASE_ASSERT(textOffset >= 0);
1518         size_t bytecodeOffset = instructions().size();
1519         m_codeBlock->addOpProfileControlFlowBytecodeOffset(bytecodeOffset);
1520
1521         emitOpcode(op_profile_control_flow);
1522         instructions().append(textOffset);
1523     }
1524 }
1525
1526 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, bool b)
1527 {
1528     return emitLoad(dst, jsBoolean(b));
1529 }
1530
1531 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, const Identifier& identifier)
1532 {
1533     JSString*& stringInMap = m_stringMap.add(identifier.impl(), nullptr).iterator->value;
1534     if (!stringInMap)
1535         stringInMap = jsOwnedString(vm(), identifier.string());
1536     return emitLoad(dst, JSValue(stringInMap));
1537 }
1538
1539 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, JSValue v, SourceCodeRepresentation sourceCodeRepresentation)
1540 {
1541     RegisterID* constantID = addConstantValue(v, sourceCodeRepresentation);
1542     if (dst)
1543         return emitMove(dst, constantID);
1544     return constantID;
1545 }
1546
1547 RegisterID* BytecodeGenerator::emitLoadGlobalObject(RegisterID* dst)
1548 {
1549     if (!m_globalObjectRegister) {
1550         int index = m_nextConstantOffset;
1551         m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
1552         ++m_nextConstantOffset;
1553         m_codeBlock->addConstant(JSValue());
1554         m_globalObjectRegister = &m_constantPoolRegisters[index];
1555         m_codeBlock->setGlobalObjectRegister(VirtualRegister(index));
1556     }
1557     if (dst)
1558         emitMove(dst, m_globalObjectRegister);
1559     return m_globalObjectRegister;
1560 }
1561
1562 template<typename LookUpVarKindFunctor>
1563 bool BytecodeGenerator::instantiateLexicalVariables(const VariableEnvironment& lexicalVariables, SymbolTable* symbolTable, ScopeRegisterType scopeRegisterType, LookUpVarKindFunctor lookUpVarKind)
1564 {
1565     bool hasCapturedVariables = false;
1566     {
1567         ConcurrentJITLocker locker(symbolTable->m_lock);
1568         for (auto& entry : lexicalVariables) {
1569             ASSERT(entry.value.isLet() || entry.value.isConst());
1570             ASSERT(!entry.value.isVar());
1571             SymbolTableEntry symbolTableEntry = symbolTable->get(locker, entry.key.get());
1572             ASSERT(symbolTableEntry.isNull());
1573
1574             // Imported bindings which are not the namespace bindings are not allocated
1575             // in the module environment as usual variables' way.
1576             // And since these types of the variables only seen in the module environment,
1577             // other lexical environment need not to take care this.
1578             if (entry.value.isImported() && !entry.value.isImportedNamespace())
1579                 continue;
1580
1581             VarKind varKind = lookUpVarKind(entry.key.get(), entry.value);
1582             VarOffset varOffset;
1583             if (varKind == VarKind::Scope) {
1584                 varOffset = VarOffset(symbolTable->takeNextScopeOffset(locker));
1585                 hasCapturedVariables = true;
1586             } else {
1587                 ASSERT(varKind == VarKind::Stack);
1588                 RegisterID* local;
1589                 if (scopeRegisterType == ScopeRegisterType::Block) {
1590                     local = newBlockScopeVariable();
1591                     local->ref();
1592                 } else
1593                     local = addVar();
1594                 varOffset = VarOffset(local->virtualRegister());
1595             }
1596
1597             SymbolTableEntry newEntry(varOffset, entry.value.isConst() ? ReadOnly : 0);
1598             symbolTable->add(locker, entry.key.get(), newEntry);
1599         }
1600     }
1601     return hasCapturedVariables;
1602 }
1603
1604 void BytecodeGenerator::emitPrefillStackTDZVariables(const VariableEnvironment& lexicalVariables, SymbolTable* symbolTable)
1605 {
1606     // Prefill stack variables with the TDZ empty value.
1607     // Scope variables will be initialized to the TDZ empty value when JSLexicalEnvironment is allocated.
1608     for (auto& entry : lexicalVariables) {
1609         // Imported bindings which are not the namespace bindings are not allocated
1610         // in the module environment as usual variables' way.
1611         // And since these types of the variables only seen in the module environment,
1612         // other lexical environment need not to take care this.
1613         if (entry.value.isImported() && !entry.value.isImportedNamespace())
1614             continue;
1615
1616         SymbolTableEntry symbolTableEntry = symbolTable->get(entry.key.get());
1617         ASSERT(!symbolTableEntry.isNull());
1618         VarOffset offset = symbolTableEntry.varOffset();
1619         if (offset.isScope())
1620             continue;
1621
1622         ASSERT(offset.isStack());
1623         emitMoveEmptyValue(&registerFor(offset.stackOffset()));
1624     }
1625 }
1626
1627 void BytecodeGenerator::pushLexicalScope(VariableEnvironmentNode* node, bool canOptimizeTDZChecks, RegisterID** constantSymbolTableResult)
1628 {
1629     VariableEnvironment& environment = node->lexicalVariables();
1630     pushLexicalScopeInternal(environment, canOptimizeTDZChecks, constantSymbolTableResult, TDZRequirement::UnderTDZ, ScopeType::LetConstScope, ScopeRegisterType::Block);
1631 }
1632
1633 void BytecodeGenerator::pushLexicalScopeInternal(VariableEnvironment& environment, bool canOptimizeTDZChecks, 
1634     RegisterID** constantSymbolTableResult, TDZRequirement tdzRequirement, ScopeType scopeType, ScopeRegisterType scopeRegisterType)
1635 {
1636     if (!environment.size())
1637         return;
1638
1639     if (m_shouldEmitDebugHooks)
1640         environment.markAllVariablesAsCaptured();
1641
1642     Strong<SymbolTable> symbolTable(*m_vm, SymbolTable::create(*m_vm));
1643     switch (scopeType) {
1644     case ScopeType::CatchScope:
1645         symbolTable->setScopeType(SymbolTable::ScopeType::CatchScope);
1646         break;
1647     case ScopeType::LetConstScope:
1648         symbolTable->setScopeType(SymbolTable::ScopeType::LexicalScope);
1649         break;
1650     case ScopeType::FunctionNameScope:
1651         symbolTable->setScopeType(SymbolTable::ScopeType::FunctionNameScope);
1652         break;
1653     }
1654
1655     auto lookUpVarKind = [] (UniquedStringImpl*, const VariableEnvironmentEntry& entry) -> VarKind {
1656         return entry.isCaptured() ? VarKind::Scope : VarKind::Stack;
1657     };
1658
1659     bool hasCapturedVariables = instantiateLexicalVariables(environment, symbolTable.get(), scopeRegisterType, lookUpVarKind);
1660
1661     RegisterID* newScope = nullptr;
1662     RegisterID* constantSymbolTable = nullptr;
1663     int symbolTableConstantIndex = 0;
1664     if (vm()->typeProfiler()) {
1665         constantSymbolTable = addConstantValue(symbolTable.get());
1666         symbolTableConstantIndex = constantSymbolTable->index();
1667     }
1668     if (hasCapturedVariables) {
1669         if (scopeRegisterType == ScopeRegisterType::Block) {
1670             newScope = newBlockScopeVariable();
1671             newScope->ref();
1672         } else
1673             newScope = addVar();
1674         if (!constantSymbolTable) {
1675             ASSERT(!vm()->typeProfiler());
1676             constantSymbolTable = addConstantValue(symbolTable->cloneScopePart(*m_vm));
1677             symbolTableConstantIndex = constantSymbolTable->index();
1678         }
1679         if (constantSymbolTableResult)
1680             *constantSymbolTableResult = constantSymbolTable;
1681
1682         emitOpcode(op_create_lexical_environment);
1683         instructions().append(newScope->index());
1684         instructions().append(scopeRegister()->index());
1685         instructions().append(constantSymbolTable->index());
1686         instructions().append(addConstantValue(tdzRequirement == TDZRequirement::UnderTDZ ? jsTDZValue() : jsUndefined())->index());
1687
1688         emitMove(scopeRegister(), newScope);
1689
1690         pushScopedControlFlowContext();
1691     }
1692
1693     m_symbolTableStack.append(SymbolTableStackEntry{ symbolTable, newScope, false, symbolTableConstantIndex });
1694     if (tdzRequirement == TDZRequirement::UnderTDZ)
1695         m_TDZStack.append(std::make_pair(environment, canOptimizeTDZChecks));
1696
1697     if (tdzRequirement == TDZRequirement::UnderTDZ)
1698         emitPrefillStackTDZVariables(environment, symbolTable.get());
1699 }
1700
1701 void BytecodeGenerator::popLexicalScope(VariableEnvironmentNode* node)
1702 {
1703     VariableEnvironment& environment = node->lexicalVariables();
1704     popLexicalScopeInternal(environment, TDZRequirement::UnderTDZ);
1705 }
1706
1707 void BytecodeGenerator::popLexicalScopeInternal(VariableEnvironment& environment, TDZRequirement tdzRequirement)
1708 {
1709     // NOTE: This function only makes sense for scopes that aren't ScopeRegisterType::Var (only function name scope right now is ScopeRegisterType::Var).
1710     // This doesn't make sense for ScopeRegisterType::Var because we deref RegisterIDs here.
1711     if (!environment.size())
1712         return;
1713
1714     if (m_shouldEmitDebugHooks)
1715         environment.markAllVariablesAsCaptured();
1716
1717     SymbolTableStackEntry stackEntry = m_symbolTableStack.takeLast();
1718     Strong<SymbolTable> symbolTable = stackEntry.m_symbolTable;
1719     ConcurrentJITLocker locker(symbolTable->m_lock);
1720     bool hasCapturedVariables = false;
1721     for (auto& entry : environment) {
1722         if (entry.value.isCaptured()) {
1723             hasCapturedVariables = true;
1724             continue;
1725         }
1726         SymbolTableEntry symbolTableEntry = symbolTable->get(locker, entry.key.get());
1727         ASSERT(!symbolTableEntry.isNull());
1728         VarOffset offset = symbolTableEntry.varOffset();
1729         ASSERT(offset.isStack());
1730         RegisterID* local = &registerFor(offset.stackOffset());
1731         local->deref();
1732     }
1733
1734     if (hasCapturedVariables) {
1735         RELEASE_ASSERT(stackEntry.m_scope);
1736         emitPopScope(scopeRegister(), stackEntry.m_scope);
1737         popScopedControlFlowContext();
1738         stackEntry.m_scope->deref();
1739     }
1740
1741     if (tdzRequirement == TDZRequirement::UnderTDZ)
1742         m_TDZStack.removeLast();
1743 }
1744
1745 void BytecodeGenerator::prepareLexicalScopeForNextForLoopIteration(VariableEnvironmentNode* node, RegisterID* loopSymbolTable)
1746 {
1747     VariableEnvironment& environment = node->lexicalVariables();
1748     if (!environment.size())
1749         return;
1750     if (m_shouldEmitDebugHooks)
1751         environment.markAllVariablesAsCaptured();
1752     if (!environment.hasCapturedVariables())
1753         return;
1754
1755     RELEASE_ASSERT(loopSymbolTable);
1756
1757     // This function needs to do setup for a for loop's activation if any of
1758     // the for loop's lexically declared variables are captured (that is, variables
1759     // declared in the loop header, not the loop body). This function needs to
1760     // make a copy of the current activation and copy the values from the previous
1761     // activation into the new activation because each iteration of a for loop
1762     // gets a new activation.
1763
1764     SymbolTableStackEntry stackEntry = m_symbolTableStack.last();
1765     Strong<SymbolTable> symbolTable = stackEntry.m_symbolTable;
1766     RegisterID* loopScope = stackEntry.m_scope;
1767     ASSERT(symbolTable->scopeSize());
1768     ASSERT(loopScope);
1769     Vector<std::pair<RegisterID*, Identifier>> activationValuesToCopyOver;
1770
1771     {
1772         ConcurrentJITLocker locker(symbolTable->m_lock);
1773         activationValuesToCopyOver.reserveInitialCapacity(symbolTable->scopeSize());
1774
1775         for (auto end = symbolTable->end(locker), ptr = symbolTable->begin(locker); ptr != end; ++ptr) {
1776             if (!ptr->value.varOffset().isScope())
1777                 continue;
1778
1779             RefPtr<UniquedStringImpl> ident = ptr->key;
1780             Identifier identifier = Identifier::fromUid(m_vm, ident.get());
1781
1782             RegisterID* transitionValue = newBlockScopeVariable();
1783             transitionValue->ref();
1784             emitGetFromScope(transitionValue, loopScope, variableForLocalEntry(identifier, ptr->value, loopSymbolTable->index(), true), DoNotThrowIfNotFound);
1785             activationValuesToCopyOver.uncheckedAppend(std::make_pair(transitionValue, identifier));
1786         }
1787     }
1788
1789     // We need this dynamic behavior of the executing code to ensure
1790     // each loop iteration has a new activation object. (It's pretty ugly).
1791     // Also, this new activation needs to be assigned to the same register
1792     // as the previous scope because the loop body is compiled under
1793     // the assumption that the scope's register index is constant even
1794     // though the value in that register will change on each loop iteration.
1795     RefPtr<RegisterID> parentScope = emitGetParentScope(newTemporary(), loopScope);
1796     emitMove(scopeRegister(), parentScope.get());
1797
1798     emitOpcode(op_create_lexical_environment);
1799     instructions().append(loopScope->index());
1800     instructions().append(scopeRegister()->index());
1801     instructions().append(loopSymbolTable->index());
1802     instructions().append(addConstantValue(jsTDZValue())->index());
1803
1804     emitMove(scopeRegister(), loopScope);
1805
1806     {
1807         ConcurrentJITLocker locker(symbolTable->m_lock);
1808         for (auto pair : activationValuesToCopyOver) {
1809             const Identifier& identifier = pair.second;
1810             SymbolTableEntry entry = symbolTable->get(locker, identifier.impl());
1811             RELEASE_ASSERT(!entry.isNull());
1812             RegisterID* transitionValue = pair.first;
1813             emitPutToScope(loopScope, variableForLocalEntry(identifier, entry, loopSymbolTable->index(), true), transitionValue, DoNotThrowIfNotFound, NotInitialization);
1814             transitionValue->deref();
1815         }
1816     }
1817 }
1818
1819 Variable BytecodeGenerator::variable(const Identifier& property)
1820 {
1821     if (property == propertyNames().thisIdentifier) {
1822         return Variable(property, VarOffset(thisRegister()->virtualRegister()), thisRegister(),
1823             ReadOnly, Variable::SpecialVariable, 0, false);
1824     }
1825     
1826     // We can optimize lookups if the lexical variable is found before a "with" or "catch"
1827     // scope because we're guaranteed static resolution. If we have to pass through
1828     // a "with" or "catch" scope we loose this guarantee.
1829     // We can't optimize cases like this:
1830     // {
1831     //     let x = ...;
1832     //     with (o) {
1833     //         doSomethingWith(x);
1834     //     }
1835     // }
1836     // Because we can't gaurantee static resolution on x.
1837     // But, in this case, we are guaranteed static resolution:
1838     // {
1839     //     let x = ...;
1840     //     with (o) {
1841     //         let x = ...;
1842     //         doSomethingWith(x);
1843     //     }
1844     // }
1845     for (unsigned i = m_symbolTableStack.size(); i--; ) {
1846         SymbolTableStackEntry& stackEntry = m_symbolTableStack[i];
1847         if (stackEntry.m_isWithScope)
1848             return Variable(property);
1849         Strong<SymbolTable>& symbolTable = stackEntry.m_symbolTable;
1850         SymbolTableEntry symbolTableEntry = symbolTable->get(property.impl());
1851         if (symbolTableEntry.isNull())
1852             continue;
1853         bool resultIsCallee = false;
1854         if (symbolTable->scopeType() == SymbolTable::ScopeType::FunctionNameScope) {
1855             if (m_usesNonStrictEval) {
1856                 // We don't know if an eval has introduced a "var" named the same thing as the function name scope variable name.
1857                 // We resort to dynamic lookup to answer this question.
1858                 Variable result = Variable(property);
1859                 return result;
1860             }
1861             resultIsCallee = true;
1862         }
1863         Variable result = variableForLocalEntry(property, symbolTableEntry, stackEntry.m_symbolTableConstantIndex, symbolTable->scopeType() == SymbolTable::ScopeType::LexicalScope);
1864         if (resultIsCallee)
1865             result.setIsReadOnly();
1866         return result;
1867     }
1868
1869     return Variable(property);
1870 }
1871
1872 Variable BytecodeGenerator::variableForLocalEntry(
1873     const Identifier& property, const SymbolTableEntry& entry, int symbolTableConstantIndex, bool isLexicallyScoped)
1874 {
1875     VarOffset offset = entry.varOffset();
1876     
1877     RegisterID* local;
1878     if (offset.isStack())
1879         local = &registerFor(offset.stackOffset());
1880     else
1881         local = nullptr;
1882     
1883     return Variable(property, offset, local, entry.getAttributes(), Variable::NormalVariable, symbolTableConstantIndex, isLexicallyScoped);
1884 }
1885
1886 void BytecodeGenerator::createVariable(
1887     const Identifier& property, VarKind varKind, SymbolTable* symbolTable, ExistingVariableMode existingVariableMode)
1888 {
1889     ASSERT(property != propertyNames().thisIdentifier);
1890     ConcurrentJITLocker locker(symbolTable->m_lock);
1891     SymbolTableEntry entry = symbolTable->get(locker, property.impl());
1892     
1893     if (!entry.isNull()) {
1894         if (existingVariableMode == IgnoreExisting)
1895             return;
1896         
1897         // Do some checks to ensure that the variable we're being asked to create is sufficiently
1898         // compatible with the one we have already created.
1899
1900         VarOffset offset = entry.varOffset();
1901         
1902         // We can't change our minds about whether it's captured.
1903         if (offset.kind() != varKind) {
1904             dataLog(
1905                 "Trying to add variable called ", property, " as ", varKind,
1906                 " but it was already added as ", offset, ".\n");
1907             RELEASE_ASSERT_NOT_REACHED();
1908         }
1909
1910         return;
1911     }
1912     
1913     VarOffset varOffset;
1914     if (varKind == VarKind::Scope)
1915         varOffset = VarOffset(symbolTable->takeNextScopeOffset(locker));
1916     else {
1917         ASSERT(varKind == VarKind::Stack);
1918         varOffset = VarOffset(virtualRegisterForLocal(m_calleeRegisters.size()));
1919     }
1920     SymbolTableEntry newEntry(varOffset, 0);
1921     symbolTable->add(locker, property.impl(), newEntry);
1922     
1923     if (varKind == VarKind::Stack) {
1924         RegisterID* local = addVar();
1925         RELEASE_ASSERT(local->index() == varOffset.stackOffset().offset());
1926     }
1927 }
1928
1929 void BytecodeGenerator::emitCheckHasInstance(RegisterID* dst, RegisterID* value, RegisterID* base, Label* target)
1930 {
1931     size_t begin = instructions().size();
1932     emitOpcode(op_check_has_instance);
1933     instructions().append(dst->index());
1934     instructions().append(value->index());
1935     instructions().append(base->index());
1936     instructions().append(target->bind(begin, instructions().size()));
1937 }
1938
1939 // Indicates the least upper bound of resolve type based on local scope. The bytecode linker
1940 // will start with this ResolveType and compute the least upper bound including intercepting scopes.
1941 ResolveType BytecodeGenerator::resolveType()
1942 {
1943     for (unsigned i = m_symbolTableStack.size(); i--; ) {
1944         if (m_symbolTableStack[i].m_isWithScope)
1945             return Dynamic;
1946         if (m_usesNonStrictEval && m_symbolTableStack[i].m_symbolTable->scopeType() == SymbolTable::ScopeType::FunctionNameScope) {
1947             // We never want to assign to a FunctionNameScope. Returning Dynamic here achieves this goal.
1948             // If we aren't in non-strict eval mode, then NodesCodeGen needs to take care not to emit
1949             // a put_to_scope with the destination being the function name scope variable.
1950             return Dynamic;
1951         }
1952     }
1953
1954     if (m_usesNonStrictEval)
1955         return GlobalPropertyWithVarInjectionChecks;
1956     return GlobalProperty;
1957 }
1958
1959 RegisterID* BytecodeGenerator::emitResolveScope(RegisterID* dst, const Variable& variable)
1960 {
1961     switch (variable.offset().kind()) {
1962     case VarKind::Stack:
1963         return nullptr;
1964         
1965     case VarKind::DirectArgument:
1966         return argumentsRegister();
1967         
1968     case VarKind::Scope:
1969         // This always refers to the activation that *we* allocated, and not the current scope that code
1970         // lives in. Note that this will change once we have proper support for block scoping. Once that
1971         // changes, it will be correct for this code to return scopeRegister(). The only reason why we
1972         // don't do that already is that m_lexicalEnvironment is required by ConstDeclNode. ConstDeclNode
1973         // requires weird things because it is a shameful pile of nonsense, but block scoping would make
1974         // that code sensible and obviate the need for us to do bad things.
1975         for (unsigned i = m_symbolTableStack.size(); i--; ) {
1976             SymbolTableStackEntry& stackEntry = m_symbolTableStack[i];
1977             // We should not resolve a variable to VarKind::Scope if a "with" scope lies in between the current
1978             // scope and the resolved scope.
1979             RELEASE_ASSERT(!stackEntry.m_isWithScope);
1980
1981             if (stackEntry.m_symbolTable->get(variable.ident().impl()).isNull())
1982                 continue;
1983             
1984             RegisterID* scope = stackEntry.m_scope;
1985             RELEASE_ASSERT(scope);
1986             return scope;
1987         }
1988
1989         RELEASE_ASSERT_NOT_REACHED();
1990         return nullptr;
1991         
1992     case VarKind::Invalid:
1993         // Indicates non-local resolution.
1994         
1995         m_codeBlock->addPropertyAccessInstruction(instructions().size());
1996         
1997         // resolve_scope dst, id, ResolveType, depth
1998         dst = tempDestination(dst);
1999         emitOpcode(op_resolve_scope);
2000         instructions().append(kill(dst));
2001         instructions().append(scopeRegister()->index());
2002         instructions().append(addConstant(variable.ident()));
2003         instructions().append(resolveType());
2004         instructions().append(localScopeDepth());
2005         instructions().append(0);
2006         return dst;
2007     }
2008     
2009     RELEASE_ASSERT_NOT_REACHED();
2010     return nullptr;
2011 }
2012
2013 RegisterID* BytecodeGenerator::emitGetFromScope(RegisterID* dst, RegisterID* scope, const Variable& variable, ResolveMode resolveMode)
2014 {
2015     switch (variable.offset().kind()) {
2016     case VarKind::Stack:
2017         return emitMove(dst, variable.local());
2018         
2019     case VarKind::DirectArgument: {
2020         UnlinkedValueProfile profile = emitProfiledOpcode(op_get_from_arguments);
2021         instructions().append(kill(dst));
2022         instructions().append(scope->index());
2023         instructions().append(variable.offset().capturedArgumentsOffset().offset());
2024         instructions().append(profile);
2025         return dst;
2026     }
2027         
2028     case VarKind::Scope:
2029     case VarKind::Invalid: {
2030         m_codeBlock->addPropertyAccessInstruction(instructions().size());
2031         
2032         // get_from_scope dst, scope, id, GetPutInfo, Structure, Operand
2033         UnlinkedValueProfile profile = emitProfiledOpcode(op_get_from_scope);
2034         instructions().append(kill(dst));
2035         instructions().append(scope->index());
2036         instructions().append(addConstant(variable.ident()));
2037         instructions().append(GetPutInfo(resolveMode, variable.offset().isScope() ? LocalClosureVar : resolveType(), NotInitialization).operand());
2038         instructions().append(localScopeDepth());
2039         instructions().append(variable.offset().isScope() ? variable.offset().scopeOffset().offset() : 0);
2040         instructions().append(profile);
2041         return dst;
2042     } }
2043     
2044     RELEASE_ASSERT_NOT_REACHED();
2045 }
2046
2047 RegisterID* BytecodeGenerator::emitPutToScope(RegisterID* scope, const Variable& variable, RegisterID* value, ResolveMode resolveMode, InitializationMode initializationMode)
2048 {
2049     switch (variable.offset().kind()) {
2050     case VarKind::Stack:
2051         emitMove(variable.local(), value);
2052         return value;
2053         
2054     case VarKind::DirectArgument:
2055         emitOpcode(op_put_to_arguments);
2056         instructions().append(scope->index());
2057         instructions().append(variable.offset().capturedArgumentsOffset().offset());
2058         instructions().append(value->index());
2059         return value;
2060         
2061     case VarKind::Scope:
2062     case VarKind::Invalid: {
2063         m_codeBlock->addPropertyAccessInstruction(instructions().size());
2064         
2065         // put_to_scope scope, id, value, GetPutInfo, Structure, Operand
2066         emitOpcode(op_put_to_scope);
2067         instructions().append(scope->index());
2068         instructions().append(addConstant(variable.ident()));
2069         instructions().append(value->index());
2070         ScopeOffset offset;
2071         if (variable.offset().isScope()) {
2072             offset = variable.offset().scopeOffset();
2073             instructions().append(GetPutInfo(resolveMode, LocalClosureVar, initializationMode).operand());
2074             instructions().append(variable.symbolTableConstantIndex());
2075         } else {
2076             ASSERT(resolveType() != LocalClosureVar);
2077             instructions().append(GetPutInfo(resolveMode, resolveType(), initializationMode).operand());
2078             instructions().append(localScopeDepth());
2079         }
2080         instructions().append(!!offset ? offset.offset() : 0);
2081         return value;
2082     } }
2083     
2084     RELEASE_ASSERT_NOT_REACHED();
2085 }
2086
2087 RegisterID* BytecodeGenerator::initializeVariable(const Variable& variable, RegisterID* value)
2088 {
2089     RELEASE_ASSERT(variable.offset().kind() != VarKind::Invalid);
2090     RegisterID* scope = emitResolveScope(nullptr, variable);
2091     return emitPutToScope(scope, variable, value, ThrowIfNotFound, NotInitialization);
2092 }
2093
2094 RegisterID* BytecodeGenerator::emitInstanceOf(RegisterID* dst, RegisterID* value, RegisterID* basePrototype)
2095 {
2096     emitOpcode(op_instanceof);
2097     instructions().append(dst->index());
2098     instructions().append(value->index());
2099     instructions().append(basePrototype->index());
2100     return dst;
2101 }
2102
2103 RegisterID* BytecodeGenerator::emitGetById(RegisterID* dst, RegisterID* base, const Identifier& property)
2104 {
2105     m_codeBlock->addPropertyAccessInstruction(instructions().size());
2106
2107     UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_id);
2108     instructions().append(kill(dst));
2109     instructions().append(base->index());
2110     instructions().append(addConstant(property));
2111     instructions().append(0);
2112     instructions().append(0);
2113     instructions().append(0);
2114     instructions().append(0);
2115     instructions().append(profile);
2116     return dst;
2117 }
2118
2119 RegisterID* BytecodeGenerator::emitPutById(RegisterID* base, const Identifier& property, RegisterID* value)
2120 {
2121     unsigned propertyIndex = addConstant(property);
2122
2123     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2124
2125     m_codeBlock->addPropertyAccessInstruction(instructions().size());
2126
2127     emitOpcode(op_put_by_id);
2128     instructions().append(base->index());
2129     instructions().append(propertyIndex);
2130     instructions().append(value->index());
2131     instructions().append(0); // old structure
2132     instructions().append(0); // offset
2133     instructions().append(0); // new structure
2134     instructions().append(0); // structure chain
2135     instructions().append(static_cast<int>(PutByIdNone)); // is not direct
2136
2137     return value;
2138 }
2139
2140 RegisterID* BytecodeGenerator::emitDirectPutById(RegisterID* base, const Identifier& property, RegisterID* value, PropertyNode::PutType putType)
2141 {
2142     ASSERT(!parseIndex(property));
2143     unsigned propertyIndex = addConstant(property);
2144
2145     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2146
2147     m_codeBlock->addPropertyAccessInstruction(instructions().size());
2148     
2149     emitOpcode(op_put_by_id);
2150     instructions().append(base->index());
2151     instructions().append(propertyIndex);
2152     instructions().append(value->index());
2153     instructions().append(0); // old structure
2154     instructions().append(0); // offset
2155     instructions().append(0); // new structure
2156     instructions().append(0); // structure chain (unused if direct)
2157     instructions().append(static_cast<int>((putType == PropertyNode::KnownDirect || property != m_vm->propertyNames->underscoreProto) ? PutByIdIsDirect : PutByIdNone));
2158     return value;
2159 }
2160
2161 void BytecodeGenerator::emitPutGetterById(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* getter)
2162 {
2163     unsigned propertyIndex = addConstant(property);
2164     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2165
2166     emitOpcode(op_put_getter_by_id);
2167     instructions().append(base->index());
2168     instructions().append(propertyIndex);
2169     instructions().append(attributes);
2170     instructions().append(getter->index());
2171 }
2172
2173 void BytecodeGenerator::emitPutSetterById(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* setter)
2174 {
2175     unsigned propertyIndex = addConstant(property);
2176     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2177
2178     emitOpcode(op_put_setter_by_id);
2179     instructions().append(base->index());
2180     instructions().append(propertyIndex);
2181     instructions().append(attributes);
2182     instructions().append(setter->index());
2183 }
2184
2185 void BytecodeGenerator::emitPutGetterSetter(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* getter, RegisterID* setter)
2186 {
2187     unsigned propertyIndex = addConstant(property);
2188
2189     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2190
2191     emitOpcode(op_put_getter_setter_by_id);
2192     instructions().append(base->index());
2193     instructions().append(propertyIndex);
2194     instructions().append(attributes);
2195     instructions().append(getter->index());
2196     instructions().append(setter->index());
2197 }
2198
2199 void BytecodeGenerator::emitPutGetterByVal(RegisterID* base, RegisterID* property, unsigned attributes, RegisterID* getter)
2200 {
2201     emitOpcode(op_put_getter_by_val);
2202     instructions().append(base->index());
2203     instructions().append(property->index());
2204     instructions().append(attributes);
2205     instructions().append(getter->index());
2206 }
2207
2208 void BytecodeGenerator::emitPutSetterByVal(RegisterID* base, RegisterID* property, unsigned attributes, RegisterID* setter)
2209 {
2210     emitOpcode(op_put_setter_by_val);
2211     instructions().append(base->index());
2212     instructions().append(property->index());
2213     instructions().append(attributes);
2214     instructions().append(setter->index());
2215 }
2216
2217 RegisterID* BytecodeGenerator::emitDeleteById(RegisterID* dst, RegisterID* base, const Identifier& property)
2218 {
2219     emitOpcode(op_del_by_id);
2220     instructions().append(dst->index());
2221     instructions().append(base->index());
2222     instructions().append(addConstant(property));
2223     return dst;
2224 }
2225
2226 RegisterID* BytecodeGenerator::emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* property)
2227 {
2228     for (size_t i = m_forInContextStack.size(); i > 0; i--) {
2229         ForInContext* context = m_forInContextStack[i - 1].get();
2230         if (context->local() != property)
2231             continue;
2232
2233         if (!context->isValid())
2234             break;
2235
2236         if (context->type() == ForInContext::IndexedForInContextType) {
2237             property = static_cast<IndexedForInContext*>(context)->index();
2238             break;
2239         }
2240
2241         ASSERT(context->type() == ForInContext::StructureForInContextType);
2242         StructureForInContext* structureContext = static_cast<StructureForInContext*>(context);
2243         UnlinkedValueProfile profile = emitProfiledOpcode(op_get_direct_pname);
2244         instructions().append(kill(dst));
2245         instructions().append(base->index());
2246         instructions().append(property->index());
2247         instructions().append(structureContext->index()->index());
2248         instructions().append(structureContext->enumerator()->index());
2249         instructions().append(profile);
2250         return dst;
2251     }
2252
2253     UnlinkedArrayProfile arrayProfile = newArrayProfile();
2254     UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_val);
2255     instructions().append(kill(dst));
2256     instructions().append(base->index());
2257     instructions().append(property->index());
2258     instructions().append(arrayProfile);
2259     instructions().append(profile);
2260     return dst;
2261 }
2262
2263 RegisterID* BytecodeGenerator::emitPutByVal(RegisterID* base, RegisterID* property, RegisterID* value)
2264 {
2265     UnlinkedArrayProfile arrayProfile = newArrayProfile();
2266     emitOpcode(op_put_by_val);
2267     instructions().append(base->index());
2268     instructions().append(property->index());
2269     instructions().append(value->index());
2270     instructions().append(arrayProfile);
2271
2272     return value;
2273 }
2274
2275 RegisterID* BytecodeGenerator::emitDirectPutByVal(RegisterID* base, RegisterID* property, RegisterID* value)
2276 {
2277     UnlinkedArrayProfile arrayProfile = newArrayProfile();
2278     emitOpcode(op_put_by_val_direct);
2279     instructions().append(base->index());
2280     instructions().append(property->index());
2281     instructions().append(value->index());
2282     instructions().append(arrayProfile);
2283     return value;
2284 }
2285
2286 RegisterID* BytecodeGenerator::emitDeleteByVal(RegisterID* dst, RegisterID* base, RegisterID* property)
2287 {
2288     emitOpcode(op_del_by_val);
2289     instructions().append(dst->index());
2290     instructions().append(base->index());
2291     instructions().append(property->index());
2292     return dst;
2293 }
2294
2295 RegisterID* BytecodeGenerator::emitPutByIndex(RegisterID* base, unsigned index, RegisterID* value)
2296 {
2297     emitOpcode(op_put_by_index);
2298     instructions().append(base->index());
2299     instructions().append(index);
2300     instructions().append(value->index());
2301     return value;
2302 }
2303
2304 RegisterID* BytecodeGenerator::emitAssert(RegisterID* condition, int line)
2305 {
2306     emitOpcode(op_assert);
2307     instructions().append(condition->index());
2308     instructions().append(line);
2309     return condition;
2310 }
2311
2312 RegisterID* BytecodeGenerator::emitCreateThis(RegisterID* dst)
2313 {
2314     size_t begin = instructions().size();
2315     m_staticPropertyAnalyzer.createThis(m_thisRegister.index(), begin + 3);
2316
2317     m_codeBlock->addPropertyAccessInstruction(instructions().size());
2318     emitOpcode(op_create_this); 
2319     instructions().append(m_thisRegister.index()); 
2320     instructions().append(m_thisRegister.index()); 
2321     instructions().append(0);
2322     instructions().append(0);
2323     return dst;
2324 }
2325
2326 void BytecodeGenerator::emitTDZCheck(RegisterID* target)
2327 {
2328     emitOpcode(op_check_tdz);
2329     instructions().append(target->index());
2330 }
2331
2332 bool BytecodeGenerator::needsTDZCheck(const Variable& variable)
2333 {
2334     for (unsigned i = m_TDZStack.size(); i--;) {
2335         VariableEnvironment& identifiers = m_TDZStack[i].first;
2336         if (identifiers.contains(variable.ident().impl()))
2337             return true;
2338     }
2339
2340     return false;
2341 }
2342
2343 void BytecodeGenerator::emitTDZCheckIfNecessary(const Variable& variable, RegisterID* target, RegisterID* scope)
2344 {
2345     if (needsTDZCheck(variable)) {
2346         if (target)
2347             emitTDZCheck(target);
2348         else {
2349             RELEASE_ASSERT(!variable.isLocal() && scope);
2350             RefPtr<RegisterID> result = emitGetFromScope(newTemporary(), scope, variable, DoNotThrowIfNotFound);
2351             emitTDZCheck(result.get());
2352         }
2353     }
2354 }
2355
2356 void BytecodeGenerator::liftTDZCheckIfPossible(const Variable& variable)
2357 {
2358     RefPtr<UniquedStringImpl> identifier(variable.ident().impl());
2359     for (unsigned i = m_TDZStack.size(); i--;) {
2360         VariableEnvironment& environment = m_TDZStack[i].first;
2361         if (environment.contains(identifier)) {
2362             bool isSyntacticallyAbleToOptimizeTDZ = m_TDZStack[i].second;
2363             if (isSyntacticallyAbleToOptimizeTDZ) {
2364                 bool wasRemoved = environment.remove(identifier);
2365                 RELEASE_ASSERT(wasRemoved);
2366             }
2367             break;
2368         }
2369     }
2370 }
2371
2372 void BytecodeGenerator::getVariablesUnderTDZ(VariableEnvironment& result)
2373 {
2374     for (auto& pair : m_TDZStack) {
2375         VariableEnvironment& environment = pair.first;
2376         for (auto entry : environment)
2377             result.add(entry.key.get());
2378     }
2379 }
2380
2381 RegisterID* BytecodeGenerator::emitNewObject(RegisterID* dst)
2382 {
2383     size_t begin = instructions().size();
2384     m_staticPropertyAnalyzer.newObject(dst->index(), begin + 2);
2385
2386     emitOpcode(op_new_object);
2387     instructions().append(dst->index());
2388     instructions().append(0);
2389     instructions().append(newObjectAllocationProfile());
2390     return dst;
2391 }
2392
2393 unsigned BytecodeGenerator::addConstantBuffer(unsigned length)
2394 {
2395     return m_codeBlock->addConstantBuffer(length);
2396 }
2397
2398 JSString* BytecodeGenerator::addStringConstant(const Identifier& identifier)
2399 {
2400     JSString*& stringInMap = m_stringMap.add(identifier.impl(), nullptr).iterator->value;
2401     if (!stringInMap) {
2402         stringInMap = jsString(vm(), identifier.string());
2403         addConstantValue(stringInMap);
2404     }
2405     return stringInMap;
2406 }
2407
2408 JSTemplateRegistryKey* BytecodeGenerator::addTemplateRegistryKeyConstant(const TemplateRegistryKey& templateRegistryKey)
2409 {
2410     JSTemplateRegistryKey*& templateRegistryKeyInMap = m_templateRegistryKeyMap.add(templateRegistryKey, nullptr).iterator->value;
2411     if (!templateRegistryKeyInMap) {
2412         templateRegistryKeyInMap = JSTemplateRegistryKey::create(*vm(), templateRegistryKey);
2413         addConstantValue(templateRegistryKeyInMap);
2414     }
2415     return templateRegistryKeyInMap;
2416 }
2417
2418 RegisterID* BytecodeGenerator::emitNewArray(RegisterID* dst, ElementNode* elements, unsigned length)
2419 {
2420 #if !ASSERT_DISABLED
2421     unsigned checkLength = 0;
2422 #endif
2423     bool hadVariableExpression = false;
2424     if (length) {
2425         for (ElementNode* n = elements; n; n = n->next()) {
2426             if (!n->value()->isConstant()) {
2427                 hadVariableExpression = true;
2428                 break;
2429             }
2430             if (n->elision())
2431                 break;
2432 #if !ASSERT_DISABLED
2433             checkLength++;
2434 #endif
2435         }
2436         if (!hadVariableExpression) {
2437             ASSERT(length == checkLength);
2438             unsigned constantBufferIndex = addConstantBuffer(length);
2439             JSValue* constantBuffer = m_codeBlock->constantBuffer(constantBufferIndex).data();
2440             unsigned index = 0;
2441             for (ElementNode* n = elements; index < length; n = n->next()) {
2442                 ASSERT(n->value()->isConstant());
2443                 constantBuffer[index++] = static_cast<ConstantNode*>(n->value())->jsValue(*this);
2444             }
2445             emitOpcode(op_new_array_buffer);
2446             instructions().append(dst->index());
2447             instructions().append(constantBufferIndex);
2448             instructions().append(length);
2449             instructions().append(newArrayAllocationProfile());
2450             return dst;
2451         }
2452     }
2453
2454     Vector<RefPtr<RegisterID>, 16, UnsafeVectorOverflow> argv;
2455     for (ElementNode* n = elements; n; n = n->next()) {
2456         if (!length)
2457             break;
2458         length--;
2459         ASSERT(!n->value()->isSpreadExpression());
2460         argv.append(newTemporary());
2461         // op_new_array requires the initial values to be a sequential range of registers
2462         ASSERT(argv.size() == 1 || argv[argv.size() - 1]->index() == argv[argv.size() - 2]->index() - 1);
2463         emitNode(argv.last().get(), n->value());
2464     }
2465     ASSERT(!length);
2466     emitOpcode(op_new_array);
2467     instructions().append(dst->index());
2468     instructions().append(argv.size() ? argv[0]->index() : 0); // argv
2469     instructions().append(argv.size()); // argc
2470     instructions().append(newArrayAllocationProfile());
2471     return dst;
2472 }
2473
2474 RegisterID* BytecodeGenerator::emitNewFunction(RegisterID* dst, FunctionMetadataNode* function)
2475 {
2476     return emitNewFunctionInternal(dst, m_codeBlock->addFunctionDecl(makeFunction(function)));
2477 }
2478
2479 RegisterID* BytecodeGenerator::emitNewFunctionInternal(RegisterID* dst, unsigned index)
2480 {
2481     emitOpcode(op_new_func);
2482     instructions().append(dst->index());
2483     instructions().append(scopeRegister()->index());
2484     instructions().append(index);
2485     return dst;
2486 }
2487
2488 RegisterID* BytecodeGenerator::emitNewRegExp(RegisterID* dst, RegExp* regExp)
2489 {
2490     emitOpcode(op_new_regexp);
2491     instructions().append(dst->index());
2492     instructions().append(addRegExp(regExp));
2493     return dst;
2494 }
2495
2496 void BytecodeGenerator::emitNewFunctionCommon(RegisterID* dst, BaseFuncExprNode* func, OpcodeID opcodeID)
2497 {
2498
2499     ASSERT(opcodeID == op_new_func_exp || opcodeID == op_new_arrow_func_exp);
2500     
2501     FunctionMetadataNode* function = func->metadata();
2502     unsigned index = m_codeBlock->addFunctionExpr(makeFunction(function));
2503     
2504     emitOpcode(opcodeID);
2505     instructions().append(dst->index());
2506     instructions().append(scopeRegister()->index());
2507     instructions().append(index);
2508     
2509     if (opcodeID == op_new_arrow_func_exp)
2510         instructions().append(thisRegister()->index());
2511 }
2512
2513 RegisterID* BytecodeGenerator::emitNewFunctionExpression(RegisterID* dst, FuncExprNode* func)
2514 {
2515     emitNewFunctionCommon(dst, func, op_new_func_exp);
2516     return dst;
2517 }
2518
2519 RegisterID* BytecodeGenerator::emitNewArrowFunctionExpression(RegisterID* dst, ArrowFuncExprNode* func)
2520 {
2521     bool isClassConstructor = m_codeBlock->isConstructor() && constructorKind() != ConstructorKind::None;
2522     if (isClassConstructor)
2523         emitTDZCheck(thisRegister());
2524     
2525     emitNewFunctionCommon(dst, func, op_new_arrow_func_exp);
2526     return dst;
2527 }
2528
2529 RegisterID* BytecodeGenerator::emitNewDefaultConstructor(RegisterID* dst, ConstructorKind constructorKind, const Identifier& name)
2530 {
2531     UnlinkedFunctionExecutable* executable = m_vm->builtinExecutables()->createDefaultConstructor(constructorKind, name);
2532     executable->setInvalidTypeProfilingOffsets();
2533
2534     unsigned index = m_codeBlock->addFunctionExpr(executable);
2535
2536     emitOpcode(op_new_func_exp);
2537     instructions().append(dst->index());
2538     instructions().append(scopeRegister()->index());
2539     instructions().append(index);
2540     return dst;
2541 }
2542
2543 RegisterID* BytecodeGenerator::emitCall(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd)
2544 {
2545     return emitCall(op_call, dst, func, expectedFunction, callArguments, divot, divotStart, divotEnd);
2546 }
2547
2548 RegisterID* BytecodeGenerator::emitCallInTailPosition(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd)
2549 {
2550     return emitCall(m_inTailPosition ? op_tail_call : op_call, dst, func, expectedFunction, callArguments, divot, divotStart, divotEnd);
2551 }
2552
2553 RegisterID* BytecodeGenerator::emitCallEval(RegisterID* dst, RegisterID* func, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd)
2554 {
2555     return emitCall(op_call_eval, dst, func, NoExpectedFunction, callArguments, divot, divotStart, divotEnd);
2556 }
2557
2558 ExpectedFunction BytecodeGenerator::expectedFunctionForIdentifier(const Identifier& identifier)
2559 {
2560     if (identifier == m_vm->propertyNames->Object || identifier == m_vm->propertyNames->ObjectPrivateName)
2561         return ExpectObjectConstructor;
2562     if (identifier == m_vm->propertyNames->Array || identifier == m_vm->propertyNames->ArrayPrivateName)
2563         return ExpectArrayConstructor;
2564     return NoExpectedFunction;
2565 }
2566
2567 ExpectedFunction BytecodeGenerator::emitExpectedFunctionSnippet(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, Label* done)
2568 {
2569     RefPtr<Label> realCall = newLabel();
2570     switch (expectedFunction) {
2571     case ExpectObjectConstructor: {
2572         // If the number of arguments is non-zero, then we can't do anything interesting.
2573         if (callArguments.argumentCountIncludingThis() >= 2)
2574             return NoExpectedFunction;
2575         
2576         size_t begin = instructions().size();
2577         emitOpcode(op_jneq_ptr);
2578         instructions().append(func->index());
2579         instructions().append(Special::ObjectConstructor);
2580         instructions().append(realCall->bind(begin, instructions().size()));
2581         
2582         if (dst != ignoredResult())
2583             emitNewObject(dst);
2584         break;
2585     }
2586         
2587     case ExpectArrayConstructor: {
2588         // If you're doing anything other than "new Array()" or "new Array(foo)" then we
2589         // don't do inline it, for now. The only reason is that call arguments are in
2590         // the opposite order of what op_new_array expects, so we'd either need to change
2591         // how op_new_array works or we'd need an op_new_array_reverse. Neither of these
2592         // things sounds like it's worth it.
2593         if (callArguments.argumentCountIncludingThis() > 2)
2594             return NoExpectedFunction;
2595         
2596         size_t begin = instructions().size();
2597         emitOpcode(op_jneq_ptr);
2598         instructions().append(func->index());
2599         instructions().append(Special::ArrayConstructor);
2600         instructions().append(realCall->bind(begin, instructions().size()));
2601         
2602         if (dst != ignoredResult()) {
2603             if (callArguments.argumentCountIncludingThis() == 2) {
2604                 emitOpcode(op_new_array_with_size);
2605                 instructions().append(dst->index());
2606                 instructions().append(callArguments.argumentRegister(0)->index());
2607                 instructions().append(newArrayAllocationProfile());
2608             } else {
2609                 ASSERT(callArguments.argumentCountIncludingThis() == 1);
2610                 emitOpcode(op_new_array);
2611                 instructions().append(dst->index());
2612                 instructions().append(0);
2613                 instructions().append(0);
2614                 instructions().append(newArrayAllocationProfile());
2615             }
2616         }
2617         break;
2618     }
2619         
2620     default:
2621         ASSERT(expectedFunction == NoExpectedFunction);
2622         return NoExpectedFunction;
2623     }
2624     
2625     size_t begin = instructions().size();
2626     emitOpcode(op_jmp);
2627     instructions().append(done->bind(begin, instructions().size()));
2628     emitLabel(realCall.get());
2629     
2630     return expectedFunction;
2631 }
2632
2633 RegisterID* BytecodeGenerator::emitCall(OpcodeID opcodeID, RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd)
2634 {
2635     ASSERT(opcodeID == op_call || opcodeID == op_call_eval || opcodeID == op_tail_call);
2636     ASSERT(func->refCount());
2637
2638     if (m_shouldEmitProfileHooks)
2639         emitMove(callArguments.profileHookRegister(), func);
2640
2641     // Generate code for arguments.
2642     unsigned argument = 0;
2643     if (callArguments.argumentsNode()) {
2644         ArgumentListNode* n = callArguments.argumentsNode()->m_listNode;
2645         if (n && n->m_expr->isSpreadExpression()) {
2646             RELEASE_ASSERT(!n->m_next);
2647             auto expression = static_cast<SpreadExpressionNode*>(n->m_expr)->expression();
2648             RefPtr<RegisterID> argumentRegister;
2649             argumentRegister = expression->emitBytecode(*this, callArguments.argumentRegister(0));
2650             RefPtr<RegisterID> thisRegister = emitMove(newTemporary(), callArguments.thisRegister());
2651             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);
2652         }
2653         for (; n; n = n->m_next)
2654             emitNode(callArguments.argumentRegister(argument++), n);
2655     }
2656     
2657     // Reserve space for call frame.
2658     Vector<RefPtr<RegisterID>, JSStack::CallFrameHeaderSize, UnsafeVectorOverflow> callFrame;
2659     for (int i = 0; i < JSStack::CallFrameHeaderSize; ++i)
2660         callFrame.append(newTemporary());
2661
2662     if (m_shouldEmitProfileHooks) {
2663         emitOpcode(op_profile_will_call);
2664         instructions().append(callArguments.profileHookRegister()->index());
2665     }
2666
2667     emitExpressionInfo(divot, divotStart, divotEnd);
2668
2669     RefPtr<Label> done = newLabel();
2670     expectedFunction = emitExpectedFunctionSnippet(dst, func, expectedFunction, callArguments, done.get());
2671     
2672     // Emit call.
2673     UnlinkedArrayProfile arrayProfile = newArrayProfile();
2674     UnlinkedValueProfile profile = emitProfiledOpcode(opcodeID);
2675     ASSERT(dst);
2676     ASSERT(dst != ignoredResult());
2677     instructions().append(dst->index());
2678     instructions().append(func->index());
2679     instructions().append(callArguments.argumentCountIncludingThis());
2680     instructions().append(callArguments.stackOffset());
2681     instructions().append(m_codeBlock->addLLIntCallLinkInfo());
2682     instructions().append(0);
2683     instructions().append(arrayProfile);
2684     instructions().append(profile);
2685     
2686     if (expectedFunction != NoExpectedFunction)
2687         emitLabel(done.get());
2688
2689     if (m_shouldEmitProfileHooks) {
2690         emitOpcode(op_profile_did_call);
2691         instructions().append(callArguments.profileHookRegister()->index());
2692     }
2693
2694     return dst;
2695 }
2696
2697 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)
2698 {
2699     return emitCallVarargs(op_call_varargs, dst, func, thisRegister, arguments, firstFreeRegister, firstVarArgOffset, profileHookRegister, divot, divotStart, divotEnd);
2700 }
2701
2702 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)
2703 {
2704     return emitCallVarargs(m_inTailPosition ? op_tail_call_varargs : op_call_varargs, dst, func, thisRegister, arguments, firstFreeRegister, firstVarArgOffset, profileHookRegister, divot, divotStart, divotEnd);
2705 }
2706
2707 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)
2708 {
2709     return emitCallVarargs(op_construct_varargs, dst, func, thisRegister, arguments, firstFreeRegister, firstVarArgOffset, profileHookRegister, divot, divotStart, divotEnd);
2710 }
2711     
2712 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)
2713 {
2714     if (m_shouldEmitProfileHooks) {
2715         emitMove(profileHookRegister, func);
2716         emitOpcode(op_profile_will_call);
2717         instructions().append(profileHookRegister->index());
2718     }
2719     
2720     emitExpressionInfo(divot, divotStart, divotEnd);
2721
2722     // Emit call.
2723     UnlinkedArrayProfile arrayProfile = newArrayProfile();
2724     UnlinkedValueProfile profile = emitProfiledOpcode(opcode);
2725     ASSERT(dst != ignoredResult());
2726     instructions().append(dst->index());
2727     instructions().append(func->index());
2728     instructions().append(thisRegister ? thisRegister->index() : 0);
2729     instructions().append(arguments->index());
2730     instructions().append(firstFreeRegister->index());
2731     instructions().append(firstVarArgOffset);
2732     instructions().append(arrayProfile);
2733     instructions().append(profile);
2734     if (m_shouldEmitProfileHooks) {
2735         emitOpcode(op_profile_did_call);
2736         instructions().append(profileHookRegister->index());
2737     }
2738     return dst;
2739 }
2740
2741 void BytecodeGenerator::emitCallDefineProperty(RegisterID* newObj, RegisterID* propertyNameRegister,
2742     RegisterID* valueRegister, RegisterID* getterRegister, RegisterID* setterRegister, unsigned options, const JSTextPosition& position)
2743 {
2744     RefPtr<RegisterID> descriptorRegister = emitNewObject(newTemporary());
2745
2746     RefPtr<RegisterID> trueRegister = emitLoad(newTemporary(), true);
2747     if (options & PropertyConfigurable)
2748         emitDirectPutById(descriptorRegister.get(), propertyNames().configurable, trueRegister.get(), PropertyNode::Unknown);
2749     if (options & PropertyWritable)
2750         emitDirectPutById(descriptorRegister.get(), propertyNames().writable, trueRegister.get(), PropertyNode::Unknown);
2751     else if (valueRegister) {
2752         RefPtr<RegisterID> falseRegister = emitLoad(newTemporary(), false);
2753         emitDirectPutById(descriptorRegister.get(), propertyNames().writable, falseRegister.get(), PropertyNode::Unknown);
2754     }
2755     if (options & PropertyEnumerable)
2756         emitDirectPutById(descriptorRegister.get(), propertyNames().enumerable, trueRegister.get(), PropertyNode::Unknown);
2757
2758     if (valueRegister)
2759         emitDirectPutById(descriptorRegister.get(), propertyNames().value, valueRegister, PropertyNode::Unknown);
2760     if (getterRegister)
2761         emitDirectPutById(descriptorRegister.get(), propertyNames().get, getterRegister, PropertyNode::Unknown);
2762     if (setterRegister)
2763         emitDirectPutById(descriptorRegister.get(), propertyNames().set, setterRegister, PropertyNode::Unknown);
2764
2765     RefPtr<RegisterID> definePropertyRegister = emitMoveLinkTimeConstant(newTemporary(), LinkTimeConstant::DefinePropertyFunction);
2766
2767     CallArguments callArguments(*this, nullptr, 3);
2768     emitLoad(callArguments.thisRegister(), jsUndefined());
2769     emitMove(callArguments.argumentRegister(0), newObj);
2770     emitMove(callArguments.argumentRegister(1), propertyNameRegister);
2771     emitMove(callArguments.argumentRegister(2), descriptorRegister.get());
2772
2773     emitCall(newTemporary(), definePropertyRegister.get(), NoExpectedFunction, callArguments, position, position, position);
2774 }
2775
2776 RegisterID* BytecodeGenerator::emitReturn(RegisterID* src)
2777 {
2778     if (isConstructor()) {
2779         bool derived = constructorKind() == ConstructorKind::Derived;
2780         if (derived && src->index() == m_thisRegister.index())
2781             emitTDZCheck(src);
2782
2783         RefPtr<Label> isObjectLabel = newLabel();
2784         emitJumpIfTrue(emitIsObject(newTemporary(), src), isObjectLabel.get());
2785
2786         if (derived) {
2787             RefPtr<Label> isUndefinedLabel = newLabel();
2788             emitJumpIfTrue(emitIsUndefined(newTemporary(), src), isUndefinedLabel.get());
2789             emitThrowTypeError("Cannot return a non-object type in the constructor of a derived class.");
2790             emitLabel(isUndefinedLabel.get());
2791             if (constructorKind() == ConstructorKind::Derived)
2792                 emitTDZCheck(&m_thisRegister);
2793         }
2794
2795         emitUnaryNoDstOp(op_ret, &m_thisRegister);
2796
2797         emitLabel(isObjectLabel.get());
2798     }
2799
2800     return emitUnaryNoDstOp(op_ret, src);
2801 }
2802
2803 RegisterID* BytecodeGenerator::emitUnaryNoDstOp(OpcodeID opcodeID, RegisterID* src)
2804 {
2805     emitOpcode(opcodeID);
2806     instructions().append(src->index());
2807     return src;
2808 }
2809
2810 RegisterID* BytecodeGenerator::emitConstruct(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd)
2811 {
2812     ASSERT(func->refCount());
2813
2814     if (m_shouldEmitProfileHooks)
2815         emitMove(callArguments.profileHookRegister(), func);
2816
2817     // Generate code for arguments.
2818     unsigned argument = 0;
2819     if (ArgumentsNode* argumentsNode = callArguments.argumentsNode()) {
2820         
2821         ArgumentListNode* n = callArguments.argumentsNode()->m_listNode;
2822         if (n && n->m_expr->isSpreadExpression()) {
2823             RELEASE_ASSERT(!n->m_next);
2824             auto expression = static_cast<SpreadExpressionNode*>(n->m_expr)->expression();
2825             RefPtr<RegisterID> argumentRegister;
2826             argumentRegister = expression->emitBytecode(*this, callArguments.argumentRegister(0));
2827             return emitConstructVarargs(dst, func, callArguments.thisRegister(), argumentRegister.get(), newTemporary(), 0, callArguments.profileHookRegister(), divot, divotStart, divotEnd);
2828         }
2829         
2830         for (ArgumentListNode* n = argumentsNode->m_listNode; n; n = n->m_next)
2831             emitNode(callArguments.argumentRegister(argument++), n);
2832     }
2833
2834     if (m_shouldEmitProfileHooks) {
2835         emitOpcode(op_profile_will_call);
2836         instructions().append(callArguments.profileHookRegister()->index());
2837     }
2838
2839     // Reserve space for call frame.
2840     Vector<RefPtr<RegisterID>, JSStack::CallFrameHeaderSize, UnsafeVectorOverflow> callFrame;
2841     for (int i = 0; i < JSStack::CallFrameHeaderSize; ++i)
2842         callFrame.append(newTemporary());
2843
2844     emitExpressionInfo(divot, divotStart, divotEnd);
2845     
2846     RefPtr<Label> done = newLabel();
2847     expectedFunction = emitExpectedFunctionSnippet(dst, func, expectedFunction, callArguments, done.get());
2848
2849     UnlinkedValueProfile profile = emitProfiledOpcode(op_construct);
2850     ASSERT(dst != ignoredResult());
2851     instructions().append(dst->index());
2852     instructions().append(func->index());
2853     instructions().append(callArguments.argumentCountIncludingThis());
2854     instructions().append(callArguments.stackOffset());
2855     instructions().append(m_codeBlock->addLLIntCallLinkInfo());
2856     instructions().append(0);
2857     instructions().append(0);
2858     instructions().append(profile);
2859
2860     if (expectedFunction != NoExpectedFunction)
2861         emitLabel(done.get());
2862
2863     if (m_shouldEmitProfileHooks) {
2864         emitOpcode(op_profile_did_call);
2865         instructions().append(callArguments.profileHookRegister()->index());
2866     }
2867
2868     return dst;
2869 }
2870
2871 RegisterID* BytecodeGenerator::emitStrcat(RegisterID* dst, RegisterID* src, int count)
2872 {
2873     emitOpcode(op_strcat);
2874     instructions().append(dst->index());
2875     instructions().append(src->index());
2876     instructions().append(count);
2877
2878     return dst;
2879 }
2880
2881 void BytecodeGenerator::emitToPrimitive(RegisterID* dst, RegisterID* src)
2882 {
2883     emitOpcode(op_to_primitive);
2884     instructions().append(dst->index());
2885     instructions().append(src->index());
2886 }
2887
2888 void BytecodeGenerator::emitGetScope()
2889 {
2890     emitOpcode(op_get_scope);
2891     instructions().append(scopeRegister()->index());
2892 }
2893
2894 RegisterID* BytecodeGenerator::emitPushWithScope(RegisterID* objectScope)
2895 {
2896     pushScopedControlFlowContext();
2897     RegisterID* newScope = newBlockScopeVariable();
2898     newScope->ref();
2899
2900     emitOpcode(op_push_with_scope);
2901     instructions().append(newScope->index());
2902     instructions().append(objectScope->index());
2903     instructions().append(scopeRegister()->index());
2904
2905     emitMove(scopeRegister(), newScope);
2906     m_symbolTableStack.append(SymbolTableStackEntry{ Strong<SymbolTable>(), newScope, true, 0 });
2907
2908     return newScope;
2909 }
2910
2911 RegisterID* BytecodeGenerator::emitGetParentScope(RegisterID* dst, RegisterID* scope)
2912 {
2913     emitOpcode(op_get_parent_scope);
2914     instructions().append(dst->index());
2915     instructions().append(scope->index());
2916     return dst;
2917 }
2918
2919 void BytecodeGenerator::emitPopScope(RegisterID* dst, RegisterID* scope)
2920 {
2921     RefPtr<RegisterID> parentScope = emitGetParentScope(newTemporary(), scope);
2922     emitMove(dst, parentScope.get());
2923 }
2924
2925 void BytecodeGenerator::emitPopWithScope()
2926 {
2927     emitPopScope(scopeRegister(), scopeRegister());
2928     popScopedControlFlowContext();
2929     SymbolTableStackEntry stackEntry = m_symbolTableStack.takeLast();
2930     stackEntry.m_scope->deref();
2931     RELEASE_ASSERT(stackEntry.m_isWithScope);
2932 }
2933
2934 void BytecodeGenerator::emitDebugHook(DebugHookID debugHookID, unsigned line, unsigned charOffset, unsigned lineStart)
2935 {
2936 #if ENABLE(DEBUG_WITH_BREAKPOINT)
2937     if (debugHookID != DidReachBreakpoint)
2938         return;
2939 #else
2940     if (!m_shouldEmitDebugHooks)
2941         return;
2942 #endif
2943     JSTextPosition divot(line, charOffset, lineStart);
2944     emitExpressionInfo(divot, divot, divot);
2945     emitOpcode(op_debug);
2946     instructions().append(debugHookID);
2947     instructions().append(false);
2948 }
2949
2950 void BytecodeGenerator::pushFinallyContext(StatementNode* finallyBlock)
2951 {
2952     // Reclaim free label scopes.
2953     while (m_labelScopes.size() && !m_labelScopes.last().refCount())
2954         m_labelScopes.removeLast();
2955
2956     ControlFlowContext scope;
2957     scope.isFinallyBlock = true;
2958     FinallyContext context = {
2959         finallyBlock,
2960         nullptr,
2961         nullptr,
2962         static_cast<unsigned>(m_scopeContextStack.size()),
2963         static_cast<unsigned>(m_switchContextStack.size()),
2964         static_cast<unsigned>(m_forInContextStack.size()),
2965         static_cast<unsigned>(m_tryContextStack.size()),
2966         static_cast<unsigned>(m_labelScopes.size()),
2967         static_cast<unsigned>(m_symbolTableStack.size()),
2968         m_finallyDepth,
2969         m_localScopeDepth
2970     };
2971     scope.finallyContext = context;
2972     m_scopeContextStack.append(scope);
2973     m_finallyDepth++;
2974 }
2975
2976 void BytecodeGenerator::pushIteratorCloseContext(RegisterID* iterator, ThrowableExpressionData* node)
2977 {
2978     // Reclaim free label scopes.
2979     while (m_labelScopes.size() && !m_labelScopes.last().refCount())
2980         m_labelScopes.removeLast();
2981
2982     ControlFlowContext scope;
2983     scope.isFinallyBlock = true;
2984     FinallyContext context = {
2985         nullptr,
2986         iterator,
2987         node,
2988         static_cast<unsigned>(m_scopeContextStack.size()),
2989         static_cast<unsigned>(m_switchContextStack.size()),
2990         static_cast<unsigned>(m_forInContextStack.size()),
2991         static_cast<unsigned>(m_tryContextStack.size()),
2992         static_cast<unsigned>(m_labelScopes.size()),
2993         static_cast<unsigned>(m_symbolTableStack.size()),
2994         m_finallyDepth,
2995         m_localScopeDepth
2996     };
2997     scope.finallyContext = context;
2998     m_scopeContextStack.append(scope);
2999     m_finallyDepth++;
3000 }
3001
3002 void BytecodeGenerator::popFinallyContext()
3003 {
3004     ASSERT(m_scopeContextStack.size());
3005     ASSERT(m_scopeContextStack.last().isFinallyBlock);
3006     ASSERT(m_scopeContextStack.last().finallyContext.finallyBlock);
3007     ASSERT(!m_scopeContextStack.last().finallyContext.iterator);
3008     ASSERT(!m_scopeContextStack.last().finallyContext.enumerationNode);
3009     ASSERT(m_finallyDepth > 0);
3010     m_scopeContextStack.removeLast();
3011     m_finallyDepth--;
3012 }
3013
3014 void BytecodeGenerator::popIteratorCloseContext()
3015 {
3016     ASSERT(m_scopeContextStack.size());
3017     ASSERT(m_scopeContextStack.last().isFinallyBlock);
3018     ASSERT(!m_scopeContextStack.last().finallyContext.finallyBlock);
3019     ASSERT(m_scopeContextStack.last().finallyContext.iterator);
3020     ASSERT(m_scopeContextStack.last().finallyContext.enumerationNode);
3021     ASSERT(m_finallyDepth > 0);
3022     m_scopeContextStack.removeLast();
3023     m_finallyDepth--;
3024 }
3025
3026 LabelScopePtr BytecodeGenerator::breakTarget(const Identifier& name)
3027 {
3028     // Reclaim free label scopes.
3029     //
3030     // The condition was previously coded as 'm_labelScopes.size() && !m_labelScopes.last().refCount()',
3031     // however sometimes this appears to lead to GCC going a little haywire and entering the loop with
3032     // size 0, leading to segfaulty badness.  We are yet to identify a valid cause within our code to
3033     // cause the GCC codegen to misbehave in this fashion, and as such the following refactoring of the
3034     // loop condition is a workaround.
3035     while (m_labelScopes.size()) {
3036         if  (m_labelScopes.last().refCount())
3037             break;
3038         m_labelScopes.removeLast();
3039     }
3040
3041     if (!m_labelScopes.size())
3042         return LabelScopePtr::null();
3043
3044     // We special-case the following, which is a syntax error in Firefox:
3045     // label:
3046     //     break;
3047     if (name.isEmpty()) {
3048         for (int i = m_labelScopes.size() - 1; i >= 0; --i) {
3049             LabelScope* scope = &m_labelScopes[i];
3050             if (scope->type() != LabelScope::NamedLabel) {
3051                 ASSERT(scope->breakTarget());
3052                 return LabelScopePtr(m_labelScopes, i);
3053             }
3054         }
3055         return LabelScopePtr::null();
3056     }
3057
3058     for (int i = m_labelScopes.size() - 1; i >= 0; --i) {
3059         LabelScope* scope = &m_labelScopes[i];
3060         if (scope->name() && *scope->name() == name) {
3061             ASSERT(scope->breakTarget());
3062             return LabelScopePtr(m_labelScopes, i);
3063         }
3064     }
3065     return LabelScopePtr::null();
3066 }
3067
3068 LabelScopePtr BytecodeGenerator::continueTarget(const Identifier& name)
3069 {
3070     // Reclaim free label scopes.
3071     while (m_labelScopes.size() && !m_labelScopes.last().refCount())
3072         m_labelScopes.removeLast();
3073
3074     if (!m_labelScopes.size())
3075         return LabelScopePtr::null();
3076
3077     if (name.isEmpty()) {
3078         for (int i = m_labelScopes.size() - 1; i >= 0; --i) {
3079             LabelScope* scope = &m_labelScopes[i];
3080             if (scope->type() == LabelScope::Loop) {
3081                 ASSERT(scope->continueTarget());
3082                 return LabelScopePtr(m_labelScopes, i);
3083             }
3084         }
3085         return LabelScopePtr::null();
3086     }
3087
3088     // Continue to the loop nested nearest to the label scope that matches
3089     // 'name'.
3090     LabelScopePtr result = LabelScopePtr::null();
3091     for (int i = m_labelScopes.size() - 1; i >= 0; --i) {
3092         LabelScope* scope = &m_labelScopes[i];
3093         if (scope->type() == LabelScope::Loop) {
3094             ASSERT(scope->continueTarget());
3095             result = LabelScopePtr(m_labelScopes, i);
3096         }
3097         if (scope->name() && *scope->name() == name)
3098             return result; // may be null.
3099     }
3100     return LabelScopePtr::null();
3101 }
3102
3103 void BytecodeGenerator::allocateCalleeSaveSpace()
3104 {
3105     size_t virtualRegisterCountForCalleeSaves = CodeBlock::llintBaselineCalleeSaveSpaceAsVirtualRegisters();
3106
3107     for (size_t i = 0; i < virtualRegisterCountForCalleeSaves; i++) {
3108         RegisterID* localRegister = addVar();
3109         localRegister->ref();
3110         m_localRegistersForCalleeSaveRegisters.append(localRegister);
3111     }
3112 }
3113
3114 void BytecodeGenerator::allocateAndEmitScope()
3115 {
3116     m_scopeRegister = addVar();
3117     m_scopeRegister->ref();
3118     m_codeBlock->setScopeRegister(scopeRegister()->virtualRegister());
3119     emitGetScope();
3120     m_topMostScope = addVar();
3121     emitMove(m_topMostScope, scopeRegister());
3122 }
3123
3124 RegisterID* BytecodeGenerator::emitLoadArrowFunctionThis(RegisterID* arrowFunctionThis)
3125 {
3126     emitOpcode(op_load_arrowfunction_this);
3127     instructions().append(arrowFunctionThis->index());
3128     return arrowFunctionThis;
3129 }
3130     
3131 void BytecodeGenerator::emitComplexPopScopes(RegisterID* scope, ControlFlowContext* topScope, ControlFlowContext* bottomScope)
3132 {
3133     while (topScope > bottomScope) {
3134         // First we count the number of dynamic scopes we need to remove to get
3135         // to a finally block.
3136         int nNormalScopes = 0;
3137         while (topScope > bottomScope) {
3138             if (topScope->isFinallyBlock)
3139                 break;
3140             ++nNormalScopes;
3141             --topScope;
3142         }
3143
3144         if (nNormalScopes) {
3145             // We need to remove a number of dynamic scopes to get to the next
3146             // finally block
3147             RefPtr<RegisterID> parentScope = newTemporary();
3148             while (nNormalScopes--) {
3149                 parentScope = emitGetParentScope(parentScope.get(), scope);
3150                 emitMove(scope, parentScope.get());
3151             }
3152
3153             // If topScope == bottomScope then there isn't a finally block left to emit.
3154             if (topScope == bottomScope)
3155                 return;
3156         }
3157         
3158         Vector<ControlFlowContext> savedScopeContextStack;
3159         Vector<SwitchInfo> savedSwitchContextStack;
3160         Vector<std::unique_ptr<ForInContext>> savedForInContextStack;
3161         Vector<TryContext> poppedTryContexts;
3162         Vector<SymbolTableStackEntry> savedSymbolTableStack;
3163         LabelScopeStore savedLabelScopes;
3164         while (topScope > bottomScope && topScope->isFinallyBlock) {
3165             RefPtr<Label> beforeFinally = emitLabel(newLabel().get());
3166             
3167             // Save the current state of the world while instating the state of the world
3168             // for the finally block.
3169             FinallyContext finallyContext = topScope->finallyContext;
3170             bool flipScopes = finallyContext.scopeContextStackSize != m_scopeContextStack.size();
3171             bool flipSwitches = finallyContext.switchContextStackSize != m_switchContextStack.size();
3172             bool flipForIns = finallyContext.forInContextStackSize != m_forInContextStack.size();
3173             bool flipTries = finallyContext.tryContextStackSize != m_tryContextStack.size();
3174             bool flipLabelScopes = finallyContext.labelScopesSize != m_labelScopes.size();
3175             bool flipSymbolTableStack = finallyContext.symbolTableStackSize != m_symbolTableStack.size();
3176             int topScopeIndex = -1;
3177             int bottomScopeIndex = -1;
3178             if (flipScopes) {
3179                 topScopeIndex = topScope - m_scopeContextStack.begin();
3180                 bottomScopeIndex = bottomScope - m_scopeContextStack.begin();
3181                 savedScopeContextStack = m_scopeContextStack;
3182                 m_scopeContextStack.shrink(finallyContext.scopeContextStackSize);
3183             }
3184             if (flipSwitches) {
3185                 savedSwitchContextStack = m_switchContextStack;
3186                 m_switchContextStack.shrink(finallyContext.switchContextStackSize);
3187             }
3188             if (flipForIns) {
3189                 savedForInContextStack.swap(m_forInContextStack);
3190                 m_forInContextStack.shrink(finallyContext.forInContextStackSize);
3191             }
3192             if (flipTries) {
3193                 while (m_tryContextStack.size() != finallyContext.tryContextStackSize) {
3194                     ASSERT(m_tryContextStack.size() > finallyContext.tryContextStackSize);
3195                     TryContext context = m_tryContextStack.last();
3196                     m_tryContextStack.removeLast();
3197                     TryRange range;
3198                     range.start = context.start;
3199                     range.end = beforeFinally;
3200                     range.tryData = context.tryData;
3201                     m_tryRanges.append(range);
3202                     poppedTryContexts.append(context);
3203                 }
3204             }
3205             if (flipLabelScopes) {
3206                 savedLabelScopes = m_labelScopes;
3207                 while (m_labelScopes.size() > finallyContext.labelScopesSize)
3208                     m_labelScopes.removeLast();
3209             }
3210             if (flipSymbolTableStack) {
3211                 savedSymbolTableStack = m_symbolTableStack;
3212                 m_symbolTableStack.shrink(finallyContext.symbolTableStackSize);
3213             }
3214             int savedFinallyDepth = m_finallyDepth;
3215             m_finallyDepth = finallyContext.finallyDepth;
3216             int savedDynamicScopeDepth = m_localScopeDepth;
3217             m_localScopeDepth = finallyContext.dynamicScopeDepth;
3218             
3219             if (finallyContext.finallyBlock) {
3220                 // Emit the finally block.
3221                 emitNode(finallyContext.finallyBlock);
3222             } else {
3223                 // Emit the IteratorClose block.
3224                 ASSERT(finallyContext.iterator);
3225                 emitIteratorClose(finallyContext.iterator, finallyContext.enumerationNode);
3226             }
3227
3228             RefPtr<Label> afterFinally = emitLabel(newLabel().get());
3229             
3230             // Restore the state of the world.
3231             if (flipScopes) {
3232                 m_scopeContextStack = savedScopeContextStack;
3233                 topScope = &m_scopeContextStack[topScopeIndex]; // assert it's within bounds
3234                 bottomScope = m_scopeContextStack.begin() + bottomScopeIndex; // don't assert, since it the index might be -1.
3235             }
3236             if (flipSwitches)
3237                 m_switchContextStack = savedSwitchContextStack;
3238             if (flipForIns)
3239                 m_forInContextStack.swap(savedForInContextStack);
3240             if (flipTries) {
3241                 ASSERT(m_tryContextStack.size() == finallyContext.tryContextStackSize);
3242                 for (unsigned i = poppedTryContexts.size(); i--;) {
3243                     TryContext context = poppedTryContexts[i];
3244                     context.start = afterFinally;
3245                     m_tryContextStack.append(context);
3246                 }
3247                 poppedTryContexts.clear();
3248             }
3249             if (flipLabelScopes)
3250                 m_labelScopes = savedLabelScopes;
3251             if (flipSymbolTableStack)
3252                 m_symbolTableStack = savedSymbolTableStack;
3253             m_finallyDepth = savedFinallyDepth;
3254             m_localScopeDepth = savedDynamicScopeDepth;
3255             
3256             --topScope;
3257         }
3258     }
3259 }
3260
3261 void BytecodeGenerator::emitPopScopes(RegisterID* scope, int targetScopeDepth)
3262 {
3263     ASSERT(labelScopeDepth() - targetScopeDepth >= 0);
3264
3265     size_t scopeDelta = labelScopeDepth() - targetScopeDepth;
3266     ASSERT(scopeDelta <= m_scopeContextStack.size());
3267     if (!scopeDelta)
3268         return;
3269
3270     if (!m_finallyDepth) {
3271         RefPtr<RegisterID> parentScope = newTemporary();
3272         while (scopeDelta--) {
3273             parentScope = emitGetParentScope(parentScope.get(), scope);
3274             emitMove(scope, parentScope.get());
3275         }
3276         return;
3277     }
3278
3279     emitComplexPopScopes(scope, &m_scopeContextStack.last(), &m_scopeContextStack.last() - scopeDelta);
3280 }
3281
3282 TryData* BytecodeGenerator::pushTry(Label* start)
3283 {
3284     TryData tryData;
3285     tryData.target = newLabel();
3286     tryData.handlerType = HandlerType::Illegal;
3287     m_tryData.append(tryData);
3288     TryData* result = &m_tryData.last();
3289     
3290     TryContext tryContext;
3291     tryContext.start = start;
3292     tryContext.tryData = result;
3293     
3294     m_tryContextStack.append(tryContext);
3295     
3296     return result;
3297 }
3298
3299 void BytecodeGenerator::popTryAndEmitCatch(TryData* tryData, RegisterID* exceptionRegister, RegisterID* thrownValueRegister, Label* end, HandlerType handlerType)
3300 {
3301     m_usesExceptions = true;
3302     
3303     ASSERT_UNUSED(tryData, m_tryContextStack.last().tryData == tryData);
3304     
3305     TryRange tryRange;
3306     tryRange.start = m_tryContextStack.last().start;
3307     tryRange.end = end;
3308     tryRange.tryData = m_tryContextStack.last().tryData;
3309     m_tryRanges.append(tryRange);
3310     m_tryContextStack.removeLast();
3311     
3312     emitLabel(tryRange.tryData->target.get());
3313     tryRange.tryData->handlerType = handlerType;
3314
3315     emitOpcode(op_catch);
3316     instructions().append(exceptionRegister->index());
3317     instructions().append(thrownValueRegister->index());
3318
3319     bool foundLocalScope = false;
3320     for (unsigned i = m_symbolTableStack.size(); i--; ) {
3321         // Note that if we don't find a local scope in the current function/program, 
3322         // we must grab the outer-most scope of this bytecode generation.
3323         if (m_symbolTableStack[i].m_scope) {
3324             foundLocalScope = true;
3325             emitMove(scopeRegister(), m_symbolTableStack[i].m_scope);
3326             break;
3327         }
3328     }
3329     if (!foundLocalScope)
3330         emitMove(scopeRegister(), m_topMostScope);
3331 }
3332
3333 int BytecodeGenerator::localScopeDepth() const
3334 {
3335     return m_localScopeDepth;
3336 }
3337
3338 int BytecodeGenerator::labelScopeDepth() const
3339
3340     return localScopeDepth() + m_finallyDepth;
3341 }
3342
3343 void BytecodeGenerator::emitThrowReferenceError(const String& message)
3344 {
3345     emitOpcode(op_throw_static_error);
3346     instructions().append(addConstantValue(addStringConstant(Identifier::fromString(m_vm, message)))->index());
3347     instructions().append(true);
3348 }
3349
3350 void BytecodeGenerator::emitThrowTypeError(const String& message)
3351 {
3352     emitOpcode(op_throw_static_error);
3353     instructions().append(addConstantValue(addStringConstant(Identifier::fromString(m_vm, message)))->index());
3354     instructions().append(false);
3355 }
3356
3357 void BytecodeGenerator::emitPushFunctionNameScope(const Identifier& property, RegisterID* callee, bool isCaptured)
3358 {
3359     // There is some nuance here:
3360     // If we're in strict mode code, the function name scope variable acts exactly like a "const" variable.
3361     // If we're not in strict mode code, we want to allow bogus assignments to the name scoped variable.
3362     // This means any assignment to the variable won't throw, but it won't actually assign a new value to it.
3363     // To accomplish this, we don't report that this scope is a lexical scope. This will prevent
3364     // any throws when trying to assign to the variable (while still ensuring it keeps its original
3365     // value). There is some ugliness and exploitation of a leaky abstraction here, but it's better than 
3366     // having a completely new op code and a class to handle name scopes which are so close in functionality
3367     // to lexical environments.
3368     VariableEnvironment nameScopeEnvironment;
3369     auto addResult = nameScopeEnvironment.add(property);
3370     if (isCaptured)
3371         addResult.iterator->value.setIsCaptured();
3372     addResult.iterator->value.setIsConst(); // The function name scope name acts like a const variable.
3373     unsigned numVars = m_codeBlock->m_numVars;
3374     pushLexicalScopeInternal(nameScopeEnvironment, true, nullptr, TDZRequirement::NotUnderTDZ, ScopeType::FunctionNameScope, ScopeRegisterType::Var);
3375     ASSERT_UNUSED(numVars, m_codeBlock->m_numVars == static_cast<int>(numVars + 1)); // Should have only created one new "var" for the function name scope.
3376     bool shouldTreatAsLexicalVariable = isStrictMode();
3377     Variable functionVar = variableForLocalEntry(property, m_symbolTableStack.last().m_symbolTable->get(property.impl()), m_symbolTableStack.last().m_symbolTableConstantIndex, shouldTreatAsLexicalVariable);
3378     emitPutToScope(m_symbolTableStack.last().m_scope, functionVar, callee, ThrowIfNotFound, NotInitialization);
3379 }
3380
3381 void BytecodeGenerator::pushScopedControlFlowContext()
3382 {
3383     ControlFlowContext context;
3384     context.isFinallyBlock = false;
3385     m_scopeContextStack.append(context);
3386     m_localScopeDepth++;
3387 }
3388
3389 void BytecodeGenerator::popScopedControlFlowContext()
3390 {
3391     ASSERT(m_scopeContextStack.size());
3392     ASSERT(!m_scopeContextStack.last().isFinallyBlock);
3393     m_scopeContextStack.removeLast();
3394     m_localScopeDepth--;
3395 }
3396
3397 void BytecodeGenerator::emitPushCatchScope(const Identifier& property, RegisterID* exceptionValue, VariableEnvironment& environment)
3398 {
3399     RELEASE_ASSERT(environment.contains(property.impl()));
3400     pushLexicalScopeInternal(environment, true, nullptr, TDZRequirement::NotUnderTDZ, ScopeType::CatchScope, ScopeRegisterType::Block);
3401     Variable exceptionVar = variable(property);
3402     RELEASE_ASSERT(exceptionVar.isResolved());
3403     RefPtr<RegisterID> scope = emitResolveScope(nullptr, exceptionVar);
3404     emitPutToScope(scope.get(), exceptionVar, exceptionValue, ThrowIfNotFound, NotInitialization);
3405 }
3406
3407 void BytecodeGenerator::emitPopCatchScope(VariableEnvironment& environment) 
3408 {
3409     popLexicalScopeInternal(environment, TDZRequirement::NotUnderTDZ);
3410 }
3411
3412 void BytecodeGenerator::beginSwitch(RegisterID* scrutineeRegister, SwitchInfo::SwitchType type)
3413 {
3414     SwitchInfo info = { static_cast<uint32_t>(instructions().size()), type };
3415     switch (type) {
3416         case SwitchInfo::SwitchImmediate:
3417             emitOpcode(op_switch_imm);
3418             break;
3419         case SwitchInfo::SwitchCharacter:
3420             emitOpcode(op_switch_char);
3421             break;
3422         case SwitchInfo::SwitchString:
3423             emitOpcode(op_switch_string);
3424             break;
3425         default:
3426             RELEASE_ASSERT_NOT_REACHED();
3427     }
3428
3429     instructions().append(0); // place holder for table index
3430     instructions().append(0); // place holder for default target    
3431     instructions().append(scrutineeRegister->index());
3432     m_switchContextStack.append(info);
3433 }
3434
3435 static int32_t keyForImmediateSwitch(ExpressionNode* node, int32_t min, int32_t max)
3436 {
3437     UNUSED_PARAM(max);
3438     ASSERT(node->isNumber());
3439     double value = static_cast<NumberNode*>(node)->value();
3440     int32_t key = static_cast<int32_t>(value);
3441     ASSERT(key == value);
3442     ASSERT(key >= min);
3443     ASSERT(key <= max);
3444     return key - min;
3445 }
3446
3447 static int32_t keyForCharacterSwitch(ExpressionNode* node, int32_t min, int32_t max)
3448 {
3449     UNUSED_PARAM(max);
3450     ASSERT(node->isString());
3451     StringImpl* clause = static_cast<StringNode*>(node)->value().impl();
3452     ASSERT(clause->length() == 1);
3453     
3454     int32_t key = (*clause)[0];
3455     ASSERT(key >= min);
3456     ASSERT(key <= max);
3457     return key - min;
3458 }
3459
3460 static void prepareJumpTableForSwitch(
3461     UnlinkedSimpleJumpTable& jumpTable, int32_t switchAddress, uint32_t clauseCount,
3462     RefPtr<Label>* labels, ExpressionNode** nodes, int32_t min, int32_t max,
3463     int32_t (*keyGetter)(ExpressionNode*, int32_t min, int32_t max))
3464 {
3465     jumpTable.min = min;
3466     jumpTable.branchOffsets.resize(max - min + 1);
3467     jumpTable.branchOffsets.fill(0);
3468     for (uint32_t i = 0; i < clauseCount; ++i) {
3469         // We're emitting this after the clause labels should have been fixed, so 
3470         // the labels should not be "forward" references
3471         ASSERT(!labels[i]->isForward());
3472         jumpTable.add(keyGetter(nodes[i], min, max), labels[i]->bind(switchAddress, switchAddress + 3)); 
3473     }
3474 }
3475
3476 static void prepareJumpTableForStringSwitch(UnlinkedStringJumpTable& jumpTable, int32_t switchAddress, uint32_t clauseCount, RefPtr<Label>* labels, ExpressionNode** nodes)
3477 {
3478     for (uint32_t i = 0; i < clauseCount; ++i) {
3479         // We're emitting this after the clause labels should have been fixed, so 
3480         // the labels should not be "forward" references
3481         ASSERT(!labels[i]->isForward());
3482         
3483         ASSERT(nodes[i]->isString());
3484         StringImpl* clause = static_cast<StringNode*>(nodes[i])->value().impl();
3485         jumpTable.offsetTable.add(clause, labels[i]->bind(switchAddress, switchAddress + 3));
3486     }
3487 }
3488
3489 void BytecodeGenerator::endSwitch(uint32_t clauseCount, RefPtr<Label>* labels, ExpressionNode** nodes, Label* defaultLabel, int32_t min, int32_t max)
3490 {
3491     SwitchInfo switchInfo = m_switchContextStack.last();
3492     m_switchContextStack.removeLast();
3493     
3494     switch (switchInfo.switchType) {
3495     case SwitchInfo::SwitchImmediate:
3496     case SwitchInfo::SwitchCharacter: {
3497         instructions()[switchInfo.bytecodeOffset + 1] = m_codeBlock->numberOfSwitchJumpTables();
3498         instructions()[switchInfo.bytecodeOffset + 2] = defaultLabel->bind(switchInfo.bytecodeOffset, switchInfo.bytecodeOffset + 3);
3499
3500         UnlinkedSimpleJumpTable& jumpTable = m_codeBlock->addSwitchJumpTable();
3501         prepareJumpTableForSwitch(
3502             jumpTable, switchInfo.bytecodeOffset, clauseCount, labels, nodes, min, max,
3503             switchInfo.switchType == SwitchInfo::SwitchImmediate
3504                 ? keyForImmediateSwitch
3505                 : keyForCharacterSwitch); 
3506         break;
3507     }
3508         
3509     case SwitchInfo::SwitchString: {
3510         instructions()[switchInfo.bytecodeOffset + 1] = m_codeBlock->numberOfStringSwitchJumpTables();
3511         instructions()[switchInfo.bytecodeOffset + 2] = defaultLabel->bind(switchInfo.bytecodeOffset, switchInfo.bytecodeOffset + 3);
3512
3513         UnlinkedStringJumpTable& jumpTable = m_codeBlock->addStringSwitchJumpTable();
3514         prepareJumpTableForStringSwitch(jumpTable, switchInfo.bytecodeOffset, clauseCount, labels, nodes);
3515         break;
3516     }
3517         
3518     default:
3519         RELEASE_ASSERT_NOT_REACHED();
3520         break;
3521     }
3522 }
3523
3524 RegisterID* BytecodeGenerator::emitThrowExpressionTooDeepException()
3525 {
3526     // It would be nice to do an even better job of identifying exactly where the expression is.
3527     // And we could make the caller pass the node pointer in, if there was some way of getting
3528     // that from an arbitrary node. However, calling emitExpressionInfo without any useful data
3529     // is still good enough to get us an accurate line number.
3530     m_expressionTooDeep = true;
3531     return newTemporary();
3532 }
3533
3534 bool BytecodeGenerator::isArgumentNumber(const Identifier& ident, int argumentNumber)
3535 {
3536     RegisterID* registerID = variable(ident).local();
3537     if (!registerID)
3538         return false;
3539     return registerID->index() == CallFrame::argumentOffset(argumentNumber);
3540 }
3541
3542 bool BytecodeGenerator::emitReadOnlyExceptionIfNeeded(const Variable& variable)
3543 {
3544     // If we're in strict mode, we always throw.
3545     // If we're not in strict mode, we throw for "const" variables but not the function callee.
3546     if (isStrictMode() || variable.isConst()) {
3547         emitOpcode(op_throw_static_error);
3548         instructions().append(addConstantValue(addStringConstant(Identifier::fromString(m_vm, StrictModeReadonlyPropertyWriteError)))->index());
3549         instructions().append(false);
3550         return true;
3551     }
3552     return false;
3553 }
3554     
3555 void BytecodeGenerator::emitEnumeration(ThrowableExpressionData* node, ExpressionNode* subjectNode, const std::function<void(BytecodeGenerator&, RegisterID*)>& callBack, VariableEnvironmentNode* forLoopNode, RegisterID* forLoopSymbolTable)
3556 {
3557     RefPtr<RegisterID> subject = newTemporary();
3558     emitNode(subject.get(), subjectNode);
3559     RefPtr<RegisterID> iterator = emitGetById(newTemporary(), subject.get(), propertyNames().iteratorSymbol);
3560     {
3561         CallArguments args(*this, nullptr);
3562         emitMove(args.thisRegister(), subject.get());
3563         emitCall(iterator.get(), iterator.get(), NoExpectedFunction, args, node->divot(), node->divotStart(), node->divotEnd());
3564     }
3565
3566     RefPtr<Label> loopDone = newLabel();
3567     // RefPtr<Register> iterator's lifetime must be longer than IteratorCloseContext.
3568     pushIteratorCloseContext(iterator.get(), node);
3569     {
3570         LabelScopePtr scope = newLabelScope(LabelScope::Loop);
3571         RefPtr<RegisterID> value = newTemporary();
3572         emitLoad(value.get(), jsUndefined());
3573
3574         emitJump(scope->continueTarget());
3575
3576         RefPtr<Label> loopStart = newLabel();
3577         emitLabel(loopStart.get());
3578         emitLoopHint();
3579
3580         RefPtr<Label> tryStartLabel = newLabel();
3581         emitLabel(tryStartLabel.get());
3582         TryData* tryData = pushTry(tryStartLabel.get());
3583         callBack(*this, value.get());
3584         emitJump(scope->continueTarget());
3585
3586         // IteratorClose sequence for throw-ed control flow.
3587         {
3588             RefPtr<Label> catchHere = emitLabel(newLabel().get());
3589             RefPtr<RegisterID> exceptionRegister = newTemporary();
3590             RefPtr<RegisterID> thrownValueRegister = newTemporary();
3591             popTryAndEmitCatch(tryData, exceptionRegister.get(),
3592                 thrownValueRegister.get(), catchHere.get(), HandlerType::SynthesizedFinally);
3593
3594             RefPtr<Label> catchDone = newLabel();
3595
3596             RefPtr<RegisterID> returnMethod = emitGetById(newTemporary(), iterator.get(), propertyNames().returnKeyword);
3597             emitJumpIfTrue(emitIsUndefined(newTemporary(), returnMethod.get()), catchDone.get());
3598
3599             RefPtr<Label> returnCallTryStart = newLabel();
3600             emitLabel(returnCallTryStart.get());
3601             TryData* returnCallTryData = pushTry(returnCallTryStart.get());
3602
3603             CallArguments returnArguments(*this, nullptr);
3604             emitMove(returnArguments.thisRegister(), iterator.get());
3605             emitCall(value.get(), returnMethod.get(), NoExpectedFunction, returnArguments, node->divot(), node->divotStart(), node->divotEnd());
3606
3607             emitLabel(catchDone.get());
3608             emitThrow(exceptionRegister.get());
3609
3610             // Absorb exception.
3611             popTryAndEmitCatch(returnCallTryData, newTemporary(),
3612                 newTemporary(), catchDone.get(), HandlerType::SynthesizedFinally);
3613             emitThrow(exceptionRegister.get());
3614         }
3615
3616         emitLabel(scope->continueTarget());
3617         if (forLoopNode)
3618             prepareLexicalScopeForNextForLoopIteration(forLoopNode, forLoopSymbolTable);
3619
3620         {
3621             emitIteratorNext(value.get(), iterator.get(), node);
3622             emitJumpIfTrue(emitGetById(newTemporary(), value.get(), propertyNames().done), loopDone.get());
3623             emitGetById(value.get(), value.get(), propertyNames().value);
3624             emitJump(loopStart.get());
3625         }
3626
3627         emitLabel(scope->breakTarget());
3628     }
3629
3630     // IteratorClose sequence for break-ed control flow.
3631     popIteratorCloseContext();
3632     emitIteratorClose(iterator.get(), node);
3633     emitLabel(loopDone.get());
3634 }
3635
3636 RegisterID* BytecodeGenerator::emitGetTemplateObject(RegisterID* dst, TaggedTemplateNode* taggedTemplate)
3637 {
3638     TemplateRegistryKey::StringVector rawStrings;
3639     TemplateRegistryKey::StringVector cookedStrings;
3640
3641     TemplateStringListNode* templateString = taggedTemplate->templateLiteral()->templateStrings();
3642     for (; templateString; templateString = templateString->next()) {
3643         rawStrings.append(templateString->value()->raw().impl());
3644         cookedStrings.append(templateString->value()->cooked().impl());
3645     }
3646
3647     RefPtr<RegisterID> getTemplateObject = nullptr;
3648     Variable var = variable(propertyNames().getTemplateObjectPrivateName);
3649     if (RegisterID* local = var.local())
3650         getTemplateObject = emitMove(newTemporary(), local);
3651     else {
3652         getTemplateObject = newTemporary();
3653         RefPtr<RegisterID> scope = newTemporary();
3654         moveToDestinationIfNeeded(scope.get(), emitResolveScope(scope.get(), var));
3655         emitGetFromScope(getTemplateObject.get(), scope.get(), var, ThrowIfNotFound);
3656     }
3657
3658     CallArguments arguments(*this, nullptr);
3659     emitLoad(arguments.thisRegister(), JSValue(addTemplateRegistryKeyConstant(TemplateRegistryKey(rawStrings, cookedStrings))));
3660     return emitCall(dst, getTemplateObject.get(), NoExpectedFunction, arguments, taggedTemplate->divot(), taggedTemplate->divotStart(), taggedTemplate->divotEnd());
3661 }
3662
3663 RegisterID* BytecodeGenerator::emitGetEnumerableLength(RegisterID* dst, RegisterID* base)
3664 {
3665     emitOpcode(op_get_enumerable_length);
3666     instructions().append(dst->index());
3667     instructions().append(base->index());
3668     return dst;
3669 }
3670
3671 RegisterID* BytecodeGenerator::emitHasGenericProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName)
3672 {
3673     emitOpcode(op_has_generic_property);
3674     instructions().append(dst->index());
3675     instructions().append(base->index());
3676     instructions().append(propertyName->index());