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