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