2829391a609948ab4c806c6351fb1d2ed8dae635
[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 "JSNameScope.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     for (size_t i = 0; i < m_deconstructedParameters.size(); i++) {
74         auto& entry = m_deconstructedParameters[i];
75         entry.second->bindValue(*this, entry.first.get());
76     }
77
78     {
79         RefPtr<RegisterID> temp = newTemporary();
80         RefPtr<RegisterID> globalScope = scopeRegister(); // FIXME: With lexical scoping, this won't always be the global object: https://bugs.webkit.org/show_bug.cgi?id=142944 
81         for (auto functionPair : m_functionsToInitialize) {
82             FunctionBodyNode* functionBody = functionPair.first;
83             FunctionVariableType functionType = functionPair.second;
84             emitNewFunction(temp.get(), functionBody);
85             if (functionType == NormalFunctionVariable)
86                 initializeVariable(variable(functionBody->ident()) , temp.get());
87             else if (functionType == GlobalFunctionVariable)
88                 emitPutToScope(globalScope.get(), Variable(functionBody->ident()), temp.get(), ThrowIfNotFound);
89             else
90                 RELEASE_ASSERT_NOT_REACHED();
91         }
92     }
93     
94     bool callingClassConstructor = constructorKind() != ConstructorKind::None && !isConstructor();
95     if (!callingClassConstructor)
96         m_scopeNode->emitBytecode(*this);
97
98     m_staticPropertyAnalyzer.kill();
99
100     for (unsigned i = 0; i < m_tryRanges.size(); ++i) {
101         TryRange& range = m_tryRanges[i];
102         int start = range.start->bind();
103         int end = range.end->bind();
104         
105         // This will happen for empty try blocks and for some cases of finally blocks:
106         //
107         // try {
108         //    try {
109         //    } finally {
110         //        return 42;
111         //        // *HERE*
112         //    }
113         // } finally {
114         //    print("things");
115         // }
116         //
117         // The return will pop scopes to execute the outer finally block. But this includes
118         // popping the try context for the inner try. The try context is live in the fall-through
119         // part of the finally block not because we will emit a handler that overlaps the finally,
120         // but because we haven't yet had a chance to plant the catch target. Then when we finish
121         // emitting code for the outer finally block, we repush the try contex, this time with a
122         // new start index. But that means that the start index for the try range corresponding
123         // to the inner-finally-following-the-return (marked as "*HERE*" above) will be greater
124         // than the end index of the try block. This is harmless since end < start handlers will
125         // never get matched in our logic, but we do the runtime a favor and choose to not emit
126         // such handlers at all.
127         if (end <= start)
128             continue;
129         
130         ASSERT(range.tryData->targetScopeDepth != UINT_MAX);
131         UnlinkedHandlerInfo info = {
132             static_cast<uint32_t>(start), static_cast<uint32_t>(end),
133             static_cast<uint32_t>(range.tryData->target->bind()),
134             range.tryData->targetScopeDepth
135         };
136         m_codeBlock->addExceptionHandler(info);
137     }
138     
139     m_codeBlock->setInstructions(std::make_unique<UnlinkedInstructionStream>(m_instructions));
140
141     m_codeBlock->shrinkToFit();
142
143     if (m_codeBlock->symbolTable() && !m_codeBlock->vm()->typeProfiler())
144         m_codeBlock->setSymbolTable(m_codeBlock->symbolTable()->cloneScopePart(*m_codeBlock->vm()));
145
146     if (m_expressionTooDeep)
147         return ParserError(ParserError::OutOfMemory);
148     return ParserError(ParserError::ErrorNone);
149 }
150
151 BytecodeGenerator::BytecodeGenerator(VM& vm, ProgramNode* programNode, UnlinkedProgramCodeBlock* codeBlock, DebuggerMode debuggerMode, ProfilerMode profilerMode)
152     : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
153     , m_shouldEmitProfileHooks(Options::forceProfilerBytecodeGeneration() || profilerMode == ProfilerOn)
154     , m_scopeNode(programNode)
155     , m_codeBlock(vm, codeBlock)
156     , m_thisRegister(CallFrame::thisArgumentOffset())
157     , m_codeType(GlobalCode)
158     , m_vm(&vm)
159 {
160     for (auto& constantRegister : m_linkTimeConstantRegisters)
161         constantRegister = nullptr;
162
163     m_codeBlock->setNumParameters(1); // Allocate space for "this"
164
165     emitOpcode(op_enter);
166
167     allocateAndEmitScope();
168
169     const VarStack& varStack = programNode->varStack();
170     const FunctionStack& functionStack = programNode->functionStack();
171
172     for (size_t i = 0; i < functionStack.size(); ++i) {
173         FunctionBodyNode* function = functionStack[i];
174         m_functionsToInitialize.append(std::make_pair(function, GlobalFunctionVariable));
175     }
176
177     for (size_t i = 0; i < varStack.size(); ++i)
178         codeBlock->addVariableDeclaration(varStack[i].first, !!(varStack[i].second & DeclarationStacks::IsConstant));
179
180 }
181
182 BytecodeGenerator::BytecodeGenerator(VM& vm, FunctionNode* functionNode, UnlinkedFunctionCodeBlock* codeBlock, DebuggerMode debuggerMode, ProfilerMode profilerMode)
183     : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
184     , m_shouldEmitProfileHooks(Options::forceProfilerBytecodeGeneration() || profilerMode == ProfilerOn)
185     , m_symbolTable(codeBlock->symbolTable())
186     , m_scopeNode(functionNode)
187     , m_codeBlock(vm, codeBlock)
188     , m_codeType(FunctionCode)
189     , m_vm(&vm)
190     , m_isBuiltinFunction(codeBlock->isBuiltinFunction())
191 {
192     for (auto& constantRegister : m_linkTimeConstantRegisters)
193         constantRegister = nullptr;
194
195     if (m_isBuiltinFunction)
196         m_shouldEmitDebugHooks = false;
197     
198     m_symbolTable->setUsesNonStrictEval(codeBlock->usesEval() && !codeBlock->isStrictMode());
199     Vector<Identifier> boundParameterProperties;
200     FunctionParameters& parameters = *functionNode->parameters();
201     for (size_t i = 0; i < parameters.size(); i++) {
202         auto pattern = parameters.at(i);
203         if (pattern->isBindingNode())
204             continue;
205         pattern->collectBoundIdentifiers(boundParameterProperties);
206         continue;
207     }
208
209     bool shouldCaptureSomeOfTheThings = m_shouldEmitDebugHooks || m_codeBlock->needsFullScopeChain();
210     bool shouldCaptureAllOfTheThings = m_shouldEmitDebugHooks || codeBlock->usesEval();
211     bool needsArguments = functionNode->usesArguments() || codeBlock->usesEval();
212     
213     auto captures = [&] (StringImpl* uid) -> bool {
214         if (shouldCaptureAllOfTheThings)
215             return true;
216         if (!shouldCaptureSomeOfTheThings)
217             return false;
218         if (needsArguments && uid == propertyNames().arguments.impl()) {
219             // Actually, we only need to capture the arguments object when we "need full activation"
220             // because of name scopes. But historically we did it this way, so for now we just preserve
221             // the old behavior.
222             // FIXME: https://bugs.webkit.org/show_bug.cgi?id=143072
223             return true;
224         }
225         return functionNode->captures(uid);
226     };
227     auto varKind = [&] (StringImpl* uid) -> VarKind {
228         return captures(uid) ? VarKind::Scope : VarKind::Stack;
229     };
230
231     emitOpcode(op_enter);
232
233     allocateAndEmitScope();
234     
235     m_calleeRegister.setIndex(JSStack::Callee);
236     
237     if (functionNameIsInScope(functionNode->ident(), functionNode->functionMode())
238         && functionNameScopeIsDynamic(codeBlock->usesEval(), codeBlock->isStrictMode())) {
239         // When we do this, we should make our local scope stack know about the function name symbol
240         // table. Currently this works because bytecode linking creates a phony name scope.
241         // FIXME: https://bugs.webkit.org/show_bug.cgi?id=141885
242         // Also, we could create the scope once per JSFunction instance that needs it. That wouldn't
243         // be any more correct, but it would be more performant.
244         // FIXME: https://bugs.webkit.org/show_bug.cgi?id=141887
245         emitPushFunctionNameScope(m_scopeRegister, functionNode->ident(), &m_calleeRegister, ReadOnly | DontDelete);
246     }
247
248     if (shouldCaptureSomeOfTheThings) {
249         m_lexicalEnvironmentRegister = addVar();
250         m_codeBlock->setActivationRegister(m_lexicalEnvironmentRegister->virtualRegister());
251         emitOpcode(op_create_lexical_environment);
252         instructions().append(m_lexicalEnvironmentRegister->index());
253         instructions().append(scopeRegister()->index());
254         emitOpcode(op_mov);
255         instructions().append(scopeRegister()->index());
256         instructions().append(m_lexicalEnvironmentRegister->index());
257     }
258     
259     // Make sure the code block knows about all of our parameters, and make sure that parameters
260     // needing deconstruction are noted.
261     m_parameters.grow(parameters.size() + 1); // reserve space for "this"
262     m_thisRegister.setIndex(initializeNextParameter()->index()); // this
263     for (unsigned i = 0; i < parameters.size(); ++i) {
264         auto pattern = parameters.at(i);
265         RegisterID* reg = initializeNextParameter();
266         if (!pattern->isBindingNode())
267             m_deconstructedParameters.append(std::make_pair(reg, pattern));
268     }
269     
270     // Figure out some interesting facts about our arguments.
271     bool capturesAnyArgumentByName = false;
272     if (functionNode->hasCapturedVariables()) {
273         FunctionParameters& parameters = *functionNode->parameters();
274         for (size_t i = 0; i < parameters.size(); ++i) {
275             auto pattern = parameters.at(i);
276             if (!pattern->isBindingNode())
277                 continue;
278             const Identifier& ident = static_cast<const BindingNode*>(pattern)->boundProperty();
279             capturesAnyArgumentByName |= captures(ident.impl());
280         }
281     }
282
283     if (capturesAnyArgumentByName)
284         ASSERT(m_lexicalEnvironmentRegister);
285     
286     // Need to know what our functions are called. Parameters have some goofy behaviors when it
287     // comes to functions of the same name.
288     for (FunctionBodyNode* function : functionNode->functionStack())
289         m_functions.add(function->ident().impl());
290     
291     if (needsArguments) {
292         // Create the arguments object now. We may put the arguments object into the activation if
293         // it is captured. Either way, we create two arguments object variables: one is our
294         // private variable that is immutable, and another that is the user-visible variable. The
295         // immutable one is only used here, or during formal parameter resolutions if we opt for
296         // DirectArguments.
297         
298         m_argumentsRegister = addVar();
299         m_argumentsRegister->ref();
300     }
301     
302     if (needsArguments && !codeBlock->isStrictMode()) {
303         // If we captured any formal parameter by name, then we use ScopedArguments. Otherwise we
304         // use DirectArguments. With ScopedArguments, we lift all of our arguments into the
305         // activation.
306         
307         if (capturesAnyArgumentByName) {
308             m_symbolTable->setArgumentsLength(vm, parameters.size());
309             
310             // For each parameter, we have two possibilities:
311             // Either it's a binding node with no function overlap, in which case it gets a name
312             // in the symbol table - or it just gets space reserved in the symbol table. Either
313             // way we lift the value into the scope.
314             for (unsigned i = 0; i < parameters.size(); ++i) {
315                 ScopeOffset offset = m_symbolTable->takeNextScopeOffset();
316                 m_symbolTable->setArgumentOffset(vm, i, offset);
317                 if (StringImpl* name = visibleNameForParameter(parameters.at(i))) {
318                     VarOffset varOffset(offset);
319                     SymbolTableEntry entry(varOffset);
320                     // Stores to these variables via the ScopedArguments object will not do
321                     // notifyWrite(), since that would be cumbersome. Also, watching formal
322                     // parameters when "arguments" is in play is unlikely to be super profitable.
323                     // So, we just disable it.
324                     entry.disableWatching();
325                     m_symbolTable->set(name, entry);
326                 }
327                 emitOpcode(op_put_to_scope);
328                 instructions().append(m_lexicalEnvironmentRegister->index());
329                 instructions().append(UINT_MAX);
330                 instructions().append(virtualRegisterForArgument(1 + i).offset());
331                 instructions().append(ResolveModeAndType(ThrowIfNotFound, LocalClosureVar).operand());
332                 instructions().append(0);
333                 instructions().append(offset.offset());
334             }
335             
336             // This creates a scoped arguments object and copies the overflow arguments into the
337             // scope. It's the equivalent of calling ScopedArguments::createByCopying().
338             emitOpcode(op_create_scoped_arguments);
339             instructions().append(m_argumentsRegister->index());
340             instructions().append(m_lexicalEnvironmentRegister->index());
341         } else {
342             // We're going to put all parameters into the DirectArguments object. First ensure
343             // that the symbol table knows that this is happening.
344             for (unsigned i = 0; i < parameters.size(); ++i) {
345                 if (StringImpl* name = visibleNameForParameter(parameters.at(i)))
346                     m_symbolTable->set(name, SymbolTableEntry(VarOffset(DirectArgumentsOffset(i))));
347             }
348             
349             emitOpcode(op_create_direct_arguments);
350             instructions().append(m_argumentsRegister->index());
351         }
352     } else {
353         // Create the formal parameters the normal way. Any of them could be captured, or not. If
354         // captured, lift them into the scope.
355         for (unsigned i = 0; i < parameters.size(); ++i) {
356             StringImpl* name = visibleNameForParameter(parameters.at(i));
357             if (!name)
358                 continue;
359             
360             if (!captures(name)) {
361                 // This is the easy case - just tell the symbol table about the argument. It will
362                 // be accessed directly.
363                 m_symbolTable->set(name, SymbolTableEntry(VarOffset(virtualRegisterForArgument(1 + i))));
364                 continue;
365             }
366             
367             ScopeOffset offset = m_symbolTable->takeNextScopeOffset();
368             const Identifier& ident =
369                 static_cast<const BindingNode*>(parameters.at(i))->boundProperty();
370             m_symbolTable->set(name, SymbolTableEntry(VarOffset(offset)));
371             
372             emitOpcode(op_put_to_scope);
373             instructions().append(m_lexicalEnvironmentRegister->index());
374             instructions().append(addConstant(ident));
375             instructions().append(virtualRegisterForArgument(1 + i).offset());
376             instructions().append(ResolveModeAndType(ThrowIfNotFound, LocalClosureVar).operand());
377             instructions().append(0);
378             instructions().append(offset.offset());
379         }
380     }
381     
382     if (needsArguments && codeBlock->isStrictMode()) {
383         // Allocate an out-of-bands arguments object.
384         emitOpcode(op_create_out_of_band_arguments);
385         instructions().append(m_argumentsRegister->index());
386     }
387     
388     // Now declare all variables.
389     for (const Identifier& ident : boundParameterProperties)
390         createVariable(ident, varKind(ident.impl()), IsVariable);
391     for (FunctionBodyNode* function : functionNode->functionStack()) {
392         const Identifier& ident = function->ident();
393         createVariable(ident, varKind(ident.impl()), IsVariable);
394         m_functionsToInitialize.append(std::make_pair(function, NormalFunctionVariable));
395     }
396     for (auto& entry : functionNode->varStack()) {
397         ConstantMode constantMode = modeForIsConstant(entry.second & DeclarationStacks::IsConstant);
398         // Variables named "arguments" are never const.
399         if (entry.first == propertyNames().arguments)
400             constantMode = IsVariable;
401         createVariable(entry.first, varKind(entry.first.impl()), constantMode, IgnoreExisting);
402     }
403     
404     // There are some variables that need to be preinitialized to something other than Undefined:
405     //
406     // - "arguments": unless it's used as a function or parameter, this should refer to the
407     //   arguments object.
408     //
409     // - callee: unless it's used as a var, function, or parameter, this should refer to the
410     //   callee (i.e. our function).
411     //
412     // - functions: these always override everything else.
413     //
414     // The most logical way to do all of this is to initialize none of the variables until now,
415     // and then initialize them in BytecodeGenerator::generate() in such an order that the rules
416     // for how these things override each other end up holding. We would initialize the callee
417     // first, then "arguments", then all arguments, then the functions.
418     //
419     // But some arguments are already initialized by default, since if they aren't captured and we
420     // don't have "arguments" then we just point the symbol table at the stack slot of those
421     // arguments. We end up initializing the rest of the arguments that have an uncomplicated
422     // binding (i.e. don't involve deconstruction) above when figuring out how to lay them out,
423     // because that's just the simplest thing. This means that when we initialize them, we have to
424     // watch out for the things that override arguments (namely, functions).
425     //
426     // We also initialize callee here as well, just because it's so weird. We know whether we want
427     // to do this because we can just check if it's in the symbol table.
428     if (functionNameIsInScope(functionNode->ident(), functionNode->functionMode())
429         && !functionNameScopeIsDynamic(codeBlock->usesEval(), codeBlock->isStrictMode())
430         && m_symbolTable->get(functionNode->ident().impl()).isNull()) {
431         if (captures(functionNode->ident().impl())) {
432             ScopeOffset offset;
433             {
434                 ConcurrentJITLocker locker(m_symbolTable->m_lock);
435                 offset = m_symbolTable->takeNextScopeOffset(locker);
436                 m_symbolTable->add(
437                     locker, functionNode->ident().impl(),
438                     SymbolTableEntry(VarOffset(offset), ReadOnly));
439             }
440             
441             emitOpcode(op_put_to_scope);
442             instructions().append(m_lexicalEnvironmentRegister->index());
443             instructions().append(addConstant(functionNode->ident()));
444             instructions().append(m_calleeRegister.index());
445             instructions().append(ResolveModeAndType(ThrowIfNotFound, LocalClosureVar).operand());
446             instructions().append(0);
447             instructions().append(offset.offset());
448         } else {
449             m_symbolTable->add(
450                 functionNode->ident().impl(),
451                 SymbolTableEntry(VarOffset(m_calleeRegister.virtualRegister()), ReadOnly));
452         }
453     }
454     
455     // This is our final act of weirdness. "arguments" is overridden by everything except the
456     // callee. We add it to the symbol table if it's not already there and it's not an argument.
457     if (needsArguments) {
458         // If "arguments" is overridden by a function or deconstructed parameter name, then it's
459         // OK for us to call createVariable() because it won't change anything. It's also OK for
460         // us to them tell BytecodeGenerator::generate() to write to it because it will do so
461         // before it initializes functions and deconstructed parameters. But if "arguments" is
462         // overridden by a "simple" function parameter, then we have to bail: createVariable()
463         // would assert and BytecodeGenerator::generate() would write the "arguments" after the
464         // argument value had already been properly initialized.
465         
466         bool haveParameterNamedArguments = false;
467         for (unsigned i = 0; i < parameters.size(); ++i) {
468             StringImpl* name = visibleNameForParameter(parameters.at(i));
469             if (name == propertyNames().arguments.impl()) {
470                 haveParameterNamedArguments = true;
471                 break;
472             }
473         }
474         
475         if (!haveParameterNamedArguments) {
476             createVariable(
477                 propertyNames().arguments, varKind(propertyNames().arguments.impl()), IsVariable);
478             m_needToInitializeArguments = true;
479         }
480     }
481     
482     if (isConstructor()) {
483         if (constructorKind() == ConstructorKind::Derived) {
484             m_newTargetRegister = addVar();
485             emitMove(m_newTargetRegister, &m_thisRegister);
486             emitMoveEmptyValue(&m_thisRegister);
487         } else
488             emitCreateThis(&m_thisRegister);
489     } else if (constructorKind() != ConstructorKind::None) {
490         emitThrowTypeError("Cannot call a class constructor");
491     } else if (functionNode->usesThis() || codeBlock->usesEval()) {
492         m_codeBlock->addPropertyAccessInstruction(instructions().size());
493         emitOpcode(op_to_this);
494         instructions().append(kill(&m_thisRegister));
495         instructions().append(0);
496         instructions().append(0);
497     }
498 }
499
500 BytecodeGenerator::BytecodeGenerator(VM& vm, EvalNode* evalNode, UnlinkedEvalCodeBlock* codeBlock, DebuggerMode debuggerMode, ProfilerMode profilerMode)
501     : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
502     , m_shouldEmitProfileHooks(Options::forceProfilerBytecodeGeneration() || profilerMode == ProfilerOn)
503     , m_symbolTable(codeBlock->symbolTable())
504     , m_scopeNode(evalNode)
505     , m_codeBlock(vm, codeBlock)
506     , m_thisRegister(CallFrame::thisArgumentOffset())
507     , m_codeType(EvalCode)
508     , m_vm(&vm)
509 {
510     for (auto& constantRegister : m_linkTimeConstantRegisters)
511         constantRegister = nullptr;
512
513     m_symbolTable->setUsesNonStrictEval(codeBlock->usesEval() && !codeBlock->isStrictMode());
514     m_codeBlock->setNumParameters(1);
515
516     emitOpcode(op_enter);
517
518     allocateAndEmitScope();
519
520     const DeclarationStacks::FunctionStack& functionStack = evalNode->functionStack();
521     for (size_t i = 0; i < functionStack.size(); ++i)
522         m_codeBlock->addFunctionDecl(makeFunction(functionStack[i]));
523
524     const DeclarationStacks::VarStack& varStack = evalNode->varStack();
525     unsigned numVariables = varStack.size();
526     Vector<Identifier, 0, UnsafeVectorOverflow> variables;
527     variables.reserveCapacity(numVariables);
528     for (size_t i = 0; i < numVariables; ++i) {
529         ASSERT(varStack[i].first.impl()->isAtomic() || varStack[i].first.impl()->isSymbol());
530         variables.append(varStack[i].first);
531     }
532     codeBlock->adoptVariables(variables);
533 }
534
535 BytecodeGenerator::~BytecodeGenerator()
536 {
537 }
538
539 RegisterID* BytecodeGenerator::initializeNextParameter()
540 {
541     VirtualRegister reg = virtualRegisterForArgument(m_codeBlock->numParameters());
542     RegisterID& parameter = registerFor(reg);
543     parameter.setIndex(reg.offset());
544     m_codeBlock->addParameter();
545     return &parameter;
546 }
547
548 StringImpl* BytecodeGenerator::visibleNameForParameter(DeconstructionPatternNode* pattern)
549 {
550     if (pattern->isBindingNode()) {
551         const Identifier& ident = static_cast<const BindingNode*>(pattern)->boundProperty();
552         if (!m_functions.contains(ident.impl()))
553             return ident.impl();
554     }
555     return nullptr;
556 }
557
558 RegisterID* BytecodeGenerator::newRegister()
559 {
560     m_calleeRegisters.append(virtualRegisterForLocal(m_calleeRegisters.size()));
561     int numCalleeRegisters = max<int>(m_codeBlock->m_numCalleeRegisters, m_calleeRegisters.size());
562     numCalleeRegisters = WTF::roundUpToMultipleOf(stackAlignmentRegisters(), numCalleeRegisters);
563     m_codeBlock->m_numCalleeRegisters = numCalleeRegisters;
564     return &m_calleeRegisters.last();
565 }
566
567 RegisterID* BytecodeGenerator::newTemporary()
568 {
569     // Reclaim free register IDs.
570     while (m_calleeRegisters.size() && !m_calleeRegisters.last().refCount())
571         m_calleeRegisters.removeLast();
572         
573     RegisterID* result = newRegister();
574     result->setTemporary();
575     return result;
576 }
577
578 LabelScopePtr BytecodeGenerator::newLabelScope(LabelScope::Type type, const Identifier* name)
579 {
580     // Reclaim free label scopes.
581     while (m_labelScopes.size() && !m_labelScopes.last().refCount())
582         m_labelScopes.removeLast();
583
584     // Allocate new label scope.
585     LabelScope scope(type, name, scopeDepth(), newLabel(), type == LabelScope::Loop ? newLabel() : PassRefPtr<Label>()); // Only loops have continue targets.
586     m_labelScopes.append(scope);
587     return LabelScopePtr(m_labelScopes, m_labelScopes.size() - 1);
588 }
589
590 PassRefPtr<Label> BytecodeGenerator::newLabel()
591 {
592     // Reclaim free label IDs.
593     while (m_labels.size() && !m_labels.last().refCount())
594         m_labels.removeLast();
595
596     // Allocate new label ID.
597     m_labels.append(*this);
598     return &m_labels.last();
599 }
600
601 PassRefPtr<Label> BytecodeGenerator::emitLabel(Label* l0)
602 {
603     unsigned newLabelIndex = instructions().size();
604     l0->setLocation(newLabelIndex);
605
606     if (m_codeBlock->numberOfJumpTargets()) {
607         unsigned lastLabelIndex = m_codeBlock->lastJumpTarget();
608         ASSERT(lastLabelIndex <= newLabelIndex);
609         if (newLabelIndex == lastLabelIndex) {
610             // Peephole optimizations have already been disabled by emitting the last label
611             return l0;
612         }
613     }
614
615     m_codeBlock->addJumpTarget(newLabelIndex);
616
617     // This disables peephole optimizations when an instruction is a jump target
618     m_lastOpcodeID = op_end;
619     return l0;
620 }
621
622 void BytecodeGenerator::emitOpcode(OpcodeID opcodeID)
623 {
624 #ifndef NDEBUG
625     size_t opcodePosition = instructions().size();
626     ASSERT(opcodePosition - m_lastOpcodePosition == opcodeLength(m_lastOpcodeID) || m_lastOpcodeID == op_end);
627     m_lastOpcodePosition = opcodePosition;
628 #endif
629     instructions().append(opcodeID);
630     m_lastOpcodeID = opcodeID;
631 }
632
633 UnlinkedArrayProfile BytecodeGenerator::newArrayProfile()
634 {
635     return m_codeBlock->addArrayProfile();
636 }
637
638 UnlinkedArrayAllocationProfile BytecodeGenerator::newArrayAllocationProfile()
639 {
640     return m_codeBlock->addArrayAllocationProfile();
641 }
642
643 UnlinkedObjectAllocationProfile BytecodeGenerator::newObjectAllocationProfile()
644 {
645     return m_codeBlock->addObjectAllocationProfile();
646 }
647
648 UnlinkedValueProfile BytecodeGenerator::emitProfiledOpcode(OpcodeID opcodeID)
649 {
650     UnlinkedValueProfile result = m_codeBlock->addValueProfile();
651     emitOpcode(opcodeID);
652     return result;
653 }
654
655 void BytecodeGenerator::emitLoopHint()
656 {
657     emitOpcode(op_loop_hint);
658 }
659
660 void BytecodeGenerator::retrieveLastBinaryOp(int& dstIndex, int& src1Index, int& src2Index)
661 {
662     ASSERT(instructions().size() >= 4);
663     size_t size = instructions().size();
664     dstIndex = instructions().at(size - 3).u.operand;
665     src1Index = instructions().at(size - 2).u.operand;
666     src2Index = instructions().at(size - 1).u.operand;
667 }
668
669 void BytecodeGenerator::retrieveLastUnaryOp(int& dstIndex, int& srcIndex)
670 {
671     ASSERT(instructions().size() >= 3);
672     size_t size = instructions().size();
673     dstIndex = instructions().at(size - 2).u.operand;
674     srcIndex = instructions().at(size - 1).u.operand;
675 }
676
677 void ALWAYS_INLINE BytecodeGenerator::rewindBinaryOp()
678 {
679     ASSERT(instructions().size() >= 4);
680     instructions().shrink(instructions().size() - 4);
681     m_lastOpcodeID = op_end;
682 }
683
684 void ALWAYS_INLINE BytecodeGenerator::rewindUnaryOp()
685 {
686     ASSERT(instructions().size() >= 3);
687     instructions().shrink(instructions().size() - 3);
688     m_lastOpcodeID = op_end;
689 }
690
691 PassRefPtr<Label> BytecodeGenerator::emitJump(Label* target)
692 {
693     size_t begin = instructions().size();
694     emitOpcode(op_jmp);
695     instructions().append(target->bind(begin, instructions().size()));
696     return target;
697 }
698
699 PassRefPtr<Label> BytecodeGenerator::emitJumpIfTrue(RegisterID* cond, Label* target)
700 {
701     if (m_lastOpcodeID == op_less) {
702         int dstIndex;
703         int src1Index;
704         int src2Index;
705
706         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
707
708         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
709             rewindBinaryOp();
710
711             size_t begin = instructions().size();
712             emitOpcode(op_jless);
713             instructions().append(src1Index);
714             instructions().append(src2Index);
715             instructions().append(target->bind(begin, instructions().size()));
716             return target;
717         }
718     } else if (m_lastOpcodeID == op_lesseq) {
719         int dstIndex;
720         int src1Index;
721         int src2Index;
722
723         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
724
725         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
726             rewindBinaryOp();
727
728             size_t begin = instructions().size();
729             emitOpcode(op_jlesseq);
730             instructions().append(src1Index);
731             instructions().append(src2Index);
732             instructions().append(target->bind(begin, instructions().size()));
733             return target;
734         }
735     } else if (m_lastOpcodeID == op_greater) {
736         int dstIndex;
737         int src1Index;
738         int src2Index;
739
740         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
741
742         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
743             rewindBinaryOp();
744
745             size_t begin = instructions().size();
746             emitOpcode(op_jgreater);
747             instructions().append(src1Index);
748             instructions().append(src2Index);
749             instructions().append(target->bind(begin, instructions().size()));
750             return target;
751         }
752     } else if (m_lastOpcodeID == op_greatereq) {
753         int dstIndex;
754         int src1Index;
755         int src2Index;
756
757         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
758
759         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
760             rewindBinaryOp();
761
762             size_t begin = instructions().size();
763             emitOpcode(op_jgreatereq);
764             instructions().append(src1Index);
765             instructions().append(src2Index);
766             instructions().append(target->bind(begin, instructions().size()));
767             return target;
768         }
769     } else if (m_lastOpcodeID == op_eq_null && target->isForward()) {
770         int dstIndex;
771         int srcIndex;
772
773         retrieveLastUnaryOp(dstIndex, srcIndex);
774
775         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
776             rewindUnaryOp();
777
778             size_t begin = instructions().size();
779             emitOpcode(op_jeq_null);
780             instructions().append(srcIndex);
781             instructions().append(target->bind(begin, instructions().size()));
782             return target;
783         }
784     } else if (m_lastOpcodeID == op_neq_null && target->isForward()) {
785         int dstIndex;
786         int srcIndex;
787
788         retrieveLastUnaryOp(dstIndex, srcIndex);
789
790         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
791             rewindUnaryOp();
792
793             size_t begin = instructions().size();
794             emitOpcode(op_jneq_null);
795             instructions().append(srcIndex);
796             instructions().append(target->bind(begin, instructions().size()));
797             return target;
798         }
799     }
800
801     size_t begin = instructions().size();
802
803     emitOpcode(op_jtrue);
804     instructions().append(cond->index());
805     instructions().append(target->bind(begin, instructions().size()));
806     return target;
807 }
808
809 PassRefPtr<Label> BytecodeGenerator::emitJumpIfFalse(RegisterID* cond, Label* target)
810 {
811     if (m_lastOpcodeID == op_less && target->isForward()) {
812         int dstIndex;
813         int src1Index;
814         int src2Index;
815
816         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
817
818         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
819             rewindBinaryOp();
820
821             size_t begin = instructions().size();
822             emitOpcode(op_jnless);
823             instructions().append(src1Index);
824             instructions().append(src2Index);
825             instructions().append(target->bind(begin, instructions().size()));
826             return target;
827         }
828     } else if (m_lastOpcodeID == op_lesseq && target->isForward()) {
829         int dstIndex;
830         int src1Index;
831         int src2Index;
832
833         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
834
835         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
836             rewindBinaryOp();
837
838             size_t begin = instructions().size();
839             emitOpcode(op_jnlesseq);
840             instructions().append(src1Index);
841             instructions().append(src2Index);
842             instructions().append(target->bind(begin, instructions().size()));
843             return target;
844         }
845     } else if (m_lastOpcodeID == op_greater && target->isForward()) {
846         int dstIndex;
847         int src1Index;
848         int src2Index;
849
850         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
851
852         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
853             rewindBinaryOp();
854
855             size_t begin = instructions().size();
856             emitOpcode(op_jngreater);
857             instructions().append(src1Index);
858             instructions().append(src2Index);
859             instructions().append(target->bind(begin, instructions().size()));
860             return target;
861         }
862     } else if (m_lastOpcodeID == op_greatereq && target->isForward()) {
863         int dstIndex;
864         int src1Index;
865         int src2Index;
866
867         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
868
869         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
870             rewindBinaryOp();
871
872             size_t begin = instructions().size();
873             emitOpcode(op_jngreatereq);
874             instructions().append(src1Index);
875             instructions().append(src2Index);
876             instructions().append(target->bind(begin, instructions().size()));
877             return target;
878         }
879     } else if (m_lastOpcodeID == op_not) {
880         int dstIndex;
881         int srcIndex;
882
883         retrieveLastUnaryOp(dstIndex, srcIndex);
884
885         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
886             rewindUnaryOp();
887
888             size_t begin = instructions().size();
889             emitOpcode(op_jtrue);
890             instructions().append(srcIndex);
891             instructions().append(target->bind(begin, instructions().size()));
892             return target;
893         }
894     } else if (m_lastOpcodeID == op_eq_null && target->isForward()) {
895         int dstIndex;
896         int srcIndex;
897
898         retrieveLastUnaryOp(dstIndex, srcIndex);
899
900         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
901             rewindUnaryOp();
902
903             size_t begin = instructions().size();
904             emitOpcode(op_jneq_null);
905             instructions().append(srcIndex);
906             instructions().append(target->bind(begin, instructions().size()));
907             return target;
908         }
909     } else if (m_lastOpcodeID == op_neq_null && target->isForward()) {
910         int dstIndex;
911         int srcIndex;
912
913         retrieveLastUnaryOp(dstIndex, srcIndex);
914
915         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
916             rewindUnaryOp();
917
918             size_t begin = instructions().size();
919             emitOpcode(op_jeq_null);
920             instructions().append(srcIndex);
921             instructions().append(target->bind(begin, instructions().size()));
922             return target;
923         }
924     }
925
926     size_t begin = instructions().size();
927     emitOpcode(op_jfalse);
928     instructions().append(cond->index());
929     instructions().append(target->bind(begin, instructions().size()));
930     return target;
931 }
932
933 PassRefPtr<Label> BytecodeGenerator::emitJumpIfNotFunctionCall(RegisterID* cond, Label* target)
934 {
935     size_t begin = instructions().size();
936
937     emitOpcode(op_jneq_ptr);
938     instructions().append(cond->index());
939     instructions().append(Special::CallFunction);
940     instructions().append(target->bind(begin, instructions().size()));
941     return target;
942 }
943
944 PassRefPtr<Label> BytecodeGenerator::emitJumpIfNotFunctionApply(RegisterID* cond, Label* target)
945 {
946     size_t begin = instructions().size();
947
948     emitOpcode(op_jneq_ptr);
949     instructions().append(cond->index());
950     instructions().append(Special::ApplyFunction);
951     instructions().append(target->bind(begin, instructions().size()));
952     return target;
953 }
954
955 bool BytecodeGenerator::hasConstant(const Identifier& ident) const
956 {
957     StringImpl* rep = ident.impl();
958     return m_identifierMap.contains(rep);
959 }
960
961 unsigned BytecodeGenerator::addConstant(const Identifier& ident)
962 {
963     StringImpl* rep = ident.impl();
964     IdentifierMap::AddResult result = m_identifierMap.add(rep, m_codeBlock->numberOfIdentifiers());
965     if (result.isNewEntry)
966         m_codeBlock->addIdentifier(ident);
967
968     return result.iterator->value;
969 }
970
971 // We can't hash JSValue(), so we use a dedicated data member to cache it.
972 RegisterID* BytecodeGenerator::addConstantEmptyValue()
973 {
974     if (!m_emptyValueRegister) {
975         int index = m_nextConstantOffset;
976         m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
977         ++m_nextConstantOffset;
978         m_codeBlock->addConstant(JSValue());
979         m_emptyValueRegister = &m_constantPoolRegisters[index];
980     }
981
982     return m_emptyValueRegister;
983 }
984
985 RegisterID* BytecodeGenerator::addConstantValue(JSValue v, SourceCodeRepresentation sourceCodeRepresentation)
986 {
987     if (!v)
988         return addConstantEmptyValue();
989
990     int index = m_nextConstantOffset;
991
992     EncodedJSValueWithRepresentation valueMapKey { JSValue::encode(v), sourceCodeRepresentation };
993     JSValueMap::AddResult result = m_jsValueMap.add(valueMapKey, m_nextConstantOffset);
994     if (result.isNewEntry) {
995         m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
996         ++m_nextConstantOffset;
997         m_codeBlock->addConstant(v, sourceCodeRepresentation);
998     } else
999         index = result.iterator->value;
1000     return &m_constantPoolRegisters[index];
1001 }
1002
1003 RegisterID* BytecodeGenerator::emitMoveLinkTimeConstant(RegisterID* dst, LinkTimeConstant type)
1004 {
1005     unsigned constantIndex = static_cast<unsigned>(type);
1006     if (!m_linkTimeConstantRegisters[constantIndex]) {
1007         int index = m_nextConstantOffset;
1008         m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
1009         ++m_nextConstantOffset;
1010         m_codeBlock->addConstant(type);
1011         m_linkTimeConstantRegisters[constantIndex] = &m_constantPoolRegisters[index];
1012     }
1013
1014     emitOpcode(op_mov);
1015     instructions().append(dst->index());
1016     instructions().append(m_linkTimeConstantRegisters[constantIndex]->index());
1017
1018     return dst;
1019 }
1020
1021 unsigned BytecodeGenerator::addRegExp(RegExp* r)
1022 {
1023     return m_codeBlock->addRegExp(r);
1024 }
1025
1026 RegisterID* BytecodeGenerator::emitMoveEmptyValue(RegisterID* dst)
1027 {
1028     RefPtr<RegisterID> emptyValue = addConstantEmptyValue();
1029
1030     emitOpcode(op_mov);
1031     instructions().append(dst->index());
1032     instructions().append(emptyValue->index());
1033     return dst;
1034 }
1035
1036 RegisterID* BytecodeGenerator::emitMove(RegisterID* dst, RegisterID* src)
1037 {
1038     ASSERT(src != m_emptyValueRegister);
1039
1040     m_staticPropertyAnalyzer.mov(dst->index(), src->index());
1041     emitOpcode(op_mov);
1042     instructions().append(dst->index());
1043     instructions().append(src->index());
1044
1045     if (!dst->isTemporary() && vm()->typeProfiler())
1046         emitProfileType(dst, ProfileTypeBytecodeHasGlobalID, nullptr);
1047
1048     return dst;
1049 }
1050
1051 RegisterID* BytecodeGenerator::emitUnaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src)
1052 {
1053     emitOpcode(opcodeID);
1054     instructions().append(dst->index());
1055     instructions().append(src->index());
1056     return dst;
1057 }
1058
1059 RegisterID* BytecodeGenerator::emitInc(RegisterID* srcDst)
1060 {
1061     emitOpcode(op_inc);
1062     instructions().append(srcDst->index());
1063     return srcDst;
1064 }
1065
1066 RegisterID* BytecodeGenerator::emitDec(RegisterID* srcDst)
1067 {
1068     emitOpcode(op_dec);
1069     instructions().append(srcDst->index());
1070     return srcDst;
1071 }
1072
1073 RegisterID* BytecodeGenerator::emitBinaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2, OperandTypes types)
1074 {
1075     emitOpcode(opcodeID);
1076     instructions().append(dst->index());
1077     instructions().append(src1->index());
1078     instructions().append(src2->index());
1079
1080     if (opcodeID == op_bitor || opcodeID == op_bitand || opcodeID == op_bitxor ||
1081         opcodeID == op_add || opcodeID == op_mul || opcodeID == op_sub || opcodeID == op_div)
1082         instructions().append(types.toInt());
1083
1084     return dst;
1085 }
1086
1087 RegisterID* BytecodeGenerator::emitEqualityOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2)
1088 {
1089     if (m_lastOpcodeID == op_typeof) {
1090         int dstIndex;
1091         int srcIndex;
1092
1093         retrieveLastUnaryOp(dstIndex, srcIndex);
1094
1095         if (src1->index() == dstIndex
1096             && src1->isTemporary()
1097             && m_codeBlock->isConstantRegisterIndex(src2->index())
1098             && m_codeBlock->constantRegister(src2->index()).get().isString()) {
1099             const String& value = asString(m_codeBlock->constantRegister(src2->index()).get())->tryGetValue();
1100             if (value == "undefined") {
1101                 rewindUnaryOp();
1102                 emitOpcode(op_is_undefined);
1103                 instructions().append(dst->index());
1104                 instructions().append(srcIndex);
1105                 return dst;
1106             }
1107             if (value == "boolean") {
1108                 rewindUnaryOp();
1109                 emitOpcode(op_is_boolean);
1110                 instructions().append(dst->index());
1111                 instructions().append(srcIndex);
1112                 return dst;
1113             }
1114             if (value == "number") {
1115                 rewindUnaryOp();
1116                 emitOpcode(op_is_number);
1117                 instructions().append(dst->index());
1118                 instructions().append(srcIndex);
1119                 return dst;
1120             }
1121             if (value == "string") {
1122                 rewindUnaryOp();
1123                 emitOpcode(op_is_string);
1124                 instructions().append(dst->index());
1125                 instructions().append(srcIndex);
1126                 return dst;
1127             }
1128             if (value == "object") {
1129                 rewindUnaryOp();
1130                 emitOpcode(op_is_object_or_null);
1131                 instructions().append(dst->index());
1132                 instructions().append(srcIndex);
1133                 return dst;
1134             }
1135             if (value == "function") {
1136                 rewindUnaryOp();
1137                 emitOpcode(op_is_function);
1138                 instructions().append(dst->index());
1139                 instructions().append(srcIndex);
1140                 return dst;
1141             }
1142         }
1143     }
1144
1145     emitOpcode(opcodeID);
1146     instructions().append(dst->index());
1147     instructions().append(src1->index());
1148     instructions().append(src2->index());
1149     return dst;
1150 }
1151
1152 void BytecodeGenerator::emitTypeProfilerExpressionInfo(const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1153 {
1154     unsigned start = startDivot.offset; // Ranges are inclusive of their endpoints, AND 0 indexed.
1155     unsigned end = endDivot.offset - 1; // End Ranges already go one past the inclusive range, so subtract 1.
1156     unsigned instructionOffset = instructions().size() - 1;
1157     m_codeBlock->addTypeProfilerExpressionInfo(instructionOffset, start, end);
1158 }
1159
1160 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag flag, const Identifier* identifier)
1161 {
1162     if (flag == ProfileTypeBytecodeGetFromScope || flag == ProfileTypeBytecodePutToScope)
1163         RELEASE_ASSERT(identifier);
1164
1165     // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType?
1166     emitOpcode(op_profile_type);
1167     instructions().append(registerToProfile->index());
1168     instructions().append(0);
1169     instructions().append(flag);
1170     instructions().append(identifier ? addConstant(*identifier) : 0);
1171     instructions().append(resolveType());
1172 }
1173
1174 void BytecodeGenerator::emitProfileControlFlow(int textOffset)
1175 {
1176     if (vm()->controlFlowProfiler()) {
1177         RELEASE_ASSERT(textOffset >= 0);
1178         size_t bytecodeOffset = instructions().size();
1179         m_codeBlock->addOpProfileControlFlowBytecodeOffset(bytecodeOffset);
1180
1181         emitOpcode(op_profile_control_flow);
1182         instructions().append(textOffset);
1183     }
1184 }
1185
1186 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, bool b)
1187 {
1188     return emitLoad(dst, jsBoolean(b));
1189 }
1190
1191 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, const Identifier& identifier)
1192 {
1193     JSString*& stringInMap = m_stringMap.add(identifier.impl(), nullptr).iterator->value;
1194     if (!stringInMap)
1195         stringInMap = jsOwnedString(vm(), identifier.string());
1196     return emitLoad(dst, JSValue(stringInMap));
1197 }
1198
1199 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, JSValue v, SourceCodeRepresentation sourceCodeRepresentation)
1200 {
1201     RegisterID* constantID = addConstantValue(v, sourceCodeRepresentation);
1202     if (dst)
1203         return emitMove(dst, constantID);
1204     return constantID;
1205 }
1206
1207 RegisterID* BytecodeGenerator::emitLoadGlobalObject(RegisterID* dst)
1208 {
1209     if (!m_globalObjectRegister) {
1210         int index = m_nextConstantOffset;
1211         m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
1212         ++m_nextConstantOffset;
1213         m_codeBlock->addConstant(JSValue());
1214         m_globalObjectRegister = &m_constantPoolRegisters[index];
1215         m_codeBlock->setGlobalObjectRegister(VirtualRegister(index));
1216     }
1217     if (dst)
1218         emitMove(dst, m_globalObjectRegister);
1219     return m_globalObjectRegister;
1220 }
1221
1222 Variable BytecodeGenerator::variable(const Identifier& property)
1223 {
1224     if (property == propertyNames().thisIdentifier) {
1225         return Variable(
1226             property, VarOffset(thisRegister()->virtualRegister()), thisRegister(),
1227             ReadOnly, Variable::SpecialVariable);
1228     }
1229     
1230     if (!shouldOptimizeLocals())
1231         return Variable(property);
1232     
1233     SymbolTableEntry entry = symbolTable().get(property.impl());
1234     if (entry.isNull())
1235         return Variable(property);
1236     
1237     if (entry.varOffset().isScope() && m_localScopeDepth) {
1238         // FIXME: We should be able to statically resolve through our local scopes.
1239         // https://bugs.webkit.org/show_bug.cgi?id=141885
1240         return Variable(property);
1241     }
1242     
1243     return variableForLocalEntry(property, entry);
1244 }
1245
1246 Variable BytecodeGenerator::variablePerSymbolTable(const Identifier& property)
1247 {
1248     SymbolTableEntry entry = symbolTable().get(property.impl());
1249     if (entry.isNull())
1250         return Variable(property);
1251     
1252     return variableForLocalEntry(property, entry);
1253 }
1254
1255 Variable BytecodeGenerator::variableForLocalEntry(
1256     const Identifier& property, const SymbolTableEntry& entry)
1257 {
1258     VarOffset offset = entry.varOffset();
1259     
1260     RegisterID* local;
1261     if (offset.isStack())
1262         local = &registerFor(offset.stackOffset());
1263     else
1264         local = nullptr;
1265     
1266     return Variable(property, offset, local, entry.getAttributes(), Variable::NormalVariable);
1267 }
1268
1269 void BytecodeGenerator::createVariable(
1270     const Identifier& property, VarKind varKind, ConstantMode constantMode,
1271     ExistingVariableMode existingVariableMode)
1272 {
1273     ASSERT(property != propertyNames().thisIdentifier);
1274     
1275     ConcurrentJITLocker locker(symbolTable().m_lock);
1276     SymbolTableEntry entry = symbolTable().get(locker, property.impl());
1277     
1278     if (!entry.isNull()) {
1279         if (existingVariableMode == IgnoreExisting)
1280             return;
1281         
1282         // Do some checks to ensure that the variable we're being asked to create is sufficiently
1283         // compatible with the one we have already created.
1284
1285         VarOffset offset = entry.varOffset();
1286         
1287         // We can't change our minds about whether it's captured.
1288         if (offset.kind() != varKind || constantMode != entry.constantMode()) {
1289             dataLog(
1290                 "Trying to add variable called ", property, " as ", varKind, "/", constantMode,
1291                 " but it was already added as ", offset, "/", entry.constantMode(), ".\n");
1292             RELEASE_ASSERT_NOT_REACHED();
1293         }
1294
1295         return;
1296     }
1297     
1298     VarOffset varOffset;
1299     if (varKind == VarKind::Scope)
1300         varOffset = VarOffset(symbolTable().takeNextScopeOffset(locker));
1301     else {
1302         ASSERT(varKind == VarKind::Stack);
1303         varOffset = VarOffset(virtualRegisterForLocal(m_calleeRegisters.size()));
1304     }
1305     SymbolTableEntry newEntry(varOffset, constantMode == IsConstant ? ReadOnly : 0);
1306     symbolTable().add(locker, property.impl(), newEntry);
1307     
1308     if (varKind == VarKind::Stack) {
1309         RegisterID* local = addVar();
1310         RELEASE_ASSERT(local->index() == varOffset.stackOffset().offset());
1311     }
1312 }
1313
1314 void BytecodeGenerator::emitCheckHasInstance(RegisterID* dst, RegisterID* value, RegisterID* base, Label* target)
1315 {
1316     size_t begin = instructions().size();
1317     emitOpcode(op_check_has_instance);
1318     instructions().append(dst->index());
1319     instructions().append(value->index());
1320     instructions().append(base->index());
1321     instructions().append(target->bind(begin, instructions().size()));
1322 }
1323
1324 // Indicates the least upper bound of resolve type based on local scope. The bytecode linker
1325 // will start with this ResolveType and compute the least upper bound including intercepting scopes.
1326 ResolveType BytecodeGenerator::resolveType()
1327 {
1328     if (m_localScopeDepth)
1329         return Dynamic;
1330     if (m_symbolTable && m_symbolTable->usesNonStrictEval())
1331         return GlobalPropertyWithVarInjectionChecks;
1332     return GlobalProperty;
1333 }
1334
1335 RegisterID* BytecodeGenerator::emitResolveScope(RegisterID* dst, const Variable& variable)
1336 {
1337     switch (variable.offset().kind()) {
1338     case VarKind::Stack:
1339         return nullptr;
1340         
1341     case VarKind::DirectArgument:
1342         return argumentsRegister();
1343         
1344     case VarKind::Scope:
1345         // This always refers to the activation that *we* allocated, and not the current scope that code
1346         // lives in. Note that this will change once we have proper support for block scoping. Once that
1347         // changes, it will be correct for this code to return scopeRegister(). The only reason why we
1348         // don't do that already is that m_lexicalEnvironment is required by ConstDeclNode. ConstDeclNode
1349         // requires weird things because it is a shameful pile of nonsense, but block scoping would make
1350         // that code sensible and obviate the need for us to do bad things.
1351         return m_lexicalEnvironmentRegister;
1352         
1353     case VarKind::Invalid:
1354         // Indicates non-local resolution.
1355         
1356         ASSERT(!m_symbolTable || !m_symbolTable->contains(variable.ident().impl()) || resolveType() == Dynamic);
1357         
1358         m_codeBlock->addPropertyAccessInstruction(instructions().size());
1359         
1360         // resolve_scope dst, id, ResolveType, depth
1361         emitOpcode(op_resolve_scope);
1362         dst = tempDestination(dst);
1363         instructions().append(kill(dst));
1364         instructions().append(scopeRegister()->index());
1365         instructions().append(addConstant(variable.ident()));
1366         instructions().append(resolveType());
1367         instructions().append(0);
1368         instructions().append(0);
1369         return dst;
1370     }
1371     
1372     RELEASE_ASSERT_NOT_REACHED();
1373     return nullptr;
1374 }
1375
1376 RegisterID* BytecodeGenerator::emitGetFromScope(RegisterID* dst, RegisterID* scope, const Variable& variable, ResolveMode resolveMode)
1377 {
1378     switch (variable.offset().kind()) {
1379     case VarKind::Stack:
1380         return emitMove(dst, variable.local());
1381         
1382     case VarKind::DirectArgument: {
1383         UnlinkedValueProfile profile = emitProfiledOpcode(op_get_from_arguments);
1384         instructions().append(kill(dst));
1385         instructions().append(scope->index());
1386         instructions().append(variable.offset().capturedArgumentsOffset().offset());
1387         instructions().append(profile);
1388         return dst;
1389     }
1390         
1391     case VarKind::Scope:
1392     case VarKind::Invalid: {
1393         m_codeBlock->addPropertyAccessInstruction(instructions().size());
1394         
1395         // get_from_scope dst, scope, id, ResolveModeAndType, Structure, Operand
1396         UnlinkedValueProfile profile = emitProfiledOpcode(op_get_from_scope);
1397         instructions().append(kill(dst));
1398         instructions().append(scope->index());
1399         instructions().append(addConstant(variable.ident()));
1400         instructions().append(ResolveModeAndType(resolveMode, variable.offset().isScope() ? LocalClosureVar : resolveType()).operand());
1401         instructions().append(0);
1402         instructions().append(variable.offset().isScope() ? variable.offset().scopeOffset().offset() : 0);
1403         instructions().append(profile);
1404         return dst;
1405     } }
1406     
1407     RELEASE_ASSERT_NOT_REACHED();
1408 }
1409
1410 RegisterID* BytecodeGenerator::emitPutToScope(RegisterID* scope, const Variable& variable, RegisterID* value, ResolveMode resolveMode)
1411 {
1412     switch (variable.offset().kind()) {
1413     case VarKind::Stack:
1414         emitMove(variable.local(), value);
1415         return value;
1416         
1417     case VarKind::DirectArgument:
1418         emitOpcode(op_put_to_arguments);
1419         instructions().append(scope->index());
1420         instructions().append(variable.offset().capturedArgumentsOffset().offset());
1421         instructions().append(value->index());
1422         return value;
1423         
1424     case VarKind::Scope:
1425     case VarKind::Invalid: {
1426         m_codeBlock->addPropertyAccessInstruction(instructions().size());
1427         
1428         // put_to_scope scope, id, value, ResolveModeAndType, Structure, Operand
1429         emitOpcode(op_put_to_scope);
1430         instructions().append(scope->index());
1431         instructions().append(addConstant(variable.ident()));
1432         instructions().append(value->index());
1433         ScopeOffset offset;
1434         if (variable.offset().isScope()) {
1435             offset = variable.offset().scopeOffset();
1436             instructions().append(ResolveModeAndType(resolveMode, LocalClosureVar).operand());
1437         } else {
1438             ASSERT(resolveType() != LocalClosureVar);
1439             instructions().append(ResolveModeAndType(resolveMode, resolveType()).operand());
1440         }
1441         instructions().append(0);
1442         instructions().append(!!offset ? offset.offset() : 0);
1443         return value;
1444     } }
1445     
1446     RELEASE_ASSERT_NOT_REACHED();
1447 }
1448
1449 RegisterID* BytecodeGenerator::initializeVariable(const Variable& variable, RegisterID* value)
1450 {
1451     RegisterID* scope;
1452     switch (variable.offset().kind()) {
1453     case VarKind::Stack:
1454         scope = nullptr;
1455         break;
1456         
1457     case VarKind::DirectArgument:
1458         scope = argumentsRegister();
1459         break;
1460         
1461     case VarKind::Scope:
1462         scope = scopeRegister();
1463         break;
1464         
1465     default:
1466         RELEASE_ASSERT_NOT_REACHED();
1467         scope = nullptr;
1468         break;
1469     }
1470
1471     return emitPutToScope(scope, variable, value, ThrowIfNotFound);
1472 }
1473
1474 RegisterID* BytecodeGenerator::emitInstanceOf(RegisterID* dst, RegisterID* value, RegisterID* basePrototype)
1475 {
1476     emitOpcode(op_instanceof);
1477     instructions().append(dst->index());
1478     instructions().append(value->index());
1479     instructions().append(basePrototype->index());
1480     return dst;
1481 }
1482
1483 RegisterID* BytecodeGenerator::emitInitGlobalConst(const Identifier& identifier, RegisterID* value)
1484 {
1485     ASSERT(m_codeType == GlobalCode);
1486     emitOpcode(op_init_global_const_nop);
1487     instructions().append(0);
1488     instructions().append(value->index());
1489     instructions().append(0);
1490     instructions().append(addConstant(identifier));
1491     return value;
1492 }
1493
1494 RegisterID* BytecodeGenerator::emitGetById(RegisterID* dst, RegisterID* base, const Identifier& property)
1495 {
1496     m_codeBlock->addPropertyAccessInstruction(instructions().size());
1497
1498     UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_id);
1499     instructions().append(kill(dst));
1500     instructions().append(base->index());
1501     instructions().append(addConstant(property));
1502     instructions().append(0);
1503     instructions().append(0);
1504     instructions().append(0);
1505     instructions().append(0);
1506     instructions().append(profile);
1507     return dst;
1508 }
1509
1510 RegisterID* BytecodeGenerator::emitPutById(RegisterID* base, const Identifier& property, RegisterID* value)
1511 {
1512     unsigned propertyIndex = addConstant(property);
1513
1514     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
1515
1516     m_codeBlock->addPropertyAccessInstruction(instructions().size());
1517
1518     emitOpcode(op_put_by_id);
1519     instructions().append(base->index());
1520     instructions().append(propertyIndex);
1521     instructions().append(value->index());
1522     instructions().append(0);
1523     instructions().append(0);
1524     instructions().append(0);
1525     instructions().append(0);
1526     instructions().append(0);
1527
1528     return value;
1529 }
1530
1531 RegisterID* BytecodeGenerator::emitDirectPutById(RegisterID* base, const Identifier& property, RegisterID* value, PropertyNode::PutType putType)
1532 {
1533     unsigned propertyIndex = addConstant(property);
1534
1535     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
1536
1537     m_codeBlock->addPropertyAccessInstruction(instructions().size());
1538     
1539     emitOpcode(op_put_by_id);
1540     instructions().append(base->index());
1541     instructions().append(propertyIndex);
1542     instructions().append(value->index());
1543     instructions().append(0);
1544     instructions().append(0);
1545     instructions().append(0);
1546     instructions().append(0);
1547     instructions().append(putType == PropertyNode::KnownDirect || (property != m_vm->propertyNames->underscoreProto && !parseIndex(property)));
1548     return value;
1549 }
1550
1551 void BytecodeGenerator::emitPutGetterSetter(RegisterID* base, const Identifier& property, RegisterID* getter, RegisterID* setter)
1552 {
1553     unsigned propertyIndex = addConstant(property);
1554
1555     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
1556
1557     emitOpcode(op_put_getter_setter);
1558     instructions().append(base->index());
1559     instructions().append(propertyIndex);
1560     instructions().append(getter->index());
1561     instructions().append(setter->index());
1562 }
1563
1564 RegisterID* BytecodeGenerator::emitDeleteById(RegisterID* dst, RegisterID* base, const Identifier& property)
1565 {
1566     emitOpcode(op_del_by_id);
1567     instructions().append(dst->index());
1568     instructions().append(base->index());
1569     instructions().append(addConstant(property));
1570     return dst;
1571 }
1572
1573 RegisterID* BytecodeGenerator::emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* property)
1574 {
1575     for (size_t i = m_forInContextStack.size(); i > 0; i--) {
1576         ForInContext* context = m_forInContextStack[i - 1].get();
1577         if (context->local() != property)
1578             continue;
1579
1580         if (!context->isValid())
1581             break;
1582
1583         if (context->type() == ForInContext::IndexedForInContextType) {
1584             property = static_cast<IndexedForInContext*>(context)->index();
1585             break;
1586         }
1587
1588         ASSERT(context->type() == ForInContext::StructureForInContextType);
1589         StructureForInContext* structureContext = static_cast<StructureForInContext*>(context);
1590         UnlinkedValueProfile profile = emitProfiledOpcode(op_get_direct_pname);
1591         instructions().append(kill(dst));
1592         instructions().append(base->index());
1593         instructions().append(property->index());
1594         instructions().append(structureContext->index()->index());
1595         instructions().append(structureContext->enumerator()->index());
1596         instructions().append(profile);
1597         return dst;
1598     }
1599
1600     UnlinkedArrayProfile arrayProfile = newArrayProfile();
1601     UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_val);
1602     instructions().append(kill(dst));
1603     instructions().append(base->index());
1604     instructions().append(property->index());
1605     instructions().append(arrayProfile);
1606     instructions().append(profile);
1607     return dst;
1608 }
1609
1610 RegisterID* BytecodeGenerator::emitPutByVal(RegisterID* base, RegisterID* property, RegisterID* value)
1611 {
1612     UnlinkedArrayProfile arrayProfile = newArrayProfile();
1613     emitOpcode(op_put_by_val);
1614     instructions().append(base->index());
1615     instructions().append(property->index());
1616     instructions().append(value->index());
1617     instructions().append(arrayProfile);
1618
1619     return value;
1620 }
1621
1622 RegisterID* BytecodeGenerator::emitDirectPutByVal(RegisterID* base, RegisterID* property, RegisterID* value)
1623 {
1624     UnlinkedArrayProfile arrayProfile = newArrayProfile();
1625     emitOpcode(op_put_by_val_direct);
1626     instructions().append(base->index());
1627     instructions().append(property->index());
1628     instructions().append(value->index());
1629     instructions().append(arrayProfile);
1630     return value;
1631 }
1632
1633 RegisterID* BytecodeGenerator::emitDeleteByVal(RegisterID* dst, RegisterID* base, RegisterID* property)
1634 {
1635     emitOpcode(op_del_by_val);
1636     instructions().append(dst->index());
1637     instructions().append(base->index());
1638     instructions().append(property->index());
1639     return dst;
1640 }
1641
1642 RegisterID* BytecodeGenerator::emitPutByIndex(RegisterID* base, unsigned index, RegisterID* value)
1643 {
1644     emitOpcode(op_put_by_index);
1645     instructions().append(base->index());
1646     instructions().append(index);
1647     instructions().append(value->index());
1648     return value;
1649 }
1650
1651 RegisterID* BytecodeGenerator::emitCreateThis(RegisterID* dst)
1652 {
1653     size_t begin = instructions().size();
1654     m_staticPropertyAnalyzer.createThis(m_thisRegister.index(), begin + 3);
1655
1656     m_codeBlock->addPropertyAccessInstruction(instructions().size());
1657     emitOpcode(op_create_this); 
1658     instructions().append(m_thisRegister.index()); 
1659     instructions().append(m_thisRegister.index()); 
1660     instructions().append(0);
1661     instructions().append(0);
1662     return dst;
1663 }
1664
1665 void BytecodeGenerator::emitTDZCheck(RegisterID* target)
1666 {
1667     emitOpcode(op_check_tdz);
1668     instructions().append(target->index());
1669 }
1670
1671 RegisterID* BytecodeGenerator::emitNewObject(RegisterID* dst)
1672 {
1673     size_t begin = instructions().size();
1674     m_staticPropertyAnalyzer.newObject(dst->index(), begin + 2);
1675
1676     emitOpcode(op_new_object);
1677     instructions().append(dst->index());
1678     instructions().append(0);
1679     instructions().append(newObjectAllocationProfile());
1680     return dst;
1681 }
1682
1683 unsigned BytecodeGenerator::addConstantBuffer(unsigned length)
1684 {
1685     return m_codeBlock->addConstantBuffer(length);
1686 }
1687
1688 JSString* BytecodeGenerator::addStringConstant(const Identifier& identifier)
1689 {
1690     JSString*& stringInMap = m_stringMap.add(identifier.impl(), nullptr).iterator->value;
1691     if (!stringInMap) {
1692         stringInMap = jsString(vm(), identifier.string());
1693         addConstantValue(stringInMap);
1694     }
1695     return stringInMap;
1696 }
1697
1698 RegisterID* BytecodeGenerator::emitNewArray(RegisterID* dst, ElementNode* elements, unsigned length)
1699 {
1700 #if !ASSERT_DISABLED
1701     unsigned checkLength = 0;
1702 #endif
1703     bool hadVariableExpression = false;
1704     if (length) {
1705         for (ElementNode* n = elements; n; n = n->next()) {
1706             if (!n->value()->isConstant()) {
1707                 hadVariableExpression = true;
1708                 break;
1709             }
1710             if (n->elision())
1711                 break;
1712 #if !ASSERT_DISABLED
1713             checkLength++;
1714 #endif
1715         }
1716         if (!hadVariableExpression) {
1717             ASSERT(length == checkLength);
1718             unsigned constantBufferIndex = addConstantBuffer(length);
1719             JSValue* constantBuffer = m_codeBlock->constantBuffer(constantBufferIndex).data();
1720             unsigned index = 0;
1721             for (ElementNode* n = elements; index < length; n = n->next()) {
1722                 ASSERT(n->value()->isConstant());
1723                 constantBuffer[index++] = static_cast<ConstantNode*>(n->value())->jsValue(*this);
1724             }
1725             emitOpcode(op_new_array_buffer);
1726             instructions().append(dst->index());
1727             instructions().append(constantBufferIndex);
1728             instructions().append(length);
1729             instructions().append(newArrayAllocationProfile());
1730             return dst;
1731         }
1732     }
1733
1734     Vector<RefPtr<RegisterID>, 16, UnsafeVectorOverflow> argv;
1735     for (ElementNode* n = elements; n; n = n->next()) {
1736         if (!length)
1737             break;
1738         length--;
1739         ASSERT(!n->value()->isSpreadExpression());
1740         argv.append(newTemporary());
1741         // op_new_array requires the initial values to be a sequential range of registers
1742         ASSERT(argv.size() == 1 || argv[argv.size() - 1]->index() == argv[argv.size() - 2]->index() - 1);
1743         emitNode(argv.last().get(), n->value());
1744     }
1745     ASSERT(!length);
1746     emitOpcode(op_new_array);
1747     instructions().append(dst->index());
1748     instructions().append(argv.size() ? argv[0]->index() : 0); // argv
1749     instructions().append(argv.size()); // argc
1750     instructions().append(newArrayAllocationProfile());
1751     return dst;
1752 }
1753
1754 RegisterID* BytecodeGenerator::emitNewFunction(RegisterID* dst, FunctionBodyNode* function)
1755 {
1756     return emitNewFunctionInternal(dst, m_codeBlock->addFunctionDecl(makeFunction(function)));
1757 }
1758
1759 RegisterID* BytecodeGenerator::emitNewFunctionInternal(RegisterID* dst, unsigned index)
1760 {
1761     emitOpcode(op_new_func);
1762     instructions().append(dst->index());
1763     instructions().append(scopeRegister()->index());
1764     instructions().append(index);
1765     return dst;
1766 }
1767
1768 RegisterID* BytecodeGenerator::emitNewRegExp(RegisterID* dst, RegExp* regExp)
1769 {
1770     emitOpcode(op_new_regexp);
1771     instructions().append(dst->index());
1772     instructions().append(addRegExp(regExp));
1773     return dst;
1774 }
1775
1776 RegisterID* BytecodeGenerator::emitNewFunctionExpression(RegisterID* r0, FuncExprNode* n)
1777 {
1778     FunctionBodyNode* function = n->body();
1779     unsigned index = m_codeBlock->addFunctionExpr(makeFunction(function));
1780
1781     emitOpcode(op_new_func_exp);
1782     instructions().append(r0->index());
1783     instructions().append(scopeRegister()->index());
1784     instructions().append(index);
1785     return r0;
1786 }
1787
1788 RegisterID* BytecodeGenerator::emitNewDefaultConstructor(RegisterID* dst, ConstructorKind constructorKind, const Identifier& name)
1789 {
1790     UnlinkedFunctionExecutable* executable = m_vm->builtinExecutables()->createDefaultConstructor(constructorKind, name);
1791
1792     unsigned index = m_codeBlock->addFunctionExpr(executable);
1793
1794     emitOpcode(op_new_func_exp);
1795     instructions().append(dst->index());
1796     instructions().append(scopeRegister()->index());
1797     instructions().append(index);
1798     return dst;
1799 }
1800
1801 RegisterID* BytecodeGenerator::emitCall(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd)
1802 {
1803     return emitCall(op_call, dst, func, expectedFunction, callArguments, divot, divotStart, divotEnd);
1804 }
1805
1806 RegisterID* BytecodeGenerator::emitCallEval(RegisterID* dst, RegisterID* func, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd)
1807 {
1808     return emitCall(op_call_eval, dst, func, NoExpectedFunction, callArguments, divot, divotStart, divotEnd);
1809 }
1810
1811 ExpectedFunction BytecodeGenerator::expectedFunctionForIdentifier(const Identifier& identifier)
1812 {
1813     if (identifier == m_vm->propertyNames->Object)
1814         return ExpectObjectConstructor;
1815     if (identifier == m_vm->propertyNames->Array)
1816         return ExpectArrayConstructor;
1817     return NoExpectedFunction;
1818 }
1819
1820 ExpectedFunction BytecodeGenerator::emitExpectedFunctionSnippet(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, Label* done)
1821 {
1822     RefPtr<Label> realCall = newLabel();
1823     switch (expectedFunction) {
1824     case ExpectObjectConstructor: {
1825         // If the number of arguments is non-zero, then we can't do anything interesting.
1826         if (callArguments.argumentCountIncludingThis() >= 2)
1827             return NoExpectedFunction;
1828         
1829         size_t begin = instructions().size();
1830         emitOpcode(op_jneq_ptr);
1831         instructions().append(func->index());
1832         instructions().append(Special::ObjectConstructor);
1833         instructions().append(realCall->bind(begin, instructions().size()));
1834         
1835         if (dst != ignoredResult())
1836             emitNewObject(dst);
1837         break;
1838     }
1839         
1840     case ExpectArrayConstructor: {
1841         // If you're doing anything other than "new Array()" or "new Array(foo)" then we
1842         // don't do inline it, for now. The only reason is that call arguments are in
1843         // the opposite order of what op_new_array expects, so we'd either need to change
1844         // how op_new_array works or we'd need an op_new_array_reverse. Neither of these
1845         // things sounds like it's worth it.
1846         if (callArguments.argumentCountIncludingThis() > 2)
1847             return NoExpectedFunction;
1848         
1849         size_t begin = instructions().size();
1850         emitOpcode(op_jneq_ptr);
1851         instructions().append(func->index());
1852         instructions().append(Special::ArrayConstructor);
1853         instructions().append(realCall->bind(begin, instructions().size()));
1854         
1855         if (dst != ignoredResult()) {
1856             if (callArguments.argumentCountIncludingThis() == 2) {
1857                 emitOpcode(op_new_array_with_size);
1858                 instructions().append(dst->index());
1859                 instructions().append(callArguments.argumentRegister(0)->index());
1860                 instructions().append(newArrayAllocationProfile());
1861             } else {
1862                 ASSERT(callArguments.argumentCountIncludingThis() == 1);
1863                 emitOpcode(op_new_array);
1864                 instructions().append(dst->index());
1865                 instructions().append(0);
1866                 instructions().append(0);
1867                 instructions().append(newArrayAllocationProfile());
1868             }
1869         }
1870         break;
1871     }
1872         
1873     default:
1874         ASSERT(expectedFunction == NoExpectedFunction);
1875         return NoExpectedFunction;
1876     }
1877     
1878     size_t begin = instructions().size();
1879     emitOpcode(op_jmp);
1880     instructions().append(done->bind(begin, instructions().size()));
1881     emitLabel(realCall.get());
1882     
1883     return expectedFunction;
1884 }
1885
1886 RegisterID* BytecodeGenerator::emitCall(OpcodeID opcodeID, RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd)
1887 {
1888     ASSERT(opcodeID == op_call || opcodeID == op_call_eval);
1889     ASSERT(func->refCount());
1890
1891     if (m_shouldEmitProfileHooks)
1892         emitMove(callArguments.profileHookRegister(), func);
1893
1894     // Generate code for arguments.
1895     unsigned argument = 0;
1896     if (callArguments.argumentsNode()) {
1897         ArgumentListNode* n = callArguments.argumentsNode()->m_listNode;
1898         if (n && n->m_expr->isSpreadExpression()) {
1899             RELEASE_ASSERT(!n->m_next);
1900             auto expression = static_cast<SpreadExpressionNode*>(n->m_expr)->expression();
1901             RefPtr<RegisterID> argumentRegister;
1902             argumentRegister = expression->emitBytecode(*this, callArguments.argumentRegister(0));
1903             RefPtr<RegisterID> thisRegister = emitMove(newTemporary(), callArguments.thisRegister());
1904             return emitCallVarargs(dst, func, callArguments.thisRegister(), argumentRegister.get(), newTemporary(), 0, callArguments.profileHookRegister(), divot, divotStart, divotEnd);
1905         }
1906         for (; n; n = n->m_next)
1907             emitNode(callArguments.argumentRegister(argument++), n);
1908     }
1909     
1910     // Reserve space for call frame.
1911     Vector<RefPtr<RegisterID>, JSStack::CallFrameHeaderSize, UnsafeVectorOverflow> callFrame;
1912     for (int i = 0; i < JSStack::CallFrameHeaderSize; ++i)
1913         callFrame.append(newTemporary());
1914
1915     if (m_shouldEmitProfileHooks) {
1916         emitOpcode(op_profile_will_call);
1917         instructions().append(callArguments.profileHookRegister()->index());
1918     }
1919
1920     emitExpressionInfo(divot, divotStart, divotEnd);
1921
1922     RefPtr<Label> done = newLabel();
1923     expectedFunction = emitExpectedFunctionSnippet(dst, func, expectedFunction, callArguments, done.get());
1924     
1925     // Emit call.
1926     UnlinkedArrayProfile arrayProfile = newArrayProfile();
1927     UnlinkedValueProfile profile = emitProfiledOpcode(opcodeID);
1928     ASSERT(dst);
1929     ASSERT(dst != ignoredResult());
1930     instructions().append(dst->index());
1931     instructions().append(func->index());
1932     instructions().append(callArguments.argumentCountIncludingThis());
1933     instructions().append(callArguments.stackOffset());
1934     instructions().append(m_codeBlock->addLLIntCallLinkInfo());
1935     instructions().append(0);
1936     instructions().append(arrayProfile);
1937     instructions().append(profile);
1938     
1939     if (expectedFunction != NoExpectedFunction)
1940         emitLabel(done.get());
1941
1942     if (m_shouldEmitProfileHooks) {
1943         emitOpcode(op_profile_did_call);
1944         instructions().append(callArguments.profileHookRegister()->index());
1945     }
1946
1947     return dst;
1948 }
1949
1950 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)
1951 {
1952     return emitCallVarargs(op_call_varargs, dst, func, thisRegister, arguments, firstFreeRegister, firstVarArgOffset, profileHookRegister, divot, divotStart, divotEnd);
1953 }
1954
1955 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)
1956 {
1957     return emitCallVarargs(op_construct_varargs, dst, func, thisRegister, arguments, firstFreeRegister, firstVarArgOffset, profileHookRegister, divot, divotStart, divotEnd);
1958 }
1959     
1960 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)
1961 {
1962     if (m_shouldEmitProfileHooks) {
1963         emitMove(profileHookRegister, func);
1964         emitOpcode(op_profile_will_call);
1965         instructions().append(profileHookRegister->index());
1966     }
1967     
1968     emitExpressionInfo(divot, divotStart, divotEnd);
1969
1970     // Emit call.
1971     UnlinkedArrayProfile arrayProfile = newArrayProfile();
1972     UnlinkedValueProfile profile = emitProfiledOpcode(opcode);
1973     ASSERT(dst != ignoredResult());
1974     instructions().append(dst->index());
1975     instructions().append(func->index());
1976     instructions().append(thisRegister ? thisRegister->index() : 0);
1977     instructions().append(arguments->index());
1978     instructions().append(firstFreeRegister->index());
1979     instructions().append(firstVarArgOffset);
1980     instructions().append(arrayProfile);
1981     instructions().append(profile);
1982     if (m_shouldEmitProfileHooks) {
1983         emitOpcode(op_profile_did_call);
1984         instructions().append(profileHookRegister->index());
1985     }
1986     return dst;
1987 }
1988
1989 void BytecodeGenerator::emitCallDefineProperty(RegisterID* newObj, RegisterID* propertyNameRegister,
1990     RegisterID* valueRegister, RegisterID* getterRegister, RegisterID* setterRegister, unsigned options, const JSTextPosition& position)
1991 {
1992     RefPtr<RegisterID> descriptorRegister = emitNewObject(newTemporary());
1993
1994     RefPtr<RegisterID> trueRegister = emitLoad(newTemporary(), true);
1995     if (options & PropertyConfigurable)
1996         emitDirectPutById(descriptorRegister.get(), propertyNames().configurable, trueRegister.get(), PropertyNode::Unknown);
1997     if (options & PropertyWritable)
1998         emitDirectPutById(descriptorRegister.get(), propertyNames().writable, trueRegister.get(), PropertyNode::Unknown);
1999     else if (valueRegister) {
2000         RefPtr<RegisterID> falseRegister = emitLoad(newTemporary(), false);
2001         emitDirectPutById(descriptorRegister.get(), propertyNames().writable, falseRegister.get(), PropertyNode::Unknown);
2002     }
2003     if (options & PropertyEnumerable)
2004         emitDirectPutById(descriptorRegister.get(), propertyNames().enumerable, trueRegister.get(), PropertyNode::Unknown);
2005
2006     if (valueRegister)
2007         emitDirectPutById(descriptorRegister.get(), propertyNames().value, valueRegister, PropertyNode::Unknown);
2008     if (getterRegister)
2009         emitDirectPutById(descriptorRegister.get(), propertyNames().get, getterRegister, PropertyNode::Unknown);
2010     if (setterRegister)
2011         emitDirectPutById(descriptorRegister.get(), propertyNames().set, setterRegister, PropertyNode::Unknown);
2012
2013     RefPtr<RegisterID> definePropertyRegister = emitMoveLinkTimeConstant(newTemporary(), LinkTimeConstant::DefinePropertyFunction);
2014
2015     CallArguments callArguments(*this, nullptr, 3);
2016     emitLoad(callArguments.thisRegister(), jsUndefined());
2017     emitMove(callArguments.argumentRegister(0), newObj);
2018     emitMove(callArguments.argumentRegister(1), propertyNameRegister);
2019     emitMove(callArguments.argumentRegister(2), descriptorRegister.get());
2020
2021     emitCall(newTemporary(), definePropertyRegister.get(), NoExpectedFunction, callArguments, position, position, position);
2022 }
2023
2024 RegisterID* BytecodeGenerator::emitReturn(RegisterID* src)
2025 {
2026     if (isConstructor()) {
2027         bool derived = constructorKind() == ConstructorKind::Derived;
2028         if (derived && src->index() == m_thisRegister.index())
2029             emitTDZCheck(src);
2030
2031         RefPtr<Label> isObjectLabel = newLabel();
2032         emitJumpIfTrue(emitIsObject(newTemporary(), src), isObjectLabel.get());
2033
2034         if (derived) {
2035             RefPtr<Label> isUndefinedLabel = newLabel();
2036             emitJumpIfTrue(emitIsUndefined(newTemporary(), src), isUndefinedLabel.get());
2037             emitThrowTypeError("Cannot return a non-object type in the constructor of a derived class.");
2038             emitLabel(isUndefinedLabel.get());
2039             if (constructorKind() == ConstructorKind::Derived)
2040                 emitTDZCheck(&m_thisRegister);
2041         }
2042
2043         emitUnaryNoDstOp(op_ret, &m_thisRegister);
2044
2045         emitLabel(isObjectLabel.get());
2046     }
2047
2048     return emitUnaryNoDstOp(op_ret, src);
2049 }
2050
2051 RegisterID* BytecodeGenerator::emitUnaryNoDstOp(OpcodeID opcodeID, RegisterID* src)
2052 {
2053     emitOpcode(opcodeID);
2054     instructions().append(src->index());
2055     return src;
2056 }
2057
2058 RegisterID* BytecodeGenerator::emitConstruct(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd)
2059 {
2060     ASSERT(func->refCount());
2061
2062     if (m_shouldEmitProfileHooks)
2063         emitMove(callArguments.profileHookRegister(), func);
2064
2065     // Generate code for arguments.
2066     unsigned argument = 0;
2067     if (ArgumentsNode* argumentsNode = callArguments.argumentsNode()) {
2068         
2069         ArgumentListNode* n = callArguments.argumentsNode()->m_listNode;
2070         if (n && n->m_expr->isSpreadExpression()) {
2071             RELEASE_ASSERT(!n->m_next);
2072             auto expression = static_cast<SpreadExpressionNode*>(n->m_expr)->expression();
2073             RefPtr<RegisterID> argumentRegister;
2074             argumentRegister = expression->emitBytecode(*this, callArguments.argumentRegister(0));
2075             return emitConstructVarargs(dst, func, callArguments.thisRegister(), argumentRegister.get(), newTemporary(), 0, callArguments.profileHookRegister(), divot, divotStart, divotEnd);
2076         }
2077         
2078         for (ArgumentListNode* n = argumentsNode->m_listNode; n; n = n->m_next)
2079             emitNode(callArguments.argumentRegister(argument++), n);
2080     }
2081
2082     if (m_shouldEmitProfileHooks) {
2083         emitOpcode(op_profile_will_call);
2084         instructions().append(callArguments.profileHookRegister()->index());
2085     }
2086
2087     // Reserve space for call frame.
2088     Vector<RefPtr<RegisterID>, JSStack::CallFrameHeaderSize, UnsafeVectorOverflow> callFrame;
2089     for (int i = 0; i < JSStack::CallFrameHeaderSize; ++i)
2090         callFrame.append(newTemporary());
2091
2092     emitExpressionInfo(divot, divotStart, divotEnd);
2093     
2094     RefPtr<Label> done = newLabel();
2095     expectedFunction = emitExpectedFunctionSnippet(dst, func, expectedFunction, callArguments, done.get());
2096
2097     UnlinkedValueProfile profile = emitProfiledOpcode(op_construct);
2098     ASSERT(dst != ignoredResult());
2099     instructions().append(dst->index());
2100     instructions().append(func->index());
2101     instructions().append(callArguments.argumentCountIncludingThis());
2102     instructions().append(callArguments.stackOffset());
2103     instructions().append(m_codeBlock->addLLIntCallLinkInfo());
2104     instructions().append(0);
2105     instructions().append(0);
2106     instructions().append(profile);
2107
2108     if (expectedFunction != NoExpectedFunction)
2109         emitLabel(done.get());
2110
2111     if (m_shouldEmitProfileHooks) {
2112         emitOpcode(op_profile_did_call);
2113         instructions().append(callArguments.profileHookRegister()->index());
2114     }
2115
2116     return dst;
2117 }
2118
2119 RegisterID* BytecodeGenerator::emitStrcat(RegisterID* dst, RegisterID* src, int count)
2120 {
2121     emitOpcode(op_strcat);
2122     instructions().append(dst->index());
2123     instructions().append(src->index());
2124     instructions().append(count);
2125
2126     return dst;
2127 }
2128
2129 void BytecodeGenerator::emitToPrimitive(RegisterID* dst, RegisterID* src)
2130 {
2131     emitOpcode(op_to_primitive);
2132     instructions().append(dst->index());
2133     instructions().append(src->index());
2134 }
2135
2136 void BytecodeGenerator::emitGetScope()
2137 {
2138     emitOpcode(op_get_scope);
2139     instructions().append(scopeRegister()->index());
2140 }
2141
2142 RegisterID* BytecodeGenerator::emitPushWithScope(RegisterID* dst, RegisterID* scope)
2143 {
2144     ControlFlowContext context;
2145     context.isFinallyBlock = false;
2146     m_scopeContextStack.append(context);
2147     m_localScopeDepth++;
2148
2149     return emitUnaryOp(op_push_with_scope, dst, scope);
2150 }
2151
2152 void BytecodeGenerator::emitPopScope(RegisterID* srcDst)
2153 {
2154     ASSERT(m_scopeContextStack.size());
2155     ASSERT(!m_scopeContextStack.last().isFinallyBlock);
2156
2157     emitOpcode(op_pop_scope);
2158     instructions().append(srcDst->index());
2159
2160     m_scopeContextStack.removeLast();
2161     m_localScopeDepth--;
2162 }
2163
2164 void BytecodeGenerator::emitDebugHook(DebugHookID debugHookID, unsigned line, unsigned charOffset, unsigned lineStart)
2165 {
2166 #if ENABLE(DEBUG_WITH_BREAKPOINT)
2167     if (debugHookID != DidReachBreakpoint)
2168         return;
2169 #else
2170     if (!m_shouldEmitDebugHooks)
2171         return;
2172 #endif
2173     JSTextPosition divot(line, charOffset, lineStart);
2174     emitExpressionInfo(divot, divot, divot);
2175     emitOpcode(op_debug);
2176     instructions().append(debugHookID);
2177     instructions().append(false);
2178 }
2179
2180 void BytecodeGenerator::pushFinallyContext(StatementNode* finallyBlock)
2181 {
2182     // Reclaim free label scopes.
2183     while (m_labelScopes.size() && !m_labelScopes.last().refCount())
2184         m_labelScopes.removeLast();
2185
2186     ControlFlowContext scope;
2187     scope.isFinallyBlock = true;
2188     FinallyContext context = {
2189         finallyBlock,
2190         nullptr,
2191         nullptr,
2192         static_cast<unsigned>(m_scopeContextStack.size()),
2193         static_cast<unsigned>(m_switchContextStack.size()),
2194         static_cast<unsigned>(m_forInContextStack.size()),
2195         static_cast<unsigned>(m_tryContextStack.size()),
2196         static_cast<unsigned>(m_labelScopes.size()),
2197         m_finallyDepth,
2198         m_localScopeDepth
2199     };
2200     scope.finallyContext = context;
2201     m_scopeContextStack.append(scope);
2202     m_finallyDepth++;
2203 }
2204
2205 void BytecodeGenerator::pushIteratorCloseContext(RegisterID* iterator, ThrowableExpressionData* node)
2206 {
2207     // Reclaim free label scopes.
2208     while (m_labelScopes.size() && !m_labelScopes.last().refCount())
2209         m_labelScopes.removeLast();
2210
2211     ControlFlowContext scope;
2212     scope.isFinallyBlock = true;
2213     FinallyContext context = {
2214         nullptr,
2215         iterator,
2216         node,
2217         static_cast<unsigned>(m_scopeContextStack.size()),
2218         static_cast<unsigned>(m_switchContextStack.size()),
2219         static_cast<unsigned>(m_forInContextStack.size()),
2220         static_cast<unsigned>(m_tryContextStack.size()),
2221         static_cast<unsigned>(m_labelScopes.size()),
2222         m_finallyDepth,
2223         m_localScopeDepth
2224     };
2225     scope.finallyContext = context;
2226     m_scopeContextStack.append(scope);
2227     m_finallyDepth++;
2228 }
2229
2230 void BytecodeGenerator::popFinallyContext()
2231 {
2232     ASSERT(m_scopeContextStack.size());
2233     ASSERT(m_scopeContextStack.last().isFinallyBlock);
2234     ASSERT(m_scopeContextStack.last().finallyContext.finallyBlock);
2235     ASSERT(!m_scopeContextStack.last().finallyContext.iterator);
2236     ASSERT(!m_scopeContextStack.last().finallyContext.enumerationNode);
2237     ASSERT(m_finallyDepth > 0);
2238     m_scopeContextStack.removeLast();
2239     m_finallyDepth--;
2240 }
2241
2242 void BytecodeGenerator::popIteratorCloseContext()
2243 {
2244     ASSERT(m_scopeContextStack.size());
2245     ASSERT(m_scopeContextStack.last().isFinallyBlock);
2246     ASSERT(!m_scopeContextStack.last().finallyContext.finallyBlock);
2247     ASSERT(m_scopeContextStack.last().finallyContext.iterator);
2248     ASSERT(m_scopeContextStack.last().finallyContext.enumerationNode);
2249     ASSERT(m_finallyDepth > 0);
2250     m_scopeContextStack.removeLast();
2251     m_finallyDepth--;
2252 }
2253
2254 LabelScopePtr BytecodeGenerator::breakTarget(const Identifier& name)
2255 {
2256     // Reclaim free label scopes.
2257     //
2258     // The condition was previously coded as 'm_labelScopes.size() && !m_labelScopes.last().refCount()',
2259     // however sometimes this appears to lead to GCC going a little haywire and entering the loop with
2260     // size 0, leading to segfaulty badness.  We are yet to identify a valid cause within our code to
2261     // cause the GCC codegen to misbehave in this fashion, and as such the following refactoring of the
2262     // loop condition is a workaround.
2263     while (m_labelScopes.size()) {
2264         if  (m_labelScopes.last().refCount())
2265             break;
2266         m_labelScopes.removeLast();
2267     }
2268
2269     if (!m_labelScopes.size())
2270         return LabelScopePtr::null();
2271
2272     // We special-case the following, which is a syntax error in Firefox:
2273     // label:
2274     //     break;
2275     if (name.isEmpty()) {
2276         for (int i = m_labelScopes.size() - 1; i >= 0; --i) {
2277             LabelScope* scope = &m_labelScopes[i];
2278             if (scope->type() != LabelScope::NamedLabel) {
2279                 ASSERT(scope->breakTarget());
2280                 return LabelScopePtr(m_labelScopes, i);
2281             }
2282         }
2283         return LabelScopePtr::null();
2284     }
2285
2286     for (int i = m_labelScopes.size() - 1; i >= 0; --i) {
2287         LabelScope* scope = &m_labelScopes[i];
2288         if (scope->name() && *scope->name() == name) {
2289             ASSERT(scope->breakTarget());
2290             return LabelScopePtr(m_labelScopes, i);
2291         }
2292     }
2293     return LabelScopePtr::null();
2294 }
2295
2296 LabelScopePtr BytecodeGenerator::continueTarget(const Identifier& name)
2297 {
2298     // Reclaim free label scopes.
2299     while (m_labelScopes.size() && !m_labelScopes.last().refCount())
2300         m_labelScopes.removeLast();
2301
2302     if (!m_labelScopes.size())
2303         return LabelScopePtr::null();
2304
2305     if (name.isEmpty()) {
2306         for (int i = m_labelScopes.size() - 1; i >= 0; --i) {
2307             LabelScope* scope = &m_labelScopes[i];
2308             if (scope->type() == LabelScope::Loop) {
2309                 ASSERT(scope->continueTarget());
2310                 return LabelScopePtr(m_labelScopes, i);
2311             }
2312         }
2313         return LabelScopePtr::null();
2314     }
2315
2316     // Continue to the loop nested nearest to the label scope that matches
2317     // 'name'.
2318     LabelScopePtr result = LabelScopePtr::null();
2319     for (int i = m_labelScopes.size() - 1; i >= 0; --i) {
2320         LabelScope* scope = &m_labelScopes[i];
2321         if (scope->type() == LabelScope::Loop) {
2322             ASSERT(scope->continueTarget());
2323             result = LabelScopePtr(m_labelScopes, i);
2324         }
2325         if (scope->name() && *scope->name() == name)
2326             return result; // may be null.
2327     }
2328     return LabelScopePtr::null();
2329 }
2330
2331 void BytecodeGenerator::allocateAndEmitScope()
2332 {
2333     m_scopeRegister = addVar();
2334     m_scopeRegister->ref();
2335     m_codeBlock->setScopeRegister(scopeRegister()->virtualRegister());
2336     emitGetScope();
2337 }
2338
2339 void BytecodeGenerator::emitComplexPopScopes(RegisterID* scope, ControlFlowContext* topScope, ControlFlowContext* bottomScope)
2340 {
2341     while (topScope > bottomScope) {
2342         // First we count the number of dynamic scopes we need to remove to get
2343         // to a finally block.
2344         int nNormalScopes = 0;
2345         while (topScope > bottomScope) {
2346             if (topScope->isFinallyBlock)
2347                 break;
2348             ++nNormalScopes;
2349             --topScope;
2350         }
2351
2352         if (nNormalScopes) {
2353             // We need to remove a number of dynamic scopes to get to the next
2354             // finally block
2355             while (nNormalScopes--) {
2356                 emitOpcode(op_pop_scope);
2357                 instructions().append(scope->index());
2358             }
2359
2360             // If topScope == bottomScope then there isn't a finally block left to emit.
2361             if (topScope == bottomScope)
2362                 return;
2363         }
2364         
2365         Vector<ControlFlowContext> savedScopeContextStack;
2366         Vector<SwitchInfo> savedSwitchContextStack;
2367         Vector<std::unique_ptr<ForInContext>> savedForInContextStack;
2368         Vector<TryContext> poppedTryContexts;
2369         LabelScopeStore savedLabelScopes;
2370         while (topScope > bottomScope && topScope->isFinallyBlock) {
2371             RefPtr<Label> beforeFinally = emitLabel(newLabel().get());
2372             
2373             // Save the current state of the world while instating the state of the world
2374             // for the finally block.
2375             FinallyContext finallyContext = topScope->finallyContext;
2376             bool flipScopes = finallyContext.scopeContextStackSize != m_scopeContextStack.size();
2377             bool flipSwitches = finallyContext.switchContextStackSize != m_switchContextStack.size();
2378             bool flipForIns = finallyContext.forInContextStackSize != m_forInContextStack.size();
2379             bool flipTries = finallyContext.tryContextStackSize != m_tryContextStack.size();
2380             bool flipLabelScopes = finallyContext.labelScopesSize != m_labelScopes.size();
2381             int topScopeIndex = -1;
2382             int bottomScopeIndex = -1;
2383             if (flipScopes) {
2384                 topScopeIndex = topScope - m_scopeContextStack.begin();
2385                 bottomScopeIndex = bottomScope - m_scopeContextStack.begin();
2386                 savedScopeContextStack = m_scopeContextStack;
2387                 m_scopeContextStack.shrink(finallyContext.scopeContextStackSize);
2388             }
2389             if (flipSwitches) {
2390                 savedSwitchContextStack = m_switchContextStack;
2391                 m_switchContextStack.shrink(finallyContext.switchContextStackSize);
2392             }
2393             if (flipForIns) {
2394                 savedForInContextStack.swap(m_forInContextStack);
2395                 m_forInContextStack.shrink(finallyContext.forInContextStackSize);
2396             }
2397             if (flipTries) {
2398                 while (m_tryContextStack.size() != finallyContext.tryContextStackSize) {
2399                     ASSERT(m_tryContextStack.size() > finallyContext.tryContextStackSize);
2400                     TryContext context = m_tryContextStack.last();
2401                     m_tryContextStack.removeLast();
2402                     TryRange range;
2403                     range.start = context.start;
2404                     range.end = beforeFinally;
2405                     range.tryData = context.tryData;
2406                     m_tryRanges.append(range);
2407                     poppedTryContexts.append(context);
2408                 }
2409             }
2410             if (flipLabelScopes) {
2411                 savedLabelScopes = m_labelScopes;
2412                 while (m_labelScopes.size() > finallyContext.labelScopesSize)
2413                     m_labelScopes.removeLast();
2414             }
2415             int savedFinallyDepth = m_finallyDepth;
2416             m_finallyDepth = finallyContext.finallyDepth;
2417             int savedDynamicScopeDepth = m_localScopeDepth;
2418             m_localScopeDepth = finallyContext.dynamicScopeDepth;
2419             
2420             if (finallyContext.finallyBlock) {
2421                 // Emit the finally block.
2422                 emitNode(finallyContext.finallyBlock);
2423             } else {
2424                 // Emit the IteratorClose block.
2425                 ASSERT(finallyContext.iterator);
2426                 emitIteratorClose(finallyContext.iterator, finallyContext.enumerationNode);
2427             }
2428
2429             RefPtr<Label> afterFinally = emitLabel(newLabel().get());
2430             
2431             // Restore the state of the world.
2432             if (flipScopes) {
2433                 m_scopeContextStack = savedScopeContextStack;
2434                 topScope = &m_scopeContextStack[topScopeIndex]; // assert it's within bounds
2435                 bottomScope = m_scopeContextStack.begin() + bottomScopeIndex; // don't assert, since it the index might be -1.
2436             }
2437             if (flipSwitches)
2438                 m_switchContextStack = savedSwitchContextStack;
2439             if (flipForIns)
2440                 m_forInContextStack.swap(savedForInContextStack);
2441             if (flipTries) {
2442                 ASSERT(m_tryContextStack.size() == finallyContext.tryContextStackSize);
2443                 for (unsigned i = poppedTryContexts.size(); i--;) {
2444                     TryContext context = poppedTryContexts[i];
2445                     context.start = afterFinally;
2446                     m_tryContextStack.append(context);
2447                 }
2448                 poppedTryContexts.clear();
2449             }
2450             if (flipLabelScopes)
2451                 m_labelScopes = savedLabelScopes;
2452             m_finallyDepth = savedFinallyDepth;
2453             m_localScopeDepth = savedDynamicScopeDepth;
2454             
2455             --topScope;
2456         }
2457     }
2458 }
2459
2460 void BytecodeGenerator::emitPopScopes(RegisterID* scope, int targetScopeDepth)
2461 {
2462     ASSERT(scopeDepth() - targetScopeDepth >= 0);
2463
2464     size_t scopeDelta = scopeDepth() - targetScopeDepth;
2465     ASSERT(scopeDelta <= m_scopeContextStack.size());
2466     if (!scopeDelta)
2467         return;
2468
2469     if (!m_finallyDepth) {
2470         while (scopeDelta--) {
2471             emitOpcode(op_pop_scope);
2472             instructions().append(scope->index());
2473         }
2474         return;
2475     }
2476
2477     emitComplexPopScopes(scope, &m_scopeContextStack.last(), &m_scopeContextStack.last() - scopeDelta);
2478 }
2479
2480 TryData* BytecodeGenerator::pushTry(Label* start)
2481 {
2482     TryData tryData;
2483     tryData.target = newLabel();
2484     tryData.targetScopeDepth = UINT_MAX;
2485     m_tryData.append(tryData);
2486     TryData* result = &m_tryData.last();
2487     
2488     TryContext tryContext;
2489     tryContext.start = start;
2490     tryContext.tryData = result;
2491     
2492     m_tryContextStack.append(tryContext);
2493     
2494     return result;
2495 }
2496
2497 RegisterID* BytecodeGenerator::popTryAndEmitCatch(TryData* tryData, RegisterID* targetRegister, Label* end)
2498 {
2499     m_usesExceptions = true;
2500     
2501     ASSERT_UNUSED(tryData, m_tryContextStack.last().tryData == tryData);
2502     
2503     TryRange tryRange;
2504     tryRange.start = m_tryContextStack.last().start;
2505     tryRange.end = end;
2506     tryRange.tryData = m_tryContextStack.last().tryData;
2507     m_tryRanges.append(tryRange);
2508     m_tryContextStack.removeLast();
2509     
2510     emitLabel(tryRange.tryData->target.get());
2511     tryRange.tryData->targetScopeDepth = m_localScopeDepth;
2512
2513     emitOpcode(op_catch);
2514     instructions().append(targetRegister->index());
2515     return targetRegister;
2516 }
2517
2518 void BytecodeGenerator::emitThrowReferenceError(const String& message)
2519 {
2520     emitOpcode(op_throw_static_error);
2521     instructions().append(addConstantValue(addStringConstant(Identifier::fromString(m_vm, message)))->index());
2522     instructions().append(true);
2523 }
2524
2525 void BytecodeGenerator::emitThrowTypeError(const String& message)
2526 {
2527     emitOpcode(op_throw_static_error);
2528     instructions().append(addConstantValue(addStringConstant(Identifier::fromString(m_vm, message)))->index());
2529     instructions().append(false);
2530 }
2531
2532 void BytecodeGenerator::emitPushFunctionNameScope(RegisterID* dst, const Identifier& property, RegisterID* value, unsigned attributes)
2533 {
2534     emitOpcode(op_push_name_scope);
2535     instructions().append(dst->index());
2536     instructions().append(value->index());
2537     instructions().append(addConstantValue(SymbolTable::createNameScopeTable(*vm(), property, attributes))->index());
2538     instructions().append(JSNameScope::FunctionNameScope);
2539 }
2540
2541 void BytecodeGenerator::emitPushCatchScope(RegisterID* dst, const Identifier& property, RegisterID* value, unsigned attributes)
2542 {
2543     ControlFlowContext context;
2544     context.isFinallyBlock = false;
2545     m_scopeContextStack.append(context);
2546     m_localScopeDepth++;
2547
2548     emitOpcode(op_push_name_scope);
2549     instructions().append(dst->index());
2550     instructions().append(value->index());
2551     instructions().append(addConstantValue(SymbolTable::createNameScopeTable(*vm(), property, attributes))->index());
2552     instructions().append(JSNameScope::CatchScope);
2553 }
2554
2555 void BytecodeGenerator::beginSwitch(RegisterID* scrutineeRegister, SwitchInfo::SwitchType type)
2556 {
2557     SwitchInfo info = { static_cast<uint32_t>(instructions().size()), type };
2558     switch (type) {
2559         case SwitchInfo::SwitchImmediate:
2560             emitOpcode(op_switch_imm);
2561             break;
2562         case SwitchInfo::SwitchCharacter:
2563             emitOpcode(op_switch_char);
2564             break;
2565         case SwitchInfo::SwitchString:
2566             emitOpcode(op_switch_string);
2567             break;
2568         default:
2569             RELEASE_ASSERT_NOT_REACHED();
2570     }
2571
2572     instructions().append(0); // place holder for table index
2573     instructions().append(0); // place holder for default target    
2574     instructions().append(scrutineeRegister->index());
2575     m_switchContextStack.append(info);
2576 }
2577
2578 static int32_t keyForImmediateSwitch(ExpressionNode* node, int32_t min, int32_t max)
2579 {
2580     UNUSED_PARAM(max);
2581     ASSERT(node->isNumber());
2582     double value = static_cast<NumberNode*>(node)->value();
2583     int32_t key = static_cast<int32_t>(value);
2584     ASSERT(key == value);
2585     ASSERT(key >= min);
2586     ASSERT(key <= max);
2587     return key - min;
2588 }
2589
2590 static int32_t keyForCharacterSwitch(ExpressionNode* node, int32_t min, int32_t max)
2591 {
2592     UNUSED_PARAM(max);
2593     ASSERT(node->isString());
2594     StringImpl* clause = static_cast<StringNode*>(node)->value().impl();
2595     ASSERT(clause->length() == 1);
2596     
2597     int32_t key = (*clause)[0];
2598     ASSERT(key >= min);
2599     ASSERT(key <= max);
2600     return key - min;
2601 }
2602
2603 static void prepareJumpTableForSwitch(
2604     UnlinkedSimpleJumpTable& jumpTable, int32_t switchAddress, uint32_t clauseCount,
2605     RefPtr<Label>* labels, ExpressionNode** nodes, int32_t min, int32_t max,
2606     int32_t (*keyGetter)(ExpressionNode*, int32_t min, int32_t max))
2607 {
2608     jumpTable.min = min;
2609     jumpTable.branchOffsets.resize(max - min + 1);
2610     jumpTable.branchOffsets.fill(0);
2611     for (uint32_t i = 0; i < clauseCount; ++i) {
2612         // We're emitting this after the clause labels should have been fixed, so 
2613         // the labels should not be "forward" references
2614         ASSERT(!labels[i]->isForward());
2615         jumpTable.add(keyGetter(nodes[i], min, max), labels[i]->bind(switchAddress, switchAddress + 3)); 
2616     }
2617 }
2618
2619 static void prepareJumpTableForStringSwitch(UnlinkedStringJumpTable& jumpTable, int32_t switchAddress, uint32_t clauseCount, RefPtr<Label>* labels, ExpressionNode** nodes)
2620 {
2621     for (uint32_t i = 0; i < clauseCount; ++i) {
2622         // We're emitting this after the clause labels should have been fixed, so 
2623         // the labels should not be "forward" references
2624         ASSERT(!labels[i]->isForward());
2625         
2626         ASSERT(nodes[i]->isString());
2627         StringImpl* clause = static_cast<StringNode*>(nodes[i])->value().impl();
2628         jumpTable.offsetTable.add(clause, labels[i]->bind(switchAddress, switchAddress + 3));
2629     }
2630 }
2631
2632 void BytecodeGenerator::endSwitch(uint32_t clauseCount, RefPtr<Label>* labels, ExpressionNode** nodes, Label* defaultLabel, int32_t min, int32_t max)
2633 {
2634     SwitchInfo switchInfo = m_switchContextStack.last();
2635     m_switchContextStack.removeLast();
2636     
2637     switch (switchInfo.switchType) {
2638     case SwitchInfo::SwitchImmediate:
2639     case SwitchInfo::SwitchCharacter: {
2640         instructions()[switchInfo.bytecodeOffset + 1] = m_codeBlock->numberOfSwitchJumpTables();
2641         instructions()[switchInfo.bytecodeOffset + 2] = defaultLabel->bind(switchInfo.bytecodeOffset, switchInfo.bytecodeOffset + 3);
2642
2643         UnlinkedSimpleJumpTable& jumpTable = m_codeBlock->addSwitchJumpTable();
2644         prepareJumpTableForSwitch(
2645             jumpTable, switchInfo.bytecodeOffset, clauseCount, labels, nodes, min, max,
2646             switchInfo.switchType == SwitchInfo::SwitchImmediate
2647                 ? keyForImmediateSwitch
2648                 : keyForCharacterSwitch); 
2649         break;
2650     }
2651         
2652     case SwitchInfo::SwitchString: {
2653         instructions()[switchInfo.bytecodeOffset + 1] = m_codeBlock->numberOfStringSwitchJumpTables();
2654         instructions()[switchInfo.bytecodeOffset + 2] = defaultLabel->bind(switchInfo.bytecodeOffset, switchInfo.bytecodeOffset + 3);
2655
2656         UnlinkedStringJumpTable& jumpTable = m_codeBlock->addStringSwitchJumpTable();
2657         prepareJumpTableForStringSwitch(jumpTable, switchInfo.bytecodeOffset, clauseCount, labels, nodes);
2658         break;
2659     }
2660         
2661     default:
2662         RELEASE_ASSERT_NOT_REACHED();
2663         break;
2664     }
2665 }
2666
2667 RegisterID* BytecodeGenerator::emitThrowExpressionTooDeepException()
2668 {
2669     // It would be nice to do an even better job of identifying exactly where the expression is.
2670     // And we could make the caller pass the node pointer in, if there was some way of getting
2671     // that from an arbitrary node. However, calling emitExpressionInfo without any useful data
2672     // is still good enough to get us an accurate line number.
2673     m_expressionTooDeep = true;
2674     return newTemporary();
2675 }
2676
2677 bool BytecodeGenerator::isArgumentNumber(const Identifier& ident, int argumentNumber)
2678 {
2679     RegisterID* registerID = variable(ident).local();
2680     if (!registerID)
2681         return false;
2682     return registerID->index() == CallFrame::argumentOffset(argumentNumber);
2683 }
2684
2685 void BytecodeGenerator::emitReadOnlyExceptionIfNeeded()
2686 {
2687     if (!isStrictMode())
2688         return;
2689     emitOpcode(op_throw_static_error);
2690     instructions().append(addConstantValue(addStringConstant(Identifier::fromString(m_vm, StrictModeReadonlyPropertyWriteError)))->index());
2691     instructions().append(false);
2692 }
2693     
2694 void BytecodeGenerator::emitEnumeration(ThrowableExpressionData* node, ExpressionNode* subjectNode, const std::function<void(BytecodeGenerator&, RegisterID*)>& callBack)
2695 {
2696     RefPtr<RegisterID> subject = newTemporary();
2697     emitNode(subject.get(), subjectNode);
2698     RefPtr<RegisterID> iterator = emitGetById(newTemporary(), subject.get(), propertyNames().iteratorSymbol);
2699     {
2700         CallArguments args(*this, nullptr);
2701         emitMove(args.thisRegister(), subject.get());
2702         emitCall(iterator.get(), iterator.get(), NoExpectedFunction, args, node->divot(), node->divotStart(), node->divotEnd());
2703     }
2704
2705     RefPtr<Label> loopDone = newLabel();
2706     // RefPtr<Register> iterator's lifetime must be longer than IteratorCloseContext.
2707     pushIteratorCloseContext(iterator.get(), node);
2708     {
2709         LabelScopePtr scope = newLabelScope(LabelScope::Loop);
2710         RefPtr<RegisterID> value = newTemporary();
2711         emitLoad(value.get(), jsUndefined());
2712
2713         emitJump(scope->continueTarget());
2714
2715         RefPtr<Label> loopStart = newLabel();
2716         emitLabel(loopStart.get());
2717         emitLoopHint();
2718
2719         RefPtr<Label> tryStartLabel = newLabel();
2720         emitLabel(tryStartLabel.get());
2721         TryData* tryData = pushTry(tryStartLabel.get());
2722         callBack(*this, value.get());
2723         emitJump(scope->continueTarget());
2724
2725         // IteratorClose sequence for throw-ed control flow.
2726         {
2727             RefPtr<Label> catchHere = emitLabel(newLabel().get());
2728             RefPtr<RegisterID> exceptionRegister = popTryAndEmitCatch(tryData, newTemporary(), catchHere.get());
2729             RefPtr<Label> catchDone = newLabel();
2730
2731             RefPtr<RegisterID> returnMethod = emitGetById(newTemporary(), iterator.get(), propertyNames().returnKeyword);
2732             emitJumpIfTrue(emitIsUndefined(newTemporary(), returnMethod.get()), catchDone.get());
2733
2734             RefPtr<Label> returnCallTryStart = newLabel();
2735             emitLabel(returnCallTryStart.get());
2736             TryData* returnCallTryData = pushTry(returnCallTryStart.get());
2737
2738             CallArguments returnArguments(*this, nullptr);
2739             emitMove(returnArguments.thisRegister(), iterator.get());
2740             emitCall(value.get(), returnMethod.get(), NoExpectedFunction, returnArguments, node->divot(), node->divotStart(), node->divotEnd());
2741
2742             emitLabel(catchDone.get());
2743             emitThrow(exceptionRegister.get());
2744
2745             // Absorb exception.
2746             popTryAndEmitCatch(returnCallTryData, newTemporary(), catchDone.get());
2747             emitThrow(exceptionRegister.get());
2748         }
2749
2750         emitLabel(scope->continueTarget());
2751         {
2752             {
2753                 RefPtr<RegisterID> next = emitGetById(newTemporary(), iterator.get(), propertyNames().next);
2754                 CallArguments nextArguments(*this, nullptr);
2755                 emitMove(nextArguments.thisRegister(), iterator.get());
2756                 emitCall(value.get(), next.get(), NoExpectedFunction, nextArguments, node->divot(), node->divotStart(), node->divotEnd());
2757             }
2758             {
2759                 RefPtr<Label> typeIsObject = newLabel();
2760                 emitJumpIfTrue(emitIsObject(newTemporary(), value.get()), typeIsObject.get());
2761                 emitThrowTypeError(ASCIILiteral("Iterator result interface is not an object."));
2762                 emitLabel(typeIsObject.get());
2763             }
2764             emitJumpIfTrue(emitGetById(newTemporary(), value.get(), propertyNames().done), loopDone.get());
2765             emitGetById(value.get(), value.get(), propertyNames().value);
2766             emitJump(loopStart.get());
2767         }
2768
2769         emitLabel(scope->breakTarget());
2770     }
2771
2772     // IteratorClose sequence for break-ed control flow.
2773     popIteratorCloseContext();
2774     emitIteratorClose(iterator.get(), node);
2775     emitLabel(loopDone.get());
2776 }
2777
2778 RegisterID* BytecodeGenerator::emitGetEnumerableLength(RegisterID* dst, RegisterID* base)
2779 {
2780     emitOpcode(op_get_enumerable_length);
2781     instructions().append(dst->index());
2782     instructions().append(base->index());
2783     return dst;
2784 }
2785
2786 RegisterID* BytecodeGenerator::emitHasGenericProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName)
2787 {
2788     emitOpcode(op_has_generic_property);
2789     instructions().append(dst->index());
2790     instructions().append(base->index());
2791     instructions().append(propertyName->index());
2792     return dst;
2793 }
2794
2795 RegisterID* BytecodeGenerator::emitHasIndexedProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName)
2796 {
2797     UnlinkedArrayProfile arrayProfile = newArrayProfile();
2798     emitOpcode(op_has_indexed_property);
2799     instructions().append(dst->index());
2800     instructions().append(base->index());
2801     instructions().append(propertyName->index());
2802     instructions().append(arrayProfile);
2803     return dst;
2804 }
2805
2806 RegisterID* BytecodeGenerator::emitHasStructureProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName, RegisterID* enumerator)
2807 {
2808     emitOpcode(op_has_structure_property);
2809     instructions().append(dst->index());
2810     instructions().append(base->index());
2811     instructions().append(propertyName->index());
2812     instructions().append(enumerator->index());
2813     return dst;
2814 }
2815
2816 RegisterID* BytecodeGenerator::emitGetPropertyEnumerator(RegisterID* dst, RegisterID* base)
2817 {
2818     emitOpcode(op_get_property_enumerator);
2819     instructions().append(dst->index());
2820     instructions().append(base->index());
2821     return dst;
2822 }
2823
2824 RegisterID* BytecodeGenerator::emitEnumeratorStructurePropertyName(RegisterID* dst, RegisterID* enumerator, RegisterID* index)
2825 {
2826     emitOpcode(op_enumerator_structure_pname);
2827     instructions().append(dst->index());
2828     instructions().append(enumerator->index());
2829     instructions().append(index->index());
2830     return dst;
2831 }
2832
2833 RegisterID* BytecodeGenerator::emitEnumeratorGenericPropertyName(RegisterID* dst, RegisterID* enumerator, RegisterID* index)
2834 {
2835     emitOpcode(op_enumerator_generic_pname);
2836     instructions().append(dst->index());
2837     instructions().append(enumerator->index());
2838     instructions().append(index->index());
2839     return dst;
2840 }
2841
2842 RegisterID* BytecodeGenerator::emitToIndexString(RegisterID* dst, RegisterID* index)
2843 {
2844     emitOpcode(op_to_index_string);
2845     instructions().append(dst->index());
2846     instructions().append(index->index());
2847     return dst;
2848 }
2849
2850
2851 RegisterID* BytecodeGenerator::emitIsObject(RegisterID* dst, RegisterID* src)
2852 {
2853     emitOpcode(op_is_object);
2854     instructions().append(dst->index());
2855     instructions().append(src->index());
2856     return dst;
2857 }
2858
2859 RegisterID* BytecodeGenerator::emitIsUndefined(RegisterID* dst, RegisterID* src)
2860 {
2861     emitOpcode(op_is_undefined);
2862     instructions().append(dst->index());
2863     instructions().append(src->index());
2864     return dst;
2865 }
2866
2867 void BytecodeGenerator::emitIteratorClose(RegisterID* iterator, ThrowableExpressionData* node)
2868 {
2869     RefPtr<Label> done = newLabel();
2870     RefPtr<RegisterID> returnMethod = emitGetById(newTemporary(), iterator, propertyNames().returnKeyword);
2871     emitJumpIfTrue(emitIsUndefined(newTemporary(), returnMethod.get()), done.get());
2872
2873     RefPtr<RegisterID> value = newTemporary();
2874     CallArguments returnArguments(*this, nullptr);
2875     emitMove(returnArguments.thisRegister(), iterator);
2876     emitCall(value.get(), returnMethod.get(), NoExpectedFunction, returnArguments, node->divot(), node->divotStart(), node->divotEnd());
2877     emitJumpIfTrue(emitIsObject(newTemporary(), value.get()), done.get());
2878     emitThrowTypeError(ASCIILiteral("Iterator result interface is not an object."));
2879     emitLabel(done.get());
2880 }
2881
2882 void BytecodeGenerator::pushIndexedForInScope(RegisterID* localRegister, RegisterID* indexRegister)
2883 {
2884     if (!localRegister)
2885         return;
2886     m_forInContextStack.append(std::make_unique<IndexedForInContext>(localRegister, indexRegister));
2887 }
2888
2889 void BytecodeGenerator::popIndexedForInScope(RegisterID* localRegister)
2890 {
2891     if (!localRegister)
2892         return;
2893     m_forInContextStack.removeLast();
2894 }
2895
2896 void BytecodeGenerator::pushStructureForInScope(RegisterID* localRegister, RegisterID* indexRegister, RegisterID* propertyRegister, RegisterID* enumeratorRegister)
2897 {
2898     if (!localRegister)
2899         return;
2900     m_forInContextStack.append(std::make_unique<StructureForInContext>(localRegister, indexRegister, propertyRegister, enumeratorRegister));
2901 }
2902
2903 void BytecodeGenerator::popStructureForInScope(RegisterID* localRegister)
2904 {
2905     if (!localRegister)
2906         return;
2907     m_forInContextStack.removeLast();
2908 }
2909
2910 void BytecodeGenerator::invalidateForInContextForLocal(RegisterID* localRegister)
2911 {
2912     // Lexically invalidating ForInContexts is kind of weak sauce, but it only occurs if 
2913     // either of the following conditions is true:
2914     // 
2915     // (1) The loop iteration variable is re-assigned within the body of the loop.
2916     // (2) The loop iteration variable is captured in the lexical scope of the function.
2917     //
2918     // These two situations occur sufficiently rarely that it's okay to use this style of 
2919     // "analysis" to make iteration faster. If we didn't want to do this, we would either have 
2920     // to perform some flow-sensitive analysis to see if/when the loop iteration variable was 
2921     // reassigned, or we'd have to resort to runtime checks to see if the variable had been 
2922     // reassigned from its original value.
2923     for (size_t i = m_forInContextStack.size(); i > 0; i--) {
2924         ForInContext* context = m_forInContextStack[i - 1].get();
2925         if (context->local() != localRegister)
2926             continue;
2927         context->invalidate();
2928         break;
2929     }
2930 }
2931
2932 } // namespace JSC