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