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.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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.
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.
32 #include "BytecodeGenerator.h"
34 #include "BuiltinExecutables.h"
35 #include "BytecodeLivenessAnalysis.h"
36 #include "Interpreter.h"
37 #include "JSFunction.h"
38 #include "JSGeneratorFunction.h"
39 #include "JSLexicalEnvironment.h"
40 #include "JSTemplateRegistryKey.h"
41 #include "LowLevelInterpreter.h"
42 #include "JSCInlines.h"
44 #include "StackAlignment.h"
45 #include "StrongInlines.h"
46 #include "UnlinkedCodeBlock.h"
47 #include "UnlinkedInstructionStream.h"
48 #include <wtf/StdLibExtras.h>
49 #include <wtf/text/WTFString.h>
55 void Label::setLocation(unsigned location)
57 m_location = location;
59 unsigned size = m_unresolvedJumps.size();
60 for (unsigned i = 0; i < size; ++i)
61 m_generator.instructions()[m_unresolvedJumps[i].second].u.operand = m_location - m_unresolvedJumps[i].first;
64 ParserError BytecodeGenerator::generate()
66 m_codeBlock->setThisRegister(m_thisRegister.virtualRegister());
68 emitLogShadowChickenPrologueIfNecessary();
70 // If we have declared a variable named "arguments" and we are using arguments then we should
71 // perform that assignment now.
72 if (m_needToInitializeArguments)
73 initializeVariable(variable(propertyNames().arguments), m_argumentsRegister);
76 m_restParameter->emit(*this);
79 RefPtr<RegisterID> temp = newTemporary();
80 RefPtr<RegisterID> globalScope;
81 for (auto functionPair : m_functionsToInitialize) {
82 FunctionMetadataNode* metadata = functionPair.first;
83 FunctionVariableType functionType = functionPair.second;
84 emitNewFunction(temp.get(), metadata);
85 if (functionType == NormalFunctionVariable)
86 initializeVariable(variable(metadata->ident()), temp.get());
87 else if (functionType == GlobalFunctionVariable) {
89 // We know this will resolve to the global object because our parser/global initialization code
90 // doesn't allow let/const/class variables to have the same names as functions.
91 RefPtr<RegisterID> globalObjectScope = emitResolveScope(nullptr, Variable(metadata->ident()));
92 globalScope = newBlockScopeVariable();
93 emitMove(globalScope.get(), globalObjectScope.get());
95 emitPutToScope(globalScope.get(), Variable(metadata->ident()), temp.get(), ThrowIfNotFound, InitializationMode::NotInitialization);
97 RELEASE_ASSERT_NOT_REACHED();
101 bool callingClassConstructor = constructorKind() != ConstructorKind::None && !isConstructor();
102 if (!callingClassConstructor)
103 m_scopeNode->emitBytecode(*this);
105 m_staticPropertyAnalyzer.kill();
107 for (unsigned i = 0; i < m_tryRanges.size(); ++i) {
108 TryRange& range = m_tryRanges[i];
109 int start = range.start->bind();
110 int end = range.end->bind();
112 // This will happen for empty try blocks and for some cases of finally blocks:
124 // The return will pop scopes to execute the outer finally block. But this includes
125 // popping the try context for the inner try. The try context is live in the fall-through
126 // part of the finally block not because we will emit a handler that overlaps the finally,
127 // but because we haven't yet had a chance to plant the catch target. Then when we finish
128 // emitting code for the outer finally block, we repush the try contex, this time with a
129 // new start index. But that means that the start index for the try range corresponding
130 // to the inner-finally-following-the-return (marked as "*HERE*" above) will be greater
131 // than the end index of the try block. This is harmless since end < start handlers will
132 // never get matched in our logic, but we do the runtime a favor and choose to not emit
133 // such handlers at all.
137 ASSERT(range.tryData->handlerType != HandlerType::Illegal);
138 UnlinkedHandlerInfo info(static_cast<uint32_t>(start), static_cast<uint32_t>(end),
139 static_cast<uint32_t>(range.tryData->target->bind()), range.tryData->handlerType);
140 m_codeBlock->addExceptionHandler(info);
143 m_codeBlock->setInstructions(std::make_unique<UnlinkedInstructionStream>(m_instructions));
145 m_codeBlock->shrinkToFit();
147 if (m_expressionTooDeep)
148 return ParserError(ParserError::OutOfMemory);
149 return ParserError(ParserError::ErrorNone);
152 BytecodeGenerator::BytecodeGenerator(VM& vm, ProgramNode* programNode, UnlinkedProgramCodeBlock* codeBlock, DebuggerMode debuggerMode, const VariableEnvironment* parentScopeTDZVariables)
153 : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
154 , m_scopeNode(programNode)
155 , m_codeBlock(vm, codeBlock)
156 , m_thisRegister(CallFrame::thisArgumentOffset())
157 , m_codeType(GlobalCode)
159 , m_needsToUpdateArrowFunctionContext(programNode->usesArrowFunction() || programNode->usesEval())
161 ASSERT_UNUSED(parentScopeTDZVariables, !parentScopeTDZVariables->size());
163 for (auto& constantRegister : m_linkTimeConstantRegisters)
164 constantRegister = nullptr;
166 allocateCalleeSaveSpace();
168 m_codeBlock->setNumParameters(1); // Allocate space for "this"
172 allocateAndEmitScope();
174 const FunctionStack& functionStack = programNode->functionStack();
176 for (size_t i = 0; i < functionStack.size(); ++i) {
177 FunctionMetadataNode* function = functionStack[i];
178 m_functionsToInitialize.append(std::make_pair(function, GlobalFunctionVariable));
180 if (Options::validateBytecode()) {
181 for (auto& entry : programNode->varDeclarations())
182 RELEASE_ASSERT(entry.value.isVar());
184 codeBlock->setVariableDeclarations(programNode->varDeclarations());
185 codeBlock->setLexicalDeclarations(programNode->lexicalVariables());
186 // Even though this program may have lexical variables that go under TDZ, when linking the get_from_scope/put_to_scope
187 // operations we emit we will have ResolveTypes that implictly do TDZ checks. Therefore, we don't need
188 // additional TDZ checks on top of those. This is why we can omit pushing programNode->lexicalVariables()
191 if (needsToUpdateArrowFunctionContext()) {
192 initializeArrowFunctionContextScopeIfNeeded();
193 emitPutThisToArrowFunctionContextScope();
197 BytecodeGenerator::BytecodeGenerator(VM& vm, FunctionNode* functionNode, UnlinkedFunctionCodeBlock* codeBlock, DebuggerMode debuggerMode, const VariableEnvironment* parentScopeTDZVariables)
198 : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
199 , m_scopeNode(functionNode)
200 , m_codeBlock(vm, codeBlock)
201 , m_codeType(FunctionCode)
203 , m_isBuiltinFunction(codeBlock->isBuiltinFunction())
204 , m_usesNonStrictEval(codeBlock->usesEval() && !codeBlock->isStrictMode())
205 // FIXME: We should be able to have tail call elimination with the profiler
206 // enabled. This is currently not possible because the profiler expects
207 // op_will_call / op_did_call pairs before and after a call, which are not
208 // compatible with tail calls (we have no way of emitting op_did_call).
209 // https://bugs.webkit.org/show_bug.cgi?id=148819
210 , m_inTailPosition(Options::useTailCalls() && !isConstructor() && constructorKind() == ConstructorKind::None && isStrictMode())
211 , m_needsToUpdateArrowFunctionContext(functionNode->usesArrowFunction() || functionNode->usesEval())
212 , m_derivedContextType(codeBlock->derivedContextType())
214 for (auto& constantRegister : m_linkTimeConstantRegisters)
215 constantRegister = nullptr;
217 if (m_isBuiltinFunction)
218 m_shouldEmitDebugHooks = false;
220 allocateCalleeSaveSpace();
222 SymbolTable* functionSymbolTable = SymbolTable::create(*m_vm);
223 functionSymbolTable->setUsesNonStrictEval(m_usesNonStrictEval);
224 int symbolTableConstantIndex = 0;
226 FunctionParameters& parameters = *functionNode->parameters();
227 // http://www.ecma-international.org/ecma-262/6.0/index.html#sec-functiondeclarationinstantiation
228 // This implements IsSimpleParameterList in the Ecma 2015 spec.
229 // If IsSimpleParameterList is false, we will create a strict-mode like arguments object.
230 // IsSimpleParameterList is false if the argument list contains any default parameter values,
231 // a rest parameter, or any destructuring patterns.
232 bool isSimpleParameterList = true;
233 // If we do have default parameters, destructuring parameters, or a rest parameter, our parameters will be allocated in a different scope.
234 for (size_t i = 0; i < parameters.size(); i++) {
235 std::pair<DestructuringPatternNode*, ExpressionNode*> parameter = parameters.at(i);
236 bool hasDefaultParameterValue = !!parameter.second;
237 auto pattern = parameter.first;
238 bool isSimpleParameter = !hasDefaultParameterValue && pattern->isBindingNode();
239 isSimpleParameterList &= isSimpleParameter;
242 SourceParseMode parseMode = codeBlock->parseMode();
244 bool containsArrowOrEvalButNotInArrowBlock = ((functionNode->usesArrowFunction() && functionNode->doAnyInnerArrowFunctionsUseAnyFeature()) || functionNode->usesEval()) && !m_codeBlock->isArrowFunction();
245 bool shouldCaptureSomeOfTheThings = m_shouldEmitDebugHooks || functionNode->needsActivation() || containsArrowOrEvalButNotInArrowBlock;
247 bool shouldCaptureAllOfTheThings = m_shouldEmitDebugHooks || codeBlock->usesEval();
248 bool needsArguments = (functionNode->usesArguments() || codeBlock->usesEval() || (functionNode->usesArrowFunction() && !codeBlock->isArrowFunction() && isArgumentsUsedInInnerArrowFunction()));
250 // Generator never provides "arguments". "arguments" reference will be resolved in an upper generator function scope.
251 if (parseMode == SourceParseMode::GeneratorBodyMode)
252 needsArguments = false;
254 if (parseMode == SourceParseMode::GeneratorWrapperFunctionMode && needsArguments) {
255 // Generator does not provide "arguments". Instead, wrapping GeneratorFunction provides "arguments".
256 // This is because arguments of a generator should be evaluated before starting it.
257 // To workaround it, we evaluate these arguments as arguments of a wrapping generator function, and reference it from a generator.
259 // function *gen(a, b = hello())
262 // @generatorNext: function (@generator, @generatorState, @generatorValue, @generatorResumeMode)
264 // arguments; // This `arguments` should reference to the gen's arguments.
269 shouldCaptureSomeOfTheThings = true;
272 if (shouldCaptureAllOfTheThings)
273 functionNode->varDeclarations().markAllVariablesAsCaptured();
275 auto captures = [&] (UniquedStringImpl* uid) -> bool {
276 if (!shouldCaptureSomeOfTheThings)
278 if (needsArguments && uid == propertyNames().arguments.impl()) {
279 // Actually, we only need to capture the arguments object when we "need full activation"
280 // because of name scopes. But historically we did it this way, so for now we just preserve
282 // FIXME: https://bugs.webkit.org/show_bug.cgi?id=143072
285 return functionNode->captures(uid);
287 auto varKind = [&] (UniquedStringImpl* uid) -> VarKind {
288 return captures(uid) ? VarKind::Scope : VarKind::Stack;
293 allocateAndEmitScope();
295 m_calleeRegister.setIndex(JSStack::Callee);
297 initializeParameters(parameters);
298 ASSERT(!(isSimpleParameterList && m_restParameter));
300 // Before emitting a scope creation, emit a generator prologue that contains jump based on a generator's state.
301 if (parseMode == SourceParseMode::GeneratorBodyMode) {
302 m_generatorRegister = &m_parameters[1];
304 // Jump with switch_imm based on @generatorState. We don't take the coroutine styled generator implementation.
305 // When calling `next()`, we would like to enter the same prologue instead of jumping based on the saved instruction pointer.
306 // It's suitale for inlining, because it just inlines one `next` function implementation.
308 beginGenerator(generatorStateRegister());
311 emitGeneratorStateLabel();
314 if (functionNameIsInScope(functionNode->ident(), functionNode->functionMode())) {
315 ASSERT(parseMode != SourceParseMode::GeneratorBodyMode);
316 bool isDynamicScope = functionNameScopeIsDynamic(codeBlock->usesEval(), codeBlock->isStrictMode());
317 bool isFunctionNameCaptured = captures(functionNode->ident().impl());
318 bool markAsCaptured = isDynamicScope || isFunctionNameCaptured;
319 emitPushFunctionNameScope(functionNode->ident(), &m_calleeRegister, markAsCaptured);
322 if (shouldCaptureSomeOfTheThings)
323 m_lexicalEnvironmentRegister = addVar();
325 if (shouldCaptureSomeOfTheThings || vm.typeProfiler())
326 symbolTableConstantIndex = addConstantValue(functionSymbolTable)->index();
328 // We can allocate the "var" environment if we don't have default parameter expressions. If we have
329 // default parameter expressions, we have to hold off on allocating the "var" environment because
330 // the parent scope of the "var" environment is the parameter environment.
331 if (isSimpleParameterList)
332 initializeVarLexicalEnvironment(symbolTableConstantIndex, functionSymbolTable, shouldCaptureSomeOfTheThings);
334 // Figure out some interesting facts about our arguments.
335 bool capturesAnyArgumentByName = false;
336 if (functionNode->hasCapturedVariables()) {
337 FunctionParameters& parameters = *functionNode->parameters();
338 for (size_t i = 0; i < parameters.size(); ++i) {
339 auto pattern = parameters.at(i).first;
340 if (!pattern->isBindingNode())
342 const Identifier& ident = static_cast<const BindingNode*>(pattern)->boundProperty();
343 capturesAnyArgumentByName |= captures(ident.impl());
347 if (capturesAnyArgumentByName)
348 ASSERT(m_lexicalEnvironmentRegister);
350 // Need to know what our functions are called. Parameters have some goofy behaviors when it
351 // comes to functions of the same name.
352 for (FunctionMetadataNode* function : functionNode->functionStack())
353 m_functions.add(function->ident().impl());
355 if (needsArguments) {
356 // Create the arguments object now. We may put the arguments object into the activation if
357 // it is captured. Either way, we create two arguments object variables: one is our
358 // private variable that is immutable, and another that is the user-visible variable. The
359 // immutable one is only used here, or during formal parameter resolutions if we opt for
362 m_argumentsRegister = addVar();
363 m_argumentsRegister->ref();
366 if (needsArguments && !codeBlock->isStrictMode() && isSimpleParameterList) {
367 // If we captured any formal parameter by name, then we use ScopedArguments. Otherwise we
368 // use DirectArguments. With ScopedArguments, we lift all of our arguments into the
371 ConcurrentJITLocker locker(ConcurrentJITLocker::NoLockingNecessary);
372 if (capturesAnyArgumentByName) {
373 functionSymbolTable->setArgumentsLength(vm, parameters.size());
375 // For each parameter, we have two possibilities:
376 // Either it's a binding node with no function overlap, in which case it gets a name
377 // in the symbol table - or it just gets space reserved in the symbol table. Either
378 // way we lift the value into the scope.
379 for (unsigned i = 0; i < parameters.size(); ++i) {
380 ScopeOffset offset = functionSymbolTable->takeNextScopeOffset(locker);
381 functionSymbolTable->setArgumentOffset(vm, i, offset);
382 if (UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first)) {
383 VarOffset varOffset(offset);
384 SymbolTableEntry entry(varOffset);
385 // Stores to these variables via the ScopedArguments object will not do
386 // notifyWrite(), since that would be cumbersome. Also, watching formal
387 // parameters when "arguments" is in play is unlikely to be super profitable.
388 // So, we just disable it.
389 entry.disableWatching();
390 functionSymbolTable->set(locker, name, entry);
392 emitOpcode(op_put_to_scope);
393 instructions().append(m_lexicalEnvironmentRegister->index());
394 instructions().append(UINT_MAX);
395 instructions().append(virtualRegisterForArgument(1 + i).offset());
396 instructions().append(GetPutInfo(ThrowIfNotFound, LocalClosureVar, InitializationMode::NotInitialization).operand());
397 instructions().append(symbolTableConstantIndex);
398 instructions().append(offset.offset());
401 // This creates a scoped arguments object and copies the overflow arguments into the
402 // scope. It's the equivalent of calling ScopedArguments::createByCopying().
403 emitOpcode(op_create_scoped_arguments);
404 instructions().append(m_argumentsRegister->index());
405 instructions().append(m_lexicalEnvironmentRegister->index());
407 // We're going to put all parameters into the DirectArguments object. First ensure
408 // that the symbol table knows that this is happening.
409 for (unsigned i = 0; i < parameters.size(); ++i) {
410 if (UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first))
411 functionSymbolTable->set(locker, name, SymbolTableEntry(VarOffset(DirectArgumentsOffset(i))));
414 emitOpcode(op_create_direct_arguments);
415 instructions().append(m_argumentsRegister->index());
417 } else if (isSimpleParameterList) {
418 // Create the formal parameters the normal way. Any of them could be captured, or not. If
419 // captured, lift them into the scope. We cannot do this if we have default parameter expressions
420 // because when default parameter expressions exist, they belong in their own lexical environment
421 // separate from the "var" lexical environment.
422 ConcurrentJITLocker locker(ConcurrentJITLocker::NoLockingNecessary);
423 for (unsigned i = 0; i < parameters.size(); ++i) {
424 UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first);
428 if (!captures(name)) {
429 // This is the easy case - just tell the symbol table about the argument. It will
430 // be accessed directly.
431 functionSymbolTable->set(locker, name, SymbolTableEntry(VarOffset(virtualRegisterForArgument(1 + i))));
435 ScopeOffset offset = functionSymbolTable->takeNextScopeOffset(locker);
436 const Identifier& ident =
437 static_cast<const BindingNode*>(parameters.at(i).first)->boundProperty();
438 functionSymbolTable->set(locker, name, SymbolTableEntry(VarOffset(offset)));
440 emitOpcode(op_put_to_scope);
441 instructions().append(m_lexicalEnvironmentRegister->index());
442 instructions().append(addConstant(ident));
443 instructions().append(virtualRegisterForArgument(1 + i).offset());
444 instructions().append(GetPutInfo(ThrowIfNotFound, LocalClosureVar, InitializationMode::NotInitialization).operand());
445 instructions().append(symbolTableConstantIndex);
446 instructions().append(offset.offset());
450 if (needsArguments && (codeBlock->isStrictMode() || !isSimpleParameterList)) {
451 // Allocate a cloned arguments object.
452 emitOpcode(op_create_cloned_arguments);
453 instructions().append(m_argumentsRegister->index());
456 // There are some variables that need to be preinitialized to something other than Undefined:
458 // - "arguments": unless it's used as a function or parameter, this should refer to the
461 // - functions: these always override everything else.
463 // The most logical way to do all of this is to initialize none of the variables until now,
464 // and then initialize them in BytecodeGenerator::generate() in such an order that the rules
465 // for how these things override each other end up holding. We would initialize "arguments" first,
466 // then all arguments, then the functions.
468 // But some arguments are already initialized by default, since if they aren't captured and we
469 // don't have "arguments" then we just point the symbol table at the stack slot of those
470 // arguments. We end up initializing the rest of the arguments that have an uncomplicated
471 // binding (i.e. don't involve destructuring) above when figuring out how to lay them out,
472 // because that's just the simplest thing. This means that when we initialize them, we have to
473 // watch out for the things that override arguments (namely, functions).
475 // This is our final act of weirdness. "arguments" is overridden by everything except the
476 // callee. We add it to the symbol table if it's not already there and it's not an argument.
477 bool shouldCreateArgumentsVariableInParameterScope = false;
478 if (needsArguments) {
479 // If "arguments" is overridden by a function or destructuring parameter name, then it's
480 // OK for us to call createVariable() because it won't change anything. It's also OK for
481 // us to them tell BytecodeGenerator::generate() to write to it because it will do so
482 // before it initializes functions and destructuring parameters. But if "arguments" is
483 // overridden by a "simple" function parameter, then we have to bail: createVariable()
484 // would assert and BytecodeGenerator::generate() would write the "arguments" after the
485 // argument value had already been properly initialized.
487 bool haveParameterNamedArguments = false;
488 for (unsigned i = 0; i < parameters.size(); ++i) {
489 UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first);
490 if (name == propertyNames().arguments.impl()) {
491 haveParameterNamedArguments = true;
496 bool shouldCreateArgumensVariable = !haveParameterNamedArguments && !m_codeBlock->isArrowFunction();
497 shouldCreateArgumentsVariableInParameterScope = shouldCreateArgumensVariable && !isSimpleParameterList;
498 // Do not create arguments variable in case of Arrow function. Value will be loaded from parent scope
499 if (shouldCreateArgumensVariable && !shouldCreateArgumentsVariableInParameterScope) {
501 propertyNames().arguments, varKind(propertyNames().arguments.impl()), functionSymbolTable);
503 m_needToInitializeArguments = true;
507 for (FunctionMetadataNode* function : functionNode->functionStack()) {
508 const Identifier& ident = function->ident();
509 createVariable(ident, varKind(ident.impl()), functionSymbolTable);
510 m_functionsToInitialize.append(std::make_pair(function, NormalFunctionVariable));
512 for (auto& entry : functionNode->varDeclarations()) {
513 ASSERT(!entry.value.isLet() && !entry.value.isConst());
514 if (!entry.value.isVar()) // This is either a parameter or callee.
516 if (shouldCreateArgumentsVariableInParameterScope && entry.key.get() == propertyNames().arguments.impl())
518 createVariable(Identifier::fromUid(m_vm, entry.key.get()), varKind(entry.key.get()), functionSymbolTable, IgnoreExisting);
522 m_newTargetRegister = addVar();
524 case SourceParseMode::GeneratorWrapperFunctionMode: {
525 m_generatorRegister = addVar();
527 // FIXME: Emit to_this only when Generator uses it.
528 // https://bugs.webkit.org/show_bug.cgi?id=151586
529 m_codeBlock->addPropertyAccessInstruction(instructions().size());
530 emitOpcode(op_to_this);
531 instructions().append(kill(&m_thisRegister));
532 instructions().append(0);
533 instructions().append(0);
535 emitMove(m_generatorRegister, &m_calleeRegister);
536 emitCreateThis(m_generatorRegister);
540 case SourceParseMode::GeneratorBodyMode: {
541 // |this| is already filled correctly before here.
542 emitLoad(m_newTargetRegister, jsUndefined());
547 if (SourceParseMode::ArrowFunctionMode != parseMode) {
548 if (isConstructor()) {
549 emitMove(m_newTargetRegister, &m_thisRegister);
550 if (constructorKind() == ConstructorKind::Derived)
551 emitMoveEmptyValue(&m_thisRegister);
553 emitCreateThis(&m_thisRegister);
554 } else if (constructorKind() != ConstructorKind::None) {
555 emitThrowTypeError("Cannot call a class constructor");
556 } else if (functionNode->usesThis() || codeBlock->usesEval()) {
557 m_codeBlock->addPropertyAccessInstruction(instructions().size());
558 emitOpcode(op_to_this);
559 instructions().append(kill(&m_thisRegister));
560 instructions().append(0);
561 instructions().append(0);
568 // We need load |super| & |this| for arrow function before initializeDefaultParameterValuesAndSetupFunctionScopeStack
569 // if we have default parameter expression. Because |super| & |this| values can be used there
570 if (SourceParseMode::ArrowFunctionMode == parseMode && !isSimpleParameterList) {
571 if (functionNode->usesThis() || functionNode->usesSuperProperty())
572 emitLoadThisFromArrowFunctionLexicalEnvironment();
574 if (m_scopeNode->usesNewTarget() || m_scopeNode->usesSuperCall())
575 emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
578 if (needsToUpdateArrowFunctionContext() && !codeBlock->isArrowFunction()) {
579 bool canReuseLexicalEnvironment = isSimpleParameterList;
580 initializeArrowFunctionContextScopeIfNeeded(functionSymbolTable, canReuseLexicalEnvironment);
581 emitPutThisToArrowFunctionContextScope();
582 emitPutNewTargetToArrowFunctionContextScope();
583 emitPutDerivedConstructorToArrowFunctionContextScope();
586 // All "addVar()"s needs to happen before "initializeDefaultParameterValuesAndSetupFunctionScopeStack()" is called
587 // because a function's default parameter ExpressionNodes will use temporary registers.
588 pushTDZVariables(*parentScopeTDZVariables, TDZCheckOptimization::DoNotOptimize);
589 initializeDefaultParameterValuesAndSetupFunctionScopeStack(parameters, isSimpleParameterList, functionNode, functionSymbolTable, symbolTableConstantIndex, captures, shouldCreateArgumentsVariableInParameterScope);
591 // If we don't have default parameter expression, then loading |this| inside an arrow function must be done
592 // after initializeDefaultParameterValuesAndSetupFunctionScopeStack() because that function sets up the
593 // SymbolTable stack and emitLoadThisFromArrowFunctionLexicalEnvironment() consults the SymbolTable stack
594 if (SourceParseMode::ArrowFunctionMode == parseMode && isSimpleParameterList) {
595 if (functionNode->usesThis() || functionNode->usesSuperProperty())
596 emitLoadThisFromArrowFunctionLexicalEnvironment();
598 if (m_scopeNode->usesNewTarget() || m_scopeNode->usesSuperCall())
599 emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
602 bool shouldInitializeBlockScopedFunctions = false; // We generate top-level function declarations in ::generate().
603 pushLexicalScope(m_scopeNode, TDZCheckOptimization::Optimize, NestedScopeType::IsNotNested, nullptr, shouldInitializeBlockScopedFunctions);
606 BytecodeGenerator::BytecodeGenerator(VM& vm, EvalNode* evalNode, UnlinkedEvalCodeBlock* codeBlock, DebuggerMode debuggerMode, const VariableEnvironment* parentScopeTDZVariables)
607 : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
608 , m_scopeNode(evalNode)
609 , m_codeBlock(vm, codeBlock)
610 , m_thisRegister(CallFrame::thisArgumentOffset())
611 , m_codeType(EvalCode)
613 , m_usesNonStrictEval(codeBlock->usesEval() && !codeBlock->isStrictMode())
614 , m_needsToUpdateArrowFunctionContext(evalNode->usesArrowFunction() || evalNode->usesEval())
615 , m_derivedContextType(codeBlock->derivedContextType())
617 for (auto& constantRegister : m_linkTimeConstantRegisters)
618 constantRegister = nullptr;
620 allocateCalleeSaveSpace();
622 m_codeBlock->setNumParameters(1);
626 allocateAndEmitScope();
628 const DeclarationStacks::FunctionStack& functionStack = evalNode->functionStack();
629 for (size_t i = 0; i < functionStack.size(); ++i)
630 m_codeBlock->addFunctionDecl(makeFunction(functionStack[i]));
632 const VariableEnvironment& varDeclarations = evalNode->varDeclarations();
633 unsigned numVariables = varDeclarations.size();
634 Vector<Identifier, 0, UnsafeVectorOverflow> variables;
635 variables.reserveCapacity(numVariables);
636 for (auto& entry : varDeclarations) {
637 ASSERT(entry.value.isVar());
638 ASSERT(entry.key->isAtomic() || entry.key->isSymbol());
639 variables.append(Identifier::fromUid(m_vm, entry.key.get()));
641 codeBlock->adoptVariables(variables);
643 if (evalNode->usesSuperCall() || evalNode->usesNewTarget())
644 m_newTargetRegister = addVar();
646 pushTDZVariables(*parentScopeTDZVariables, TDZCheckOptimization::DoNotOptimize);
648 if (codeBlock->isArrowFunctionContext() && (evalNode->usesThis() || evalNode->usesSuperProperty()))
649 emitLoadThisFromArrowFunctionLexicalEnvironment();
651 if (evalNode->usesSuperCall() || evalNode->usesNewTarget())
652 emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
654 if (needsToUpdateArrowFunctionContext() && !codeBlock->isArrowFunctionContext() && !isDerivedConstructorContext()) {
655 initializeArrowFunctionContextScopeIfNeeded();
656 emitPutThisToArrowFunctionContextScope();
659 bool shouldInitializeBlockScopedFunctions = false; // We generate top-level function declarations in ::generate().
660 pushLexicalScope(m_scopeNode, TDZCheckOptimization::Optimize, NestedScopeType::IsNotNested, nullptr, shouldInitializeBlockScopedFunctions);
663 BytecodeGenerator::BytecodeGenerator(VM& vm, ModuleProgramNode* moduleProgramNode, UnlinkedModuleProgramCodeBlock* codeBlock, DebuggerMode debuggerMode, const VariableEnvironment* parentScopeTDZVariables)
664 : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
665 , m_scopeNode(moduleProgramNode)
666 , m_codeBlock(vm, codeBlock)
667 , m_thisRegister(CallFrame::thisArgumentOffset())
668 , m_codeType(ModuleCode)
670 , m_usesNonStrictEval(false)
671 , m_needsToUpdateArrowFunctionContext(moduleProgramNode->usesArrowFunction() || moduleProgramNode->usesEval())
673 ASSERT_UNUSED(parentScopeTDZVariables, !parentScopeTDZVariables->size());
675 for (auto& constantRegister : m_linkTimeConstantRegisters)
676 constantRegister = nullptr;
678 if (m_isBuiltinFunction)
679 m_shouldEmitDebugHooks = false;
681 allocateCalleeSaveSpace();
683 SymbolTable* moduleEnvironmentSymbolTable = SymbolTable::create(*m_vm);
684 moduleEnvironmentSymbolTable->setUsesNonStrictEval(m_usesNonStrictEval);
685 moduleEnvironmentSymbolTable->setScopeType(SymbolTable::ScopeType::LexicalScope);
687 bool shouldCaptureAllOfTheThings = m_shouldEmitDebugHooks || codeBlock->usesEval();
688 if (shouldCaptureAllOfTheThings)
689 moduleProgramNode->varDeclarations().markAllVariablesAsCaptured();
691 auto captures = [&] (UniquedStringImpl* uid) -> bool {
692 return moduleProgramNode->captures(uid);
694 auto lookUpVarKind = [&] (UniquedStringImpl* uid, const VariableEnvironmentEntry& entry) -> VarKind {
695 // Allocate the exported variables in the module environment.
696 if (entry.isExported())
697 return VarKind::Scope;
699 // Allocate the namespace variables in the module environment to instantiate
700 // it from the outside of the module code.
701 if (entry.isImportedNamespace())
702 return VarKind::Scope;
704 if (entry.isCaptured())
705 return VarKind::Scope;
706 return captures(uid) ? VarKind::Scope : VarKind::Stack;
711 allocateAndEmitScope();
713 m_calleeRegister.setIndex(JSStack::Callee);
715 m_codeBlock->setNumParameters(1); // Allocate space for "this"
717 // Now declare all variables.
719 for (auto& entry : moduleProgramNode->varDeclarations()) {
720 ASSERT(!entry.value.isLet() && !entry.value.isConst());
721 if (!entry.value.isVar()) // This is either a parameter or callee.
723 // Imported bindings are not allocated in the module environment as usual variables' way.
724 // These references remain the "Dynamic" in the unlinked code block. Later, when linking
725 // the code block, we resolve the reference to the "ModuleVar".
726 if (entry.value.isImported() && !entry.value.isImportedNamespace())
728 createVariable(Identifier::fromUid(m_vm, entry.key.get()), lookUpVarKind(entry.key.get(), entry.value), moduleEnvironmentSymbolTable, IgnoreExisting);
731 VariableEnvironment& lexicalVariables = moduleProgramNode->lexicalVariables();
732 instantiateLexicalVariables(lexicalVariables, moduleEnvironmentSymbolTable, ScopeRegisterType::Block, lookUpVarKind);
734 // We keep the symbol table in the constant pool.
735 RegisterID* constantSymbolTable = nullptr;
736 if (vm.typeProfiler())
737 constantSymbolTable = addConstantValue(moduleEnvironmentSymbolTable);
739 constantSymbolTable = addConstantValue(moduleEnvironmentSymbolTable->cloneScopePart(*m_vm));
741 pushTDZVariables(lexicalVariables, TDZCheckOptimization::Optimize);
742 bool isWithScope = false;
743 m_symbolTableStack.append(SymbolTableStackEntry { moduleEnvironmentSymbolTable, m_topMostScope, isWithScope, constantSymbolTable->index() });
744 emitPrefillStackTDZVariables(lexicalVariables, moduleEnvironmentSymbolTable);
746 // makeFunction assumes that there's correct TDZ stack entries.
747 // So it should be called after putting our lexical environment to the TDZ stack correctly.
749 for (FunctionMetadataNode* function : moduleProgramNode->functionStack()) {
750 const auto& iterator = moduleProgramNode->varDeclarations().find(function->ident().impl());
751 RELEASE_ASSERT(iterator != moduleProgramNode->varDeclarations().end());
752 RELEASE_ASSERT(!iterator->value.isImported());
754 VarKind varKind = lookUpVarKind(iterator->key.get(), iterator->value);
755 if (varKind == VarKind::Scope) {
756 // http://www.ecma-international.org/ecma-262/6.0/#sec-moduledeclarationinstantiation
757 // Section 15.2.1.16.4, step 16-a-iv-1.
758 // All heap allocated function declarations should be instantiated when the module environment
759 // is created. They include the exported function declarations and not-exported-but-heap-allocated
760 // function declarations. This is required because exported function should be instantiated before
761 // executing the any module in the dependency graph. This enables the modules to link the imported
762 // bindings before executing the any module code.
764 // And since function declarations are instantiated before executing the module body code, the spec
765 // allows the functions inside the module to be executed before its module body is executed under
766 // the circular dependencies. The following is the example.
768 // Module A (executed first):
769 // import { b } from "B";
770 // // Here, the module "B" is not executed yet, but the function declaration is already instantiated.
771 // // So we can call the function exported from "B".
774 // export function a() {
777 // Module B (executed second):
778 // import { a } from "A";
780 // export function b() {
784 // // c is not exported, but since it is referenced from the b, we should instantiate it before
785 // // executing the "B" module code.
790 // Module EntryPoint (executed last):
794 m_codeBlock->addFunctionDecl(makeFunction(function));
796 // Stack allocated functions can be allocated when executing the module's body.
797 m_functionsToInitialize.append(std::make_pair(function, NormalFunctionVariable));
801 // Remember the constant register offset to the top-most symbol table. This symbol table will be
802 // cloned in the code block linking. After that, to create the module environment, we retrieve
803 // the cloned symbol table from the linked code block by using this offset.
804 codeBlock->setModuleEnvironmentSymbolTableConstantRegisterOffset(constantSymbolTable->index());
807 BytecodeGenerator::~BytecodeGenerator()
811 void BytecodeGenerator::initializeDefaultParameterValuesAndSetupFunctionScopeStack(
812 FunctionParameters& parameters, bool isSimpleParameterList, FunctionNode* functionNode, SymbolTable* functionSymbolTable,
813 int symbolTableConstantIndex, const std::function<bool (UniquedStringImpl*)>& captures, bool shouldCreateArgumentsVariableInParameterScope)
815 Vector<std::pair<Identifier, RefPtr<RegisterID>>> valuesToMoveIntoVars;
816 ASSERT(!(isSimpleParameterList && shouldCreateArgumentsVariableInParameterScope));
817 if (!isSimpleParameterList) {
818 // Refer to the ES6 spec section 9.2.12: http://www.ecma-international.org/ecma-262/6.0/index.html#sec-functiondeclarationinstantiation
819 // This implements step 21.
820 VariableEnvironment environment;
821 Vector<Identifier> allParameterNames;
822 for (unsigned i = 0; i < parameters.size(); i++)
823 parameters.at(i).first->collectBoundIdentifiers(allParameterNames);
824 if (shouldCreateArgumentsVariableInParameterScope)
825 allParameterNames.append(propertyNames().arguments);
826 IdentifierSet parameterSet;
827 for (auto& ident : allParameterNames) {
828 parameterSet.add(ident.impl());
829 auto addResult = environment.add(ident);
830 addResult.iterator->value.setIsLet(); // When we have default parameter expressions, parameters act like "let" variables.
831 if (captures(ident.impl()))
832 addResult.iterator->value.setIsCaptured();
834 // This implements step 25 of section 9.2.12.
835 pushLexicalScopeInternal(environment, TDZCheckOptimization::Optimize, NestedScopeType::IsNotNested, nullptr, TDZRequirement::UnderTDZ, ScopeType::LetConstScope, ScopeRegisterType::Block);
837 if (shouldCreateArgumentsVariableInParameterScope) {
838 Variable argumentsVariable = variable(propertyNames().arguments);
839 initializeVariable(argumentsVariable, m_argumentsRegister);
840 liftTDZCheckIfPossible(argumentsVariable);
843 RefPtr<RegisterID> temp = newTemporary();
844 for (unsigned i = 0; i < parameters.size(); i++) {
845 std::pair<DestructuringPatternNode*, ExpressionNode*> parameter = parameters.at(i);
846 if (parameter.first->isRestParameter())
848 RefPtr<RegisterID> parameterValue = ®isterFor(virtualRegisterForArgument(1 + i));
849 emitMove(temp.get(), parameterValue.get());
850 if (parameter.second) {
851 RefPtr<RegisterID> condition = emitIsUndefined(newTemporary(), parameterValue.get());
852 RefPtr<Label> skipDefaultParameterBecauseNotUndefined = newLabel();
853 emitJumpIfFalse(condition.get(), skipDefaultParameterBecauseNotUndefined.get());
854 emitNode(temp.get(), parameter.second);
855 emitLabel(skipDefaultParameterBecauseNotUndefined.get());
858 parameter.first->bindValue(*this, temp.get());
861 // Final act of weirdness for default parameters. If a "var" also
862 // has the same name as a parameter, it should start out as the
863 // value of that parameter. Note, though, that they will be distinct
865 // This is step 28 of section 9.2.12.
866 for (auto& entry : functionNode->varDeclarations()) {
867 if (!entry.value.isVar()) // This is either a parameter or callee.
870 if (parameterSet.contains(entry.key)) {
871 Identifier ident = Identifier::fromUid(m_vm, entry.key.get());
872 Variable var = variable(ident);
873 RegisterID* scope = emitResolveScope(nullptr, var);
874 RefPtr<RegisterID> value = emitGetFromScope(newTemporary(), scope, var, DoNotThrowIfNotFound);
875 valuesToMoveIntoVars.append(std::make_pair(ident, value));
879 // Functions with default parameter expressions must have a separate environment
880 // record for parameters and "var"s. The "var" environment record must have the
881 // parameter environment record as its parent.
882 // See step 28 of section 9.2.12.
883 bool hasCapturedVariables = !!m_lexicalEnvironmentRegister;
884 initializeVarLexicalEnvironment(symbolTableConstantIndex, functionSymbolTable, hasCapturedVariables);
887 // This completes step 28 of section 9.2.12.
888 for (unsigned i = 0; i < valuesToMoveIntoVars.size(); i++) {
889 ASSERT(!isSimpleParameterList);
890 Variable var = variable(valuesToMoveIntoVars[i].first);
891 RegisterID* scope = emitResolveScope(nullptr, var);
892 emitPutToScope(scope, var, valuesToMoveIntoVars[i].second.get(), DoNotThrowIfNotFound, InitializationMode::NotInitialization);
896 void BytecodeGenerator::initializeArrowFunctionContextScopeIfNeeded(SymbolTable* functionSymbolTable, bool canReuseLexicalEnvironment)
898 ASSERT(!m_arrowFunctionContextLexicalEnvironmentRegister);
900 if (canReuseLexicalEnvironment && m_lexicalEnvironmentRegister) {
901 RELEASE_ASSERT(!m_codeBlock->isArrowFunction());
902 RELEASE_ASSERT(functionSymbolTable);
904 m_arrowFunctionContextLexicalEnvironmentRegister = m_lexicalEnvironmentRegister;
908 ConcurrentJITLocker locker(ConcurrentJITLocker::NoLockingNecessary);
909 if (isThisUsedInInnerArrowFunction()) {
910 offset = functionSymbolTable->takeNextScopeOffset(locker);
911 functionSymbolTable->set(locker, propertyNames().thisIdentifier.impl(), SymbolTableEntry(VarOffset(offset)));
914 if (m_codeType == FunctionCode && isNewTargetUsedInInnerArrowFunction()) {
915 offset = functionSymbolTable->takeNextScopeOffset();
916 functionSymbolTable->set(locker, propertyNames().newTargetLocalPrivateName.impl(), SymbolTableEntry(VarOffset(offset)));
919 if (isConstructor() && constructorKind() == ConstructorKind::Derived && isSuperUsedInInnerArrowFunction()) {
920 offset = functionSymbolTable->takeNextScopeOffset(locker);
921 functionSymbolTable->set(locker, propertyNames().derivedConstructorPrivateName.impl(), SymbolTableEntry(VarOffset(offset)));
927 VariableEnvironment environment;
929 if (isThisUsedInInnerArrowFunction()) {
930 auto addResult = environment.add(propertyNames().thisIdentifier);
931 addResult.iterator->value.setIsCaptured();
932 addResult.iterator->value.setIsLet();
935 if (m_codeType == FunctionCode && isNewTargetUsedInInnerArrowFunction()) {
936 auto addTarget = environment.add(propertyNames().newTargetLocalPrivateName);
937 addTarget.iterator->value.setIsCaptured();
938 addTarget.iterator->value.setIsLet();
941 if (isConstructor() && constructorKind() == ConstructorKind::Derived && isSuperUsedInInnerArrowFunction()) {
942 auto derivedConstructor = environment.add(propertyNames().derivedConstructorPrivateName);
943 derivedConstructor.iterator->value.setIsCaptured();
944 derivedConstructor.iterator->value.setIsLet();
947 if (environment.size() > 0) {
948 size_t size = m_symbolTableStack.size();
949 pushLexicalScopeInternal(environment, TDZCheckOptimization::Optimize, NestedScopeType::IsNotNested, nullptr, TDZRequirement::UnderTDZ, ScopeType::LetConstScope, ScopeRegisterType::Block);
951 ASSERT_UNUSED(size, m_symbolTableStack.size() == size + 1);
953 m_arrowFunctionContextLexicalEnvironmentRegister = m_symbolTableStack.last().m_scope;
957 RegisterID* BytecodeGenerator::initializeNextParameter()
959 VirtualRegister reg = virtualRegisterForArgument(m_codeBlock->numParameters());
960 RegisterID& parameter = registerFor(reg);
961 parameter.setIndex(reg.offset());
962 m_codeBlock->addParameter();
966 void BytecodeGenerator::initializeParameters(FunctionParameters& parameters)
968 // Make sure the code block knows about all of our parameters, and make sure that parameters
969 // needing destructuring are noted.
970 m_parameters.grow(parameters.size() + 1); // reserve space for "this"
971 m_thisRegister.setIndex(initializeNextParameter()->index()); // this
972 for (unsigned i = 0; i < parameters.size(); ++i) {
973 auto pattern = parameters.at(i).first;
974 if (pattern->isRestParameter()) {
975 RELEASE_ASSERT(!m_restParameter);
976 m_restParameter = static_cast<RestParameterNode*>(pattern);
978 initializeNextParameter();
982 void BytecodeGenerator::initializeVarLexicalEnvironment(int symbolTableConstantIndex, SymbolTable* functionSymbolTable, bool hasCapturedVariables)
984 if (hasCapturedVariables) {
985 RELEASE_ASSERT(m_lexicalEnvironmentRegister);
986 emitOpcode(op_create_lexical_environment);
987 instructions().append(m_lexicalEnvironmentRegister->index());
988 instructions().append(scopeRegister()->index());
989 instructions().append(symbolTableConstantIndex);
990 instructions().append(addConstantValue(jsUndefined())->index());
993 instructions().append(scopeRegister()->index());
994 instructions().append(m_lexicalEnvironmentRegister->index());
996 pushScopedControlFlowContext();
998 bool isWithScope = false;
999 m_symbolTableStack.append(SymbolTableStackEntry{ functionSymbolTable, m_lexicalEnvironmentRegister, isWithScope, symbolTableConstantIndex });
1000 m_varScopeSymbolTableIndex = m_symbolTableStack.size() - 1;
1003 UniquedStringImpl* BytecodeGenerator::visibleNameForParameter(DestructuringPatternNode* pattern)
1005 if (pattern->isBindingNode()) {
1006 const Identifier& ident = static_cast<const BindingNode*>(pattern)->boundProperty();
1007 if (!m_functions.contains(ident.impl()))
1008 return ident.impl();
1013 RegisterID* BytecodeGenerator::newRegister()
1015 m_calleeLocals.append(virtualRegisterForLocal(m_calleeLocals.size()));
1016 int numCalleeLocals = max<int>(m_codeBlock->m_numCalleeLocals, m_calleeLocals.size());
1017 numCalleeLocals = WTF::roundUpToMultipleOf(stackAlignmentRegisters(), numCalleeLocals);
1018 m_codeBlock->m_numCalleeLocals = numCalleeLocals;
1019 return &m_calleeLocals.last();
1022 void BytecodeGenerator::reclaimFreeRegisters()
1024 while (m_calleeLocals.size() && !m_calleeLocals.last().refCount())
1025 m_calleeLocals.removeLast();
1028 RegisterID* BytecodeGenerator::newBlockScopeVariable()
1030 reclaimFreeRegisters();
1032 return newRegister();
1035 RegisterID* BytecodeGenerator::newTemporary()
1037 reclaimFreeRegisters();
1039 RegisterID* result = newRegister();
1040 result->setTemporary();
1044 LabelScopePtr BytecodeGenerator::newLabelScope(LabelScope::Type type, const Identifier* name)
1046 // Reclaim free label scopes.
1047 while (m_labelScopes.size() && !m_labelScopes.last().refCount())
1048 m_labelScopes.removeLast();
1050 // Allocate new label scope.
1051 LabelScope scope(type, name, labelScopeDepth(), newLabel(), type == LabelScope::Loop ? newLabel() : PassRefPtr<Label>()); // Only loops have continue targets.
1052 m_labelScopes.append(scope);
1053 return LabelScopePtr(m_labelScopes, m_labelScopes.size() - 1);
1056 PassRefPtr<Label> BytecodeGenerator::newLabel()
1058 // Reclaim free label IDs.
1059 while (m_labels.size() && !m_labels.last().refCount())
1060 m_labels.removeLast();
1062 // Allocate new label ID.
1063 m_labels.append(*this);
1064 return &m_labels.last();
1067 PassRefPtr<Label> BytecodeGenerator::emitLabel(Label* l0)
1069 unsigned newLabelIndex = instructions().size();
1070 l0->setLocation(newLabelIndex);
1072 if (m_codeBlock->numberOfJumpTargets()) {
1073 unsigned lastLabelIndex = m_codeBlock->lastJumpTarget();
1074 ASSERT(lastLabelIndex <= newLabelIndex);
1075 if (newLabelIndex == lastLabelIndex) {
1076 // Peephole optimizations have already been disabled by emitting the last label
1081 m_codeBlock->addJumpTarget(newLabelIndex);
1083 // This disables peephole optimizations when an instruction is a jump target
1084 m_lastOpcodeID = op_end;
1088 void BytecodeGenerator::emitOpcode(OpcodeID opcodeID)
1091 size_t opcodePosition = instructions().size();
1092 ASSERT(opcodePosition - m_lastOpcodePosition == opcodeLength(m_lastOpcodeID) || m_lastOpcodeID == op_end);
1093 m_lastOpcodePosition = opcodePosition;
1095 instructions().append(opcodeID);
1096 m_lastOpcodeID = opcodeID;
1099 UnlinkedArrayProfile BytecodeGenerator::newArrayProfile()
1101 return m_codeBlock->addArrayProfile();
1104 UnlinkedArrayAllocationProfile BytecodeGenerator::newArrayAllocationProfile()
1106 return m_codeBlock->addArrayAllocationProfile();
1109 UnlinkedObjectAllocationProfile BytecodeGenerator::newObjectAllocationProfile()
1111 return m_codeBlock->addObjectAllocationProfile();
1114 UnlinkedValueProfile BytecodeGenerator::emitProfiledOpcode(OpcodeID opcodeID)
1116 UnlinkedValueProfile result = m_codeBlock->addValueProfile();
1117 emitOpcode(opcodeID);
1121 void BytecodeGenerator::emitEnter()
1123 emitOpcode(op_enter);
1127 void BytecodeGenerator::emitLoopHint()
1129 emitOpcode(op_loop_hint);
1133 void BytecodeGenerator::emitWatchdog()
1135 if (vm()->watchdog())
1136 emitOpcode(op_watchdog);
1139 void BytecodeGenerator::retrieveLastBinaryOp(int& dstIndex, int& src1Index, int& src2Index)
1141 ASSERT(instructions().size() >= 4);
1142 size_t size = instructions().size();
1143 dstIndex = instructions().at(size - 3).u.operand;
1144 src1Index = instructions().at(size - 2).u.operand;
1145 src2Index = instructions().at(size - 1).u.operand;
1148 void BytecodeGenerator::retrieveLastUnaryOp(int& dstIndex, int& srcIndex)
1150 ASSERT(instructions().size() >= 3);
1151 size_t size = instructions().size();
1152 dstIndex = instructions().at(size - 2).u.operand;
1153 srcIndex = instructions().at(size - 1).u.operand;
1156 void ALWAYS_INLINE BytecodeGenerator::rewindBinaryOp()
1158 ASSERT(instructions().size() >= 4);
1159 instructions().shrink(instructions().size() - 4);
1160 m_lastOpcodeID = op_end;
1163 void ALWAYS_INLINE BytecodeGenerator::rewindUnaryOp()
1165 ASSERT(instructions().size() >= 3);
1166 instructions().shrink(instructions().size() - 3);
1167 m_lastOpcodeID = op_end;
1170 PassRefPtr<Label> BytecodeGenerator::emitJump(Label* target)
1172 size_t begin = instructions().size();
1174 instructions().append(target->bind(begin, instructions().size()));
1178 PassRefPtr<Label> BytecodeGenerator::emitJumpIfTrue(RegisterID* cond, Label* target)
1180 if (m_lastOpcodeID == op_less) {
1185 retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1187 if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1190 size_t begin = instructions().size();
1191 emitOpcode(op_jless);
1192 instructions().append(src1Index);
1193 instructions().append(src2Index);
1194 instructions().append(target->bind(begin, instructions().size()));
1197 } else if (m_lastOpcodeID == op_lesseq) {
1202 retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1204 if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1207 size_t begin = instructions().size();
1208 emitOpcode(op_jlesseq);
1209 instructions().append(src1Index);
1210 instructions().append(src2Index);
1211 instructions().append(target->bind(begin, instructions().size()));
1214 } else if (m_lastOpcodeID == op_greater) {
1219 retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1221 if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1224 size_t begin = instructions().size();
1225 emitOpcode(op_jgreater);
1226 instructions().append(src1Index);
1227 instructions().append(src2Index);
1228 instructions().append(target->bind(begin, instructions().size()));
1231 } else if (m_lastOpcodeID == op_greatereq) {
1236 retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1238 if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1241 size_t begin = instructions().size();
1242 emitOpcode(op_jgreatereq);
1243 instructions().append(src1Index);
1244 instructions().append(src2Index);
1245 instructions().append(target->bind(begin, instructions().size()));
1248 } else if (m_lastOpcodeID == op_eq_null && target->isForward()) {
1252 retrieveLastUnaryOp(dstIndex, srcIndex);
1254 if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1257 size_t begin = instructions().size();
1258 emitOpcode(op_jeq_null);
1259 instructions().append(srcIndex);
1260 instructions().append(target->bind(begin, instructions().size()));
1263 } else if (m_lastOpcodeID == op_neq_null && target->isForward()) {
1267 retrieveLastUnaryOp(dstIndex, srcIndex);
1269 if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1272 size_t begin = instructions().size();
1273 emitOpcode(op_jneq_null);
1274 instructions().append(srcIndex);
1275 instructions().append(target->bind(begin, instructions().size()));
1280 size_t begin = instructions().size();
1282 emitOpcode(op_jtrue);
1283 instructions().append(cond->index());
1284 instructions().append(target->bind(begin, instructions().size()));
1288 PassRefPtr<Label> BytecodeGenerator::emitJumpIfFalse(RegisterID* cond, Label* target)
1290 if (m_lastOpcodeID == op_less && target->isForward()) {
1295 retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1297 if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1300 size_t begin = instructions().size();
1301 emitOpcode(op_jnless);
1302 instructions().append(src1Index);
1303 instructions().append(src2Index);
1304 instructions().append(target->bind(begin, instructions().size()));
1307 } else if (m_lastOpcodeID == op_lesseq && target->isForward()) {
1312 retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1314 if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1317 size_t begin = instructions().size();
1318 emitOpcode(op_jnlesseq);
1319 instructions().append(src1Index);
1320 instructions().append(src2Index);
1321 instructions().append(target->bind(begin, instructions().size()));
1324 } else if (m_lastOpcodeID == op_greater && target->isForward()) {
1329 retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1331 if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1334 size_t begin = instructions().size();
1335 emitOpcode(op_jngreater);
1336 instructions().append(src1Index);
1337 instructions().append(src2Index);
1338 instructions().append(target->bind(begin, instructions().size()));
1341 } else if (m_lastOpcodeID == op_greatereq && target->isForward()) {
1346 retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1348 if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1351 size_t begin = instructions().size();
1352 emitOpcode(op_jngreatereq);
1353 instructions().append(src1Index);
1354 instructions().append(src2Index);
1355 instructions().append(target->bind(begin, instructions().size()));
1358 } else if (m_lastOpcodeID == op_not) {
1362 retrieveLastUnaryOp(dstIndex, srcIndex);
1364 if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1367 size_t begin = instructions().size();
1368 emitOpcode(op_jtrue);
1369 instructions().append(srcIndex);
1370 instructions().append(target->bind(begin, instructions().size()));
1373 } else if (m_lastOpcodeID == op_eq_null && target->isForward()) {
1377 retrieveLastUnaryOp(dstIndex, srcIndex);
1379 if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1382 size_t begin = instructions().size();
1383 emitOpcode(op_jneq_null);
1384 instructions().append(srcIndex);
1385 instructions().append(target->bind(begin, instructions().size()));
1388 } else if (m_lastOpcodeID == op_neq_null && target->isForward()) {
1392 retrieveLastUnaryOp(dstIndex, srcIndex);
1394 if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1397 size_t begin = instructions().size();
1398 emitOpcode(op_jeq_null);
1399 instructions().append(srcIndex);
1400 instructions().append(target->bind(begin, instructions().size()));
1405 size_t begin = instructions().size();
1406 emitOpcode(op_jfalse);
1407 instructions().append(cond->index());
1408 instructions().append(target->bind(begin, instructions().size()));
1412 PassRefPtr<Label> BytecodeGenerator::emitJumpIfNotFunctionCall(RegisterID* cond, Label* target)
1414 size_t begin = instructions().size();
1416 emitOpcode(op_jneq_ptr);
1417 instructions().append(cond->index());
1418 instructions().append(Special::CallFunction);
1419 instructions().append(target->bind(begin, instructions().size()));
1423 PassRefPtr<Label> BytecodeGenerator::emitJumpIfNotFunctionApply(RegisterID* cond, Label* target)
1425 size_t begin = instructions().size();
1427 emitOpcode(op_jneq_ptr);
1428 instructions().append(cond->index());
1429 instructions().append(Special::ApplyFunction);
1430 instructions().append(target->bind(begin, instructions().size()));
1434 bool BytecodeGenerator::hasConstant(const Identifier& ident) const
1436 UniquedStringImpl* rep = ident.impl();
1437 return m_identifierMap.contains(rep);
1440 unsigned BytecodeGenerator::addConstant(const Identifier& ident)
1442 UniquedStringImpl* rep = ident.impl();
1443 IdentifierMap::AddResult result = m_identifierMap.add(rep, m_codeBlock->numberOfIdentifiers());
1444 if (result.isNewEntry)
1445 m_codeBlock->addIdentifier(ident);
1447 return result.iterator->value;
1450 // We can't hash JSValue(), so we use a dedicated data member to cache it.
1451 RegisterID* BytecodeGenerator::addConstantEmptyValue()
1453 if (!m_emptyValueRegister) {
1454 int index = m_nextConstantOffset;
1455 m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
1456 ++m_nextConstantOffset;
1457 m_codeBlock->addConstant(JSValue());
1458 m_emptyValueRegister = &m_constantPoolRegisters[index];
1461 return m_emptyValueRegister;
1464 RegisterID* BytecodeGenerator::addConstantValue(JSValue v, SourceCodeRepresentation sourceCodeRepresentation)
1467 return addConstantEmptyValue();
1469 int index = m_nextConstantOffset;
1471 if (sourceCodeRepresentation == SourceCodeRepresentation::Double && v.isInt32())
1472 v = jsDoubleNumber(v.asNumber());
1473 EncodedJSValueWithRepresentation valueMapKey { JSValue::encode(v), sourceCodeRepresentation };
1474 JSValueMap::AddResult result = m_jsValueMap.add(valueMapKey, m_nextConstantOffset);
1475 if (result.isNewEntry) {
1476 m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
1477 ++m_nextConstantOffset;
1478 m_codeBlock->addConstant(v, sourceCodeRepresentation);
1480 index = result.iterator->value;
1481 return &m_constantPoolRegisters[index];
1484 RegisterID* BytecodeGenerator::emitMoveLinkTimeConstant(RegisterID* dst, LinkTimeConstant type)
1486 unsigned constantIndex = static_cast<unsigned>(type);
1487 if (!m_linkTimeConstantRegisters[constantIndex]) {
1488 int index = m_nextConstantOffset;
1489 m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
1490 ++m_nextConstantOffset;
1491 m_codeBlock->addConstant(type);
1492 m_linkTimeConstantRegisters[constantIndex] = &m_constantPoolRegisters[index];
1496 instructions().append(dst->index());
1497 instructions().append(m_linkTimeConstantRegisters[constantIndex]->index());
1502 unsigned BytecodeGenerator::addRegExp(RegExp* r)
1504 return m_codeBlock->addRegExp(r);
1507 RegisterID* BytecodeGenerator::emitMoveEmptyValue(RegisterID* dst)
1509 RefPtr<RegisterID> emptyValue = addConstantEmptyValue();
1512 instructions().append(dst->index());
1513 instructions().append(emptyValue->index());
1517 RegisterID* BytecodeGenerator::emitMove(RegisterID* dst, RegisterID* src)
1519 ASSERT(src != m_emptyValueRegister);
1521 m_staticPropertyAnalyzer.mov(dst->index(), src->index());
1523 instructions().append(dst->index());
1524 instructions().append(src->index());
1529 RegisterID* BytecodeGenerator::emitUnaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src)
1531 emitOpcode(opcodeID);
1532 instructions().append(dst->index());
1533 instructions().append(src->index());
1537 RegisterID* BytecodeGenerator::emitInc(RegisterID* srcDst)
1540 instructions().append(srcDst->index());
1544 RegisterID* BytecodeGenerator::emitDec(RegisterID* srcDst)
1547 instructions().append(srcDst->index());
1551 RegisterID* BytecodeGenerator::emitBinaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2, OperandTypes types)
1553 emitOpcode(opcodeID);
1554 instructions().append(dst->index());
1555 instructions().append(src1->index());
1556 instructions().append(src2->index());
1558 if (opcodeID == op_bitor || opcodeID == op_bitand || opcodeID == op_bitxor ||
1559 opcodeID == op_add || opcodeID == op_mul || opcodeID == op_sub || opcodeID == op_div)
1560 instructions().append(types.toInt());
1565 RegisterID* BytecodeGenerator::emitEqualityOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2)
1567 if (m_lastOpcodeID == op_typeof) {
1571 retrieveLastUnaryOp(dstIndex, srcIndex);
1573 if (src1->index() == dstIndex
1574 && src1->isTemporary()
1575 && m_codeBlock->isConstantRegisterIndex(src2->index())
1576 && m_codeBlock->constantRegister(src2->index()).get().isString()) {
1577 const String& value = asString(m_codeBlock->constantRegister(src2->index()).get())->tryGetValue();
1578 if (value == "undefined") {
1580 emitOpcode(op_is_undefined);
1581 instructions().append(dst->index());
1582 instructions().append(srcIndex);
1585 if (value == "boolean") {
1587 emitOpcode(op_is_boolean);
1588 instructions().append(dst->index());
1589 instructions().append(srcIndex);
1592 if (value == "number") {
1594 emitOpcode(op_is_number);
1595 instructions().append(dst->index());
1596 instructions().append(srcIndex);
1599 if (value == "string") {
1601 emitOpcode(op_is_string);
1602 instructions().append(dst->index());
1603 instructions().append(srcIndex);
1606 if (value == "object") {
1608 emitOpcode(op_is_object_or_null);
1609 instructions().append(dst->index());
1610 instructions().append(srcIndex);
1613 if (value == "function") {
1615 emitOpcode(op_is_function);
1616 instructions().append(dst->index());
1617 instructions().append(srcIndex);
1623 emitOpcode(opcodeID);
1624 instructions().append(dst->index());
1625 instructions().append(src1->index());
1626 instructions().append(src2->index());
1630 void BytecodeGenerator::emitTypeProfilerExpressionInfo(const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1632 ASSERT(vm()->typeProfiler());
1634 unsigned start = startDivot.offset; // Ranges are inclusive of their endpoints, AND 0 indexed.
1635 unsigned end = endDivot.offset - 1; // End Ranges already go one past the inclusive range, so subtract 1.
1636 unsigned instructionOffset = instructions().size() - 1;
1637 m_codeBlock->addTypeProfilerExpressionInfo(instructionOffset, start, end);
1640 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag flag)
1642 if (!vm()->typeProfiler())
1645 if (!registerToProfile)
1648 emitOpcode(op_profile_type);
1649 instructions().append(registerToProfile->index());
1650 instructions().append(0);
1651 instructions().append(flag);
1652 instructions().append(0);
1653 instructions().append(resolveType());
1655 // Don't emit expression info for this version of profile type. This generally means
1656 // we're profiling information for something that isn't in the actual text of a JavaScript
1657 // program. For example, implicit return undefined from a function call.
1660 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1662 emitProfileType(registerToProfile, ProfileTypeBytecodeDoesNotHaveGlobalID, startDivot, endDivot);
1665 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag flag, const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1667 if (!vm()->typeProfiler())
1670 if (!registerToProfile)
1673 // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType?
1674 emitOpcode(op_profile_type);
1675 instructions().append(registerToProfile->index());
1676 instructions().append(0);
1677 instructions().append(flag);
1678 instructions().append(0);
1679 instructions().append(resolveType());
1681 emitTypeProfilerExpressionInfo(startDivot, endDivot);
1684 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, const Variable& var, const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1686 if (!vm()->typeProfiler())
1689 if (!registerToProfile)
1692 ProfileTypeBytecodeFlag flag;
1693 int symbolTableOrScopeDepth;
1694 if (var.local() || var.offset().isScope()) {
1695 flag = ProfileTypeBytecodeLocallyResolved;
1696 ASSERT(var.symbolTableConstantIndex());
1697 symbolTableOrScopeDepth = var.symbolTableConstantIndex();
1699 flag = ProfileTypeBytecodeClosureVar;
1700 symbolTableOrScopeDepth = localScopeDepth();
1703 // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType?
1704 emitOpcode(op_profile_type);
1705 instructions().append(registerToProfile->index());
1706 instructions().append(symbolTableOrScopeDepth);
1707 instructions().append(flag);
1708 instructions().append(addConstant(var.ident()));
1709 instructions().append(resolveType());
1711 emitTypeProfilerExpressionInfo(startDivot, endDivot);
1714 void BytecodeGenerator::emitProfileControlFlow(int textOffset)
1716 if (vm()->controlFlowProfiler()) {
1717 RELEASE_ASSERT(textOffset >= 0);
1718 size_t bytecodeOffset = instructions().size();
1719 m_codeBlock->addOpProfileControlFlowBytecodeOffset(bytecodeOffset);
1721 emitOpcode(op_profile_control_flow);
1722 instructions().append(textOffset);
1726 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, bool b)
1728 return emitLoad(dst, jsBoolean(b));
1731 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, const Identifier& identifier)
1733 JSString*& stringInMap = m_stringMap.add(identifier.impl(), nullptr).iterator->value;
1735 stringInMap = jsOwnedString(vm(), identifier.string());
1736 return emitLoad(dst, JSValue(stringInMap));
1739 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, JSValue v, SourceCodeRepresentation sourceCodeRepresentation)
1741 RegisterID* constantID = addConstantValue(v, sourceCodeRepresentation);
1743 return emitMove(dst, constantID);
1747 RegisterID* BytecodeGenerator::emitLoadGlobalObject(RegisterID* dst)
1749 if (!m_globalObjectRegister) {
1750 int index = m_nextConstantOffset;
1751 m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
1752 ++m_nextConstantOffset;
1753 m_codeBlock->addConstant(JSValue());
1754 m_globalObjectRegister = &m_constantPoolRegisters[index];
1755 m_codeBlock->setGlobalObjectRegister(VirtualRegister(index));
1758 emitMove(dst, m_globalObjectRegister);
1759 return m_globalObjectRegister;
1762 template<typename LookUpVarKindFunctor>
1763 bool BytecodeGenerator::instantiateLexicalVariables(const VariableEnvironment& lexicalVariables, SymbolTable* symbolTable, ScopeRegisterType scopeRegisterType, LookUpVarKindFunctor lookUpVarKind)
1765 bool hasCapturedVariables = false;
1767 ConcurrentJITLocker locker(ConcurrentJITLocker::NoLockingNecessary);
1768 for (auto& entry : lexicalVariables) {
1769 ASSERT(entry.value.isLet() || entry.value.isConst() || entry.value.isFunction());
1770 ASSERT(!entry.value.isVar());
1771 SymbolTableEntry symbolTableEntry = symbolTable->get(locker, entry.key.get());
1772 ASSERT(symbolTableEntry.isNull());
1774 // Imported bindings which are not the namespace bindings are not allocated
1775 // in the module environment as usual variables' way.
1776 // And since these types of the variables only seen in the module environment,
1777 // other lexical environment need not to take care this.
1778 if (entry.value.isImported() && !entry.value.isImportedNamespace())
1781 VarKind varKind = lookUpVarKind(entry.key.get(), entry.value);
1782 VarOffset varOffset;
1783 if (varKind == VarKind::Scope) {
1784 varOffset = VarOffset(symbolTable->takeNextScopeOffset(locker));
1785 hasCapturedVariables = true;
1787 ASSERT(varKind == VarKind::Stack);
1789 if (scopeRegisterType == ScopeRegisterType::Block) {
1790 local = newBlockScopeVariable();
1794 varOffset = VarOffset(local->virtualRegister());
1797 SymbolTableEntry newEntry(varOffset, entry.value.isConst() ? ReadOnly : 0);
1798 symbolTable->add(locker, entry.key.get(), newEntry);
1801 return hasCapturedVariables;
1804 void BytecodeGenerator::emitPrefillStackTDZVariables(const VariableEnvironment& lexicalVariables, SymbolTable* symbolTable)
1806 // Prefill stack variables with the TDZ empty value.
1807 // Scope variables will be initialized to the TDZ empty value when JSLexicalEnvironment is allocated.
1808 ConcurrentJITLocker locker(ConcurrentJITLocker::NoLockingNecessary);
1809 for (auto& entry : lexicalVariables) {
1810 // Imported bindings which are not the namespace bindings are not allocated
1811 // in the module environment as usual variables' way.
1812 // And since these types of the variables only seen in the module environment,
1813 // other lexical environment need not to take care this.
1814 if (entry.value.isImported() && !entry.value.isImportedNamespace())
1817 if (entry.value.isFunction())
1820 SymbolTableEntry symbolTableEntry = symbolTable->get(locker, entry.key.get());
1821 ASSERT(!symbolTableEntry.isNull());
1822 VarOffset offset = symbolTableEntry.varOffset();
1823 if (offset.isScope())
1826 ASSERT(offset.isStack());
1827 emitMoveEmptyValue(®isterFor(offset.stackOffset()));
1831 void BytecodeGenerator::pushLexicalScope(VariableEnvironmentNode* node, TDZCheckOptimization tdzCheckOptimization, NestedScopeType nestedScopeType, RegisterID** constantSymbolTableResult, bool shouldInitializeBlockScopedFunctions)
1833 VariableEnvironment& environment = node->lexicalVariables();
1834 RegisterID* constantSymbolTableResultTemp = nullptr;
1835 pushLexicalScopeInternal(environment, tdzCheckOptimization, nestedScopeType, &constantSymbolTableResultTemp, TDZRequirement::UnderTDZ, ScopeType::LetConstScope, ScopeRegisterType::Block);
1837 if (shouldInitializeBlockScopedFunctions)
1838 initializeBlockScopedFunctions(environment, node->functionStack(), constantSymbolTableResultTemp);
1840 if (constantSymbolTableResult && constantSymbolTableResultTemp)
1841 *constantSymbolTableResult = constantSymbolTableResultTemp;
1844 void BytecodeGenerator::pushLexicalScopeInternal(VariableEnvironment& environment, TDZCheckOptimization tdzCheckOptimization, NestedScopeType nestedScopeType,
1845 RegisterID** constantSymbolTableResult, TDZRequirement tdzRequirement, ScopeType scopeType, ScopeRegisterType scopeRegisterType)
1847 if (!environment.size())
1850 if (m_shouldEmitDebugHooks)
1851 environment.markAllVariablesAsCaptured();
1853 SymbolTable* symbolTable = SymbolTable::create(*m_vm);
1854 switch (scopeType) {
1855 case ScopeType::CatchScope:
1856 symbolTable->setScopeType(SymbolTable::ScopeType::CatchScope);
1858 case ScopeType::LetConstScope:
1859 symbolTable->setScopeType(SymbolTable::ScopeType::LexicalScope);
1861 case ScopeType::FunctionNameScope:
1862 symbolTable->setScopeType(SymbolTable::ScopeType::FunctionNameScope);
1866 if (nestedScopeType == NestedScopeType::IsNested)
1867 symbolTable->markIsNestedLexicalScope();
1869 auto lookUpVarKind = [] (UniquedStringImpl*, const VariableEnvironmentEntry& entry) -> VarKind {
1870 return entry.isCaptured() ? VarKind::Scope : VarKind::Stack;
1873 bool hasCapturedVariables = instantiateLexicalVariables(environment, symbolTable, scopeRegisterType, lookUpVarKind);
1875 RegisterID* newScope = nullptr;
1876 RegisterID* constantSymbolTable = nullptr;
1877 int symbolTableConstantIndex = 0;
1878 if (vm()->typeProfiler()) {
1879 constantSymbolTable = addConstantValue(symbolTable);
1880 symbolTableConstantIndex = constantSymbolTable->index();
1882 if (hasCapturedVariables) {
1883 if (scopeRegisterType == ScopeRegisterType::Block) {
1884 newScope = newBlockScopeVariable();
1887 newScope = addVar();
1888 if (!constantSymbolTable) {
1889 ASSERT(!vm()->typeProfiler());
1890 constantSymbolTable = addConstantValue(symbolTable->cloneScopePart(*m_vm));
1891 symbolTableConstantIndex = constantSymbolTable->index();
1893 if (constantSymbolTableResult)
1894 *constantSymbolTableResult = constantSymbolTable;
1896 emitOpcode(op_create_lexical_environment);
1897 instructions().append(newScope->index());
1898 instructions().append(scopeRegister()->index());
1899 instructions().append(constantSymbolTable->index());
1900 instructions().append(addConstantValue(tdzRequirement == TDZRequirement::UnderTDZ ? jsTDZValue() : jsUndefined())->index());
1902 emitMove(scopeRegister(), newScope);
1904 pushScopedControlFlowContext();
1907 bool isWithScope = false;
1908 m_symbolTableStack.append(SymbolTableStackEntry{ symbolTable, newScope, isWithScope, symbolTableConstantIndex });
1909 if (tdzRequirement == TDZRequirement::UnderTDZ)
1910 pushTDZVariables(environment, tdzCheckOptimization);
1912 if (tdzRequirement == TDZRequirement::UnderTDZ)
1913 emitPrefillStackTDZVariables(environment, symbolTable);
1916 void BytecodeGenerator::initializeBlockScopedFunctions(VariableEnvironment& environment, FunctionStack& functionStack, RegisterID* constantSymbolTable)
1919 * We must transform block scoped function declarations in strict mode like so:
1923 * function foo() { ... }
1926 * function baz() { ... }
1934 * let foo = function foo() { ... }
1935 * let baz = function baz() { ... }
1941 * But without the TDZ checks.
1944 if (!environment.size()) {
1945 RELEASE_ASSERT(!functionStack.size());
1949 if (!functionStack.size())
1952 SymbolTable* symbolTable = m_symbolTableStack.last().m_symbolTable;
1953 RegisterID* scope = m_symbolTableStack.last().m_scope;
1954 RefPtr<RegisterID> temp = newTemporary();
1955 int symbolTableIndex = constantSymbolTable ? constantSymbolTable->index() : 0;
1956 ConcurrentJITLocker locker(ConcurrentJITLocker::NoLockingNecessary);
1957 for (FunctionMetadataNode* function : functionStack) {
1958 const Identifier& name = function->ident();
1959 auto iter = environment.find(name.impl());
1960 RELEASE_ASSERT(iter != environment.end());
1961 RELEASE_ASSERT(iter->value.isFunction());
1962 // We purposefully don't hold the symbol table lock around this loop because emitNewFunctionExpressionCommon may GC.
1963 SymbolTableEntry entry = symbolTable->get(locker, name.impl());
1964 RELEASE_ASSERT(!entry.isNull());
1965 emitNewFunctionExpressionCommon(temp.get(), function);
1966 bool isLexicallyScoped = true;
1967 emitPutToScope(scope, variableForLocalEntry(name, entry, symbolTableIndex, isLexicallyScoped), temp.get(), DoNotThrowIfNotFound, InitializationMode::Initialization);
1971 void BytecodeGenerator::hoistSloppyModeFunctionIfNecessary(const Identifier& functionName)
1973 if (m_scopeNode->hasSloppyModeHoistedFunction(functionName.impl())) {
1974 Variable currentFunctionVariable = variable(functionName);
1975 RefPtr<RegisterID> currentValue;
1976 if (RegisterID* local = currentFunctionVariable.local())
1977 currentValue = local;
1979 RefPtr<RegisterID> scope = emitResolveScope(nullptr, currentFunctionVariable);
1980 currentValue = emitGetFromScope(newTemporary(), scope.get(), currentFunctionVariable, DoNotThrowIfNotFound);
1983 ASSERT(m_varScopeSymbolTableIndex);
1984 ASSERT(*m_varScopeSymbolTableIndex < m_symbolTableStack.size());
1985 SymbolTableStackEntry& varScope = m_symbolTableStack[*m_varScopeSymbolTableIndex];
1986 SymbolTable* varSymbolTable = varScope.m_symbolTable;
1987 ASSERT(varSymbolTable->scopeType() == SymbolTable::ScopeType::VarScope);
1988 ConcurrentJITLocker locker(ConcurrentJITLocker::NoLockingNecessary);
1989 SymbolTableEntry entry = varSymbolTable->get(locker, functionName.impl());
1990 ASSERT(!entry.isNull());
1991 bool isLexicallyScoped = false;
1992 emitPutToScope(varScope.m_scope, variableForLocalEntry(functionName, entry, varScope.m_symbolTableConstantIndex, isLexicallyScoped), currentValue.get(), DoNotThrowIfNotFound, InitializationMode::NotInitialization);
1996 void BytecodeGenerator::popLexicalScope(VariableEnvironmentNode* node)
1998 VariableEnvironment& environment = node->lexicalVariables();
1999 popLexicalScopeInternal(environment, TDZRequirement::UnderTDZ);
2002 void BytecodeGenerator::popLexicalScopeInternal(VariableEnvironment& environment, TDZRequirement tdzRequirement)
2004 // NOTE: This function only makes sense for scopes that aren't ScopeRegisterType::Var (only function name scope right now is ScopeRegisterType::Var).
2005 // This doesn't make sense for ScopeRegisterType::Var because we deref RegisterIDs here.
2006 if (!environment.size())
2009 if (m_shouldEmitDebugHooks)
2010 environment.markAllVariablesAsCaptured();
2012 SymbolTableStackEntry stackEntry = m_symbolTableStack.takeLast();
2013 SymbolTable* symbolTable = stackEntry.m_symbolTable;
2014 bool hasCapturedVariables = false;
2015 ConcurrentJITLocker locker(ConcurrentJITLocker::NoLockingNecessary);
2016 for (auto& entry : environment) {
2017 if (entry.value.isCaptured()) {
2018 hasCapturedVariables = true;
2021 SymbolTableEntry symbolTableEntry = symbolTable->get(locker, entry.key.get());
2022 ASSERT(!symbolTableEntry.isNull());
2023 VarOffset offset = symbolTableEntry.varOffset();
2024 ASSERT(offset.isStack());
2025 RegisterID* local = ®isterFor(offset.stackOffset());
2029 if (hasCapturedVariables) {
2030 RELEASE_ASSERT(stackEntry.m_scope);
2031 emitPopScope(scopeRegister(), stackEntry.m_scope);
2032 popScopedControlFlowContext();
2033 stackEntry.m_scope->deref();
2036 if (tdzRequirement == TDZRequirement::UnderTDZ)
2037 m_TDZStack.removeLast();
2040 void BytecodeGenerator::prepareLexicalScopeForNextForLoopIteration(VariableEnvironmentNode* node, RegisterID* loopSymbolTable)
2042 VariableEnvironment& environment = node->lexicalVariables();
2043 if (!environment.size())
2045 if (m_shouldEmitDebugHooks)
2046 environment.markAllVariablesAsCaptured();
2047 if (!environment.hasCapturedVariables())
2050 RELEASE_ASSERT(loopSymbolTable);
2052 // This function needs to do setup for a for loop's activation if any of
2053 // the for loop's lexically declared variables are captured (that is, variables
2054 // declared in the loop header, not the loop body). This function needs to
2055 // make a copy of the current activation and copy the values from the previous
2056 // activation into the new activation because each iteration of a for loop
2057 // gets a new activation.
2059 SymbolTableStackEntry stackEntry = m_symbolTableStack.last();
2060 SymbolTable* symbolTable = stackEntry.m_symbolTable;
2061 RegisterID* loopScope = stackEntry.m_scope;
2062 ASSERT(symbolTable->scopeSize());
2064 Vector<std::pair<RegisterID*, Identifier>> activationValuesToCopyOver;
2067 activationValuesToCopyOver.reserveInitialCapacity(symbolTable->scopeSize());
2069 ConcurrentJITLocker locker(ConcurrentJITLocker::NoLockingNecessary);
2070 for (auto end = symbolTable->end(locker), ptr = symbolTable->begin(locker); ptr != end; ++ptr) {
2071 if (!ptr->value.varOffset().isScope())
2074 RefPtr<UniquedStringImpl> ident = ptr->key;
2075 Identifier identifier = Identifier::fromUid(m_vm, ident.get());
2077 RegisterID* transitionValue = newBlockScopeVariable();
2078 transitionValue->ref();
2079 emitGetFromScope(transitionValue, loopScope, variableForLocalEntry(identifier, ptr->value, loopSymbolTable->index(), true), DoNotThrowIfNotFound);
2080 activationValuesToCopyOver.uncheckedAppend(std::make_pair(transitionValue, identifier));
2084 // We need this dynamic behavior of the executing code to ensure
2085 // each loop iteration has a new activation object. (It's pretty ugly).
2086 // Also, this new activation needs to be assigned to the same register
2087 // as the previous scope because the loop body is compiled under
2088 // the assumption that the scope's register index is constant even
2089 // though the value in that register will change on each loop iteration.
2090 RefPtr<RegisterID> parentScope = emitGetParentScope(newTemporary(), loopScope);
2091 emitMove(scopeRegister(), parentScope.get());
2093 emitOpcode(op_create_lexical_environment);
2094 instructions().append(loopScope->index());
2095 instructions().append(scopeRegister()->index());
2096 instructions().append(loopSymbolTable->index());
2097 instructions().append(addConstantValue(jsTDZValue())->index());
2099 emitMove(scopeRegister(), loopScope);
2102 ConcurrentJITLocker locker(ConcurrentJITLocker::NoLockingNecessary);
2103 for (auto pair : activationValuesToCopyOver) {
2104 const Identifier& identifier = pair.second;
2105 SymbolTableEntry entry = symbolTable->get(locker, identifier.impl());
2106 RELEASE_ASSERT(!entry.isNull());
2107 RegisterID* transitionValue = pair.first;
2108 emitPutToScope(loopScope, variableForLocalEntry(identifier, entry, loopSymbolTable->index(), true), transitionValue, DoNotThrowIfNotFound, InitializationMode::NotInitialization);
2109 transitionValue->deref();
2114 Variable BytecodeGenerator::variable(const Identifier& property, ThisResolutionType thisResolutionType)
2116 if (property == propertyNames().thisIdentifier && thisResolutionType == ThisResolutionType::Local) {
2117 return Variable(property, VarOffset(thisRegister()->virtualRegister()), thisRegister(),
2118 ReadOnly, Variable::SpecialVariable, 0, false);
2121 // We can optimize lookups if the lexical variable is found before a "with" or "catch"
2122 // scope because we're guaranteed static resolution. If we have to pass through
2123 // a "with" or "catch" scope we loose this guarantee.
2124 // We can't optimize cases like this:
2128 // doSomethingWith(x);
2131 // Because we can't gaurantee static resolution on x.
2132 // But, in this case, we are guaranteed static resolution:
2137 // doSomethingWith(x);
2140 ConcurrentJITLocker locker(ConcurrentJITLocker::NoLockingNecessary);
2141 for (unsigned i = m_symbolTableStack.size(); i--; ) {
2142 SymbolTableStackEntry& stackEntry = m_symbolTableStack[i];
2143 if (stackEntry.m_isWithScope)
2144 return Variable(property);
2145 SymbolTable* symbolTable = stackEntry.m_symbolTable;
2146 SymbolTableEntry symbolTableEntry = symbolTable->get(locker, property.impl());
2147 if (symbolTableEntry.isNull())
2149 bool resultIsCallee = false;
2150 if (symbolTable->scopeType() == SymbolTable::ScopeType::FunctionNameScope) {
2151 if (m_usesNonStrictEval) {
2152 // We don't know if an eval has introduced a "var" named the same thing as the function name scope variable name.
2153 // We resort to dynamic lookup to answer this question.
2154 Variable result = Variable(property);
2157 resultIsCallee = true;
2159 Variable result = variableForLocalEntry(property, symbolTableEntry, stackEntry.m_symbolTableConstantIndex, symbolTable->scopeType() == SymbolTable::ScopeType::LexicalScope);
2161 result.setIsReadOnly();
2165 return Variable(property);
2168 Variable BytecodeGenerator::variableForLocalEntry(
2169 const Identifier& property, const SymbolTableEntry& entry, int symbolTableConstantIndex, bool isLexicallyScoped)
2171 VarOffset offset = entry.varOffset();
2174 if (offset.isStack())
2175 local = ®isterFor(offset.stackOffset());
2179 return Variable(property, offset, local, entry.getAttributes(), Variable::NormalVariable, symbolTableConstantIndex, isLexicallyScoped);
2182 void BytecodeGenerator::createVariable(
2183 const Identifier& property, VarKind varKind, SymbolTable* symbolTable, ExistingVariableMode existingVariableMode)
2185 ASSERT(property != propertyNames().thisIdentifier);
2186 ConcurrentJITLocker locker(ConcurrentJITLocker::NoLockingNecessary);
2187 SymbolTableEntry entry = symbolTable->get(locker, property.impl());
2189 if (!entry.isNull()) {
2190 if (existingVariableMode == IgnoreExisting)
2193 // Do some checks to ensure that the variable we're being asked to create is sufficiently
2194 // compatible with the one we have already created.
2196 VarOffset offset = entry.varOffset();
2198 // We can't change our minds about whether it's captured.
2199 if (offset.kind() != varKind) {
2201 "Trying to add variable called ", property, " as ", varKind,
2202 " but it was already added as ", offset, ".\n");
2203 RELEASE_ASSERT_NOT_REACHED();
2209 VarOffset varOffset;
2210 if (varKind == VarKind::Scope)
2211 varOffset = VarOffset(symbolTable->takeNextScopeOffset(locker));
2213 ASSERT(varKind == VarKind::Stack);
2214 varOffset = VarOffset(virtualRegisterForLocal(m_calleeLocals.size()));
2216 SymbolTableEntry newEntry(varOffset, 0);
2217 symbolTable->add(locker, property.impl(), newEntry);
2219 if (varKind == VarKind::Stack) {
2220 RegisterID* local = addVar();
2221 RELEASE_ASSERT(local->index() == varOffset.stackOffset().offset());
2225 RegisterID* BytecodeGenerator::emitOverridesHasInstance(RegisterID* dst, RegisterID* constructor, RegisterID* hasInstanceValue)
2227 emitOpcode(op_overrides_has_instance);
2228 instructions().append(dst->index());
2229 instructions().append(constructor->index());
2230 instructions().append(hasInstanceValue->index());
2234 // Indicates the least upper bound of resolve type based on local scope. The bytecode linker
2235 // will start with this ResolveType and compute the least upper bound including intercepting scopes.
2236 ResolveType BytecodeGenerator::resolveType()
2238 for (unsigned i = m_symbolTableStack.size(); i--; ) {
2239 if (m_symbolTableStack[i].m_isWithScope)
2241 if (m_usesNonStrictEval && m_symbolTableStack[i].m_symbolTable->scopeType() == SymbolTable::ScopeType::FunctionNameScope) {
2242 // We never want to assign to a FunctionNameScope. Returning Dynamic here achieves this goal.
2243 // If we aren't in non-strict eval mode, then NodesCodeGen needs to take care not to emit
2244 // a put_to_scope with the destination being the function name scope variable.
2249 if (m_usesNonStrictEval)
2250 return GlobalPropertyWithVarInjectionChecks;
2251 return GlobalProperty;
2254 RegisterID* BytecodeGenerator::emitResolveScope(RegisterID* dst, const Variable& variable)
2256 switch (variable.offset().kind()) {
2257 case VarKind::Stack:
2260 case VarKind::DirectArgument:
2261 return argumentsRegister();
2263 case VarKind::Scope: {
2264 // This always refers to the activation that *we* allocated, and not the current scope that code
2265 // lives in. Note that this will change once we have proper support for block scoping. Once that
2266 // changes, it will be correct for this code to return scopeRegister(). The only reason why we
2267 // don't do that already is that m_lexicalEnvironment is required by ConstDeclNode. ConstDeclNode
2268 // requires weird things because it is a shameful pile of nonsense, but block scoping would make
2269 // that code sensible and obviate the need for us to do bad things.
2270 ConcurrentJITLocker locker(ConcurrentJITLocker::NoLockingNecessary);
2271 for (unsigned i = m_symbolTableStack.size(); i--; ) {
2272 SymbolTableStackEntry& stackEntry = m_symbolTableStack[i];
2273 // We should not resolve a variable to VarKind::Scope if a "with" scope lies in between the current
2274 // scope and the resolved scope.
2275 RELEASE_ASSERT(!stackEntry.m_isWithScope);
2277 if (stackEntry.m_symbolTable->get(locker, variable.ident().impl()).isNull())
2280 RegisterID* scope = stackEntry.m_scope;
2281 RELEASE_ASSERT(scope);
2285 RELEASE_ASSERT_NOT_REACHED();
2289 case VarKind::Invalid:
2290 // Indicates non-local resolution.
2292 m_codeBlock->addPropertyAccessInstruction(instructions().size());
2294 // resolve_scope dst, id, ResolveType, depth
2295 dst = tempDestination(dst);
2296 emitOpcode(op_resolve_scope);
2297 instructions().append(kill(dst));
2298 instructions().append(scopeRegister()->index());
2299 instructions().append(addConstant(variable.ident()));
2300 instructions().append(resolveType());
2301 instructions().append(localScopeDepth());
2302 instructions().append(0);
2306 RELEASE_ASSERT_NOT_REACHED();
2310 RegisterID* BytecodeGenerator::emitGetFromScope(RegisterID* dst, RegisterID* scope, const Variable& variable, ResolveMode resolveMode)
2312 switch (variable.offset().kind()) {
2313 case VarKind::Stack:
2314 return emitMove(dst, variable.local());
2316 case VarKind::DirectArgument: {
2317 UnlinkedValueProfile profile = emitProfiledOpcode(op_get_from_arguments);
2318 instructions().append(kill(dst));
2319 instructions().append(scope->index());
2320 instructions().append(variable.offset().capturedArgumentsOffset().offset());
2321 instructions().append(profile);
2325 case VarKind::Scope:
2326 case VarKind::Invalid: {
2327 m_codeBlock->addPropertyAccessInstruction(instructions().size());
2329 // get_from_scope dst, scope, id, GetPutInfo, Structure, Operand
2330 UnlinkedValueProfile profile = emitProfiledOpcode(op_get_from_scope);
2331 instructions().append(kill(dst));
2332 instructions().append(scope->index());
2333 instructions().append(addConstant(variable.ident()));
2334 instructions().append(GetPutInfo(resolveMode, variable.offset().isScope() ? LocalClosureVar : resolveType(), InitializationMode::NotInitialization).operand());
2335 instructions().append(localScopeDepth());
2336 instructions().append(variable.offset().isScope() ? variable.offset().scopeOffset().offset() : 0);
2337 instructions().append(profile);
2341 RELEASE_ASSERT_NOT_REACHED();
2344 RegisterID* BytecodeGenerator::emitPutToScope(RegisterID* scope, const Variable& variable, RegisterID* value, ResolveMode resolveMode, InitializationMode initializationMode)
2346 switch (variable.offset().kind()) {
2347 case VarKind::Stack:
2348 emitMove(variable.local(), value);
2351 case VarKind::DirectArgument:
2352 emitOpcode(op_put_to_arguments);
2353 instructions().append(scope->index());
2354 instructions().append(variable.offset().capturedArgumentsOffset().offset());
2355 instructions().append(value->index());
2358 case VarKind::Scope:
2359 case VarKind::Invalid: {
2360 m_codeBlock->addPropertyAccessInstruction(instructions().size());
2362 // put_to_scope scope, id, value, GetPutInfo, Structure, Operand
2363 emitOpcode(op_put_to_scope);
2364 instructions().append(scope->index());
2365 instructions().append(addConstant(variable.ident()));
2366 instructions().append(value->index());
2368 if (variable.offset().isScope()) {
2369 offset = variable.offset().scopeOffset();
2370 instructions().append(GetPutInfo(resolveMode, LocalClosureVar, initializationMode).operand());
2371 instructions().append(variable.symbolTableConstantIndex());
2373 ASSERT(resolveType() != LocalClosureVar);
2374 instructions().append(GetPutInfo(resolveMode, resolveType(), initializationMode).operand());
2375 instructions().append(localScopeDepth());
2377 instructions().append(!!offset ? offset.offset() : 0);
2381 RELEASE_ASSERT_NOT_REACHED();
2384 RegisterID* BytecodeGenerator::initializeVariable(const Variable& variable, RegisterID* value)
2386 RELEASE_ASSERT(variable.offset().kind() != VarKind::Invalid);
2387 RegisterID* scope = emitResolveScope(nullptr, variable);
2388 return emitPutToScope(scope, variable, value, ThrowIfNotFound, InitializationMode::NotInitialization);
2391 RegisterID* BytecodeGenerator::emitInstanceOf(RegisterID* dst, RegisterID* value, RegisterID* basePrototype)
2393 emitOpcode(op_instanceof);
2394 instructions().append(dst->index());
2395 instructions().append(value->index());
2396 instructions().append(basePrototype->index());
2400 RegisterID* BytecodeGenerator::emitInstanceOfCustom(RegisterID* dst, RegisterID* value, RegisterID* constructor, RegisterID* hasInstanceValue)
2402 emitOpcode(op_instanceof_custom);
2403 instructions().append(dst->index());
2404 instructions().append(value->index());
2405 instructions().append(constructor->index());
2406 instructions().append(hasInstanceValue->index());
2410 RegisterID* BytecodeGenerator::emitTryGetById(RegisterID* dst, RegisterID* base, const Identifier& property)
2412 ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties are not supported with tryGetById.");
2414 emitOpcode(op_try_get_by_id);
2415 instructions().append(kill(dst));
2416 instructions().append(base->index());
2417 instructions().append(addConstant(property));
2421 RegisterID* BytecodeGenerator::emitGetById(RegisterID* dst, RegisterID* base, const Identifier& property)
2423 ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with get_by_val.");
2425 m_codeBlock->addPropertyAccessInstruction(instructions().size());
2427 UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_id);
2428 instructions().append(kill(dst));
2429 instructions().append(base->index());
2430 instructions().append(addConstant(property));
2431 instructions().append(0);
2432 instructions().append(0);
2433 instructions().append(0);
2434 instructions().append(0);
2435 instructions().append(profile);
2439 RegisterID* BytecodeGenerator::emitGetById(RegisterID* dst, RegisterID* base, RegisterID* thisVal, const Identifier& property)
2441 ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with get_by_val.");
2443 emitOpcode(op_get_by_id_with_this);
2444 instructions().append(kill(dst));
2445 instructions().append(base->index());
2446 instructions().append(thisVal->index());
2447 instructions().append(addConstant(property));
2451 RegisterID* BytecodeGenerator::emitPutById(RegisterID* base, const Identifier& property, RegisterID* value)
2453 ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with put_by_val.");
2455 unsigned propertyIndex = addConstant(property);
2457 m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2459 m_codeBlock->addPropertyAccessInstruction(instructions().size());
2461 emitOpcode(op_put_by_id);
2462 instructions().append(base->index());
2463 instructions().append(propertyIndex);
2464 instructions().append(value->index());
2465 instructions().append(0); // old structure
2466 instructions().append(0); // offset
2467 instructions().append(0); // new structure
2468 instructions().append(0); // structure chain
2469 instructions().append(static_cast<int>(PutByIdNone)); // is not direct
2474 RegisterID* BytecodeGenerator::emitPutById(RegisterID* base, RegisterID* thisValue, const Identifier& property, RegisterID* value)
2476 ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with put_by_val.");
2478 unsigned propertyIndex = addConstant(property);
2480 emitOpcode(op_put_by_id_with_this);
2481 instructions().append(base->index());
2482 instructions().append(thisValue->index());
2483 instructions().append(propertyIndex);
2484 instructions().append(value->index());
2489 RegisterID* BytecodeGenerator::emitDirectPutById(RegisterID* base, const Identifier& property, RegisterID* value, PropertyNode::PutType putType)
2491 ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with put_by_val(direct).");
2493 unsigned propertyIndex = addConstant(property);
2495 m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2497 m_codeBlock->addPropertyAccessInstruction(instructions().size());
2499 emitOpcode(op_put_by_id);
2500 instructions().append(base->index());
2501 instructions().append(propertyIndex);
2502 instructions().append(value->index());
2503 instructions().append(0); // old structure
2504 instructions().append(0); // offset
2505 instructions().append(0); // new structure
2506 instructions().append(0); // structure chain (unused if direct)
2507 instructions().append(static_cast<int>((putType == PropertyNode::KnownDirect || property != m_vm->propertyNames->underscoreProto) ? PutByIdIsDirect : PutByIdNone));
2511 void BytecodeGenerator::emitPutGetterById(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* getter)
2513 unsigned propertyIndex = addConstant(property);
2514 m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2516 emitOpcode(op_put_getter_by_id);
2517 instructions().append(base->index());
2518 instructions().append(propertyIndex);
2519 instructions().append(attributes);
2520 instructions().append(getter->index());
2523 void BytecodeGenerator::emitPutSetterById(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* setter)
2525 unsigned propertyIndex = addConstant(property);
2526 m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2528 emitOpcode(op_put_setter_by_id);
2529 instructions().append(base->index());
2530 instructions().append(propertyIndex);
2531 instructions().append(attributes);
2532 instructions().append(setter->index());
2535 void BytecodeGenerator::emitPutGetterSetter(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* getter, RegisterID* setter)
2537 unsigned propertyIndex = addConstant(property);
2539 m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2541 emitOpcode(op_put_getter_setter_by_id);
2542 instructions().append(base->index());
2543 instructions().append(propertyIndex);
2544 instructions().append(attributes);
2545 instructions().append(getter->index());
2546 instructions().append(setter->index());
2549 void BytecodeGenerator::emitPutGetterByVal(RegisterID* base, RegisterID* property, unsigned attributes, RegisterID* getter)
2551 emitOpcode(op_put_getter_by_val);
2552 instructions().append(base->index());
2553 instructions().append(property->index());
2554 instructions().append(attributes);
2555 instructions().append(getter->index());
2558 void BytecodeGenerator::emitPutSetterByVal(RegisterID* base, RegisterID* property, unsigned attributes, RegisterID* setter)
2560 emitOpcode(op_put_setter_by_val);
2561 instructions().append(base->index());
2562 instructions().append(property->index());
2563 instructions().append(attributes);
2564 instructions().append(setter->index());
2567 RegisterID* BytecodeGenerator::emitDeleteById(RegisterID* dst, RegisterID* base, const Identifier& property)
2569 emitOpcode(op_del_by_id);
2570 instructions().append(dst->index());
2571 instructions().append(base->index());
2572 instructions().append(addConstant(property));
2576 RegisterID* BytecodeGenerator::emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* property)
2578 for (size_t i = m_forInContextStack.size(); i > 0; i--) {
2579 ForInContext* context = m_forInContextStack[i - 1].get();
2580 if (context->local() != property)
2583 if (!context->isValid())
2586 if (context->type() == ForInContext::IndexedForInContextType) {
2587 property = static_cast<IndexedForInContext*>(context)->index();
2591 ASSERT(context->type() == ForInContext::StructureForInContextType);
2592 StructureForInContext* structureContext = static_cast<StructureForInContext*>(context);
2593 UnlinkedValueProfile profile = emitProfiledOpcode(op_get_direct_pname);
2594 instructions().append(kill(dst));
2595 instructions().append(base->index());
2596 instructions().append(property->index());
2597 instructions().append(structureContext->index()->index());
2598 instructions().append(structureContext->enumerator()->index());
2599 instructions().append(profile);
2603 UnlinkedArrayProfile arrayProfile = newArrayProfile();
2604 UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_val);
2605 instructions().append(kill(dst));
2606 instructions().append(base->index());
2607 instructions().append(property->index());
2608 instructions().append(arrayProfile);
2609 instructions().append(profile);
2613 RegisterID* BytecodeGenerator::emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* thisValue, RegisterID* property)
2615 emitOpcode(op_get_by_val_with_this);
2616 instructions().append(kill(dst));
2617 instructions().append(base->index());
2618 instructions().append(thisValue->index());
2619 instructions().append(property->index());
2623 RegisterID* BytecodeGenerator::emitPutByVal(RegisterID* base, RegisterID* property, RegisterID* value)
2625 UnlinkedArrayProfile arrayProfile = newArrayProfile();
2626 emitOpcode(op_put_by_val);
2627 instructions().append(base->index());
2628 instructions().append(property->index());
2629 instructions().append(value->index());
2630 instructions().append(arrayProfile);
2635 RegisterID* BytecodeGenerator::emitPutByVal(RegisterID* base, RegisterID* thisValue, RegisterID* property, RegisterID* value)
2637 emitOpcode(op_put_by_val_with_this);
2638 instructions().append(base->index());
2639 instructions().append(thisValue->index());
2640 instructions().append(property->index());
2641 instructions().append(value->index());
2646 RegisterID* BytecodeGenerator::emitDirectPutByVal(RegisterID* base, RegisterID* property, RegisterID* value)
2648 UnlinkedArrayProfile arrayProfile = newArrayProfile();
2649 emitOpcode(op_put_by_val_direct);
2650 instructions().append(base->index());
2651 instructions().append(property->index());
2652 instructions().append(value->index());
2653 instructions().append(arrayProfile);
2657 RegisterID* BytecodeGenerator::emitDeleteByVal(RegisterID* dst, RegisterID* base, RegisterID* property)
2659 emitOpcode(op_del_by_val);
2660 instructions().append(dst->index());
2661 instructions().append(base->index());
2662 instructions().append(property->index());
2666 RegisterID* BytecodeGenerator::emitPutByIndex(RegisterID* base, unsigned index, RegisterID* value)
2668 emitOpcode(op_put_by_index);
2669 instructions().append(base->index());
2670 instructions().append(index);
2671 instructions().append(value->index());
2675 RegisterID* BytecodeGenerator::emitAssert(RegisterID* condition, int line)
2677 emitOpcode(op_assert);
2678 instructions().append(condition->index());
2679 instructions().append(line);
2683 RegisterID* BytecodeGenerator::emitCreateThis(RegisterID* dst)
2685 size_t begin = instructions().size();
2686 m_staticPropertyAnalyzer.createThis(dst->index(), begin + 3);
2688 m_codeBlock->addPropertyAccessInstruction(instructions().size());
2689 emitOpcode(op_create_this);
2690 instructions().append(dst->index());
2691 instructions().append(dst->index());
2692 instructions().append(0);
2693 instructions().append(0);
2697 void BytecodeGenerator::emitTDZCheck(RegisterID* target)
2699 emitOpcode(op_check_tdz);
2700 instructions().append(target->index());
2703 bool BytecodeGenerator::needsTDZCheck(const Variable& variable)
2705 for (unsigned i = m_TDZStack.size(); i--;) {
2706 VariableEnvironment& identifiers = m_TDZStack[i].first;
2707 if (identifiers.contains(variable.ident().impl()))
2714 void BytecodeGenerator::emitTDZCheckIfNecessary(const Variable& variable, RegisterID* target, RegisterID* scope)
2716 if (needsTDZCheck(variable)) {
2718 emitTDZCheck(target);
2720 RELEASE_ASSERT(!variable.isLocal() && scope);
2721 RefPtr<RegisterID> result = emitGetFromScope(newTemporary(), scope, variable, DoNotThrowIfNotFound);
2722 emitTDZCheck(result.get());
2727 void BytecodeGenerator::liftTDZCheckIfPossible(const Variable& variable)
2729 RefPtr<UniquedStringImpl> identifier(variable.ident().impl());
2730 for (unsigned i = m_TDZStack.size(); i--;) {
2731 VariableEnvironment& environment = m_TDZStack[i].first;
2732 if (environment.contains(identifier)) {
2733 TDZCheckOptimization tdzCheckOptimizationCapability = m_TDZStack[i].second;
2734 if (tdzCheckOptimizationCapability == TDZCheckOptimization::Optimize) {
2735 bool wasRemoved = environment.remove(identifier);
2736 RELEASE_ASSERT(wasRemoved);
2743 void BytecodeGenerator::pushTDZVariables(VariableEnvironment environment, TDZCheckOptimization optimization)
2745 if (!environment.size())
2748 Vector<UniquedStringImpl*, 4> functionsToRemove;
2749 for (const auto& entry : environment) {
2750 if (entry.value.isFunction())
2751 functionsToRemove.append(entry.key.get());
2754 for (UniquedStringImpl* function : functionsToRemove)
2755 environment.remove(function);
2757 m_TDZStack.append(std::make_pair(WTFMove(environment), optimization));
2760 void BytecodeGenerator::getVariablesUnderTDZ(VariableEnvironment& result)
2762 for (auto& pair : m_TDZStack) {
2763 VariableEnvironment& environment = pair.first;
2764 for (auto entry : environment)
2765 result.add(entry.key.get());
2769 RegisterID* BytecodeGenerator::emitNewObject(RegisterID* dst)
2771 size_t begin = instructions().size();
2772 m_staticPropertyAnalyzer.newObject(dst->index(), begin + 2);
2774 emitOpcode(op_new_object);
2775 instructions().append(dst->index());
2776 instructions().append(0);
2777 instructions().append(newObjectAllocationProfile());
2781 unsigned BytecodeGenerator::addConstantBuffer(unsigned length)
2783 return m_codeBlock->addConstantBuffer(length);
2786 JSString* BytecodeGenerator::addStringConstant(const Identifier& identifier)
2788 JSString*& stringInMap = m_stringMap.add(identifier.impl(), nullptr).iterator->value;
2790 stringInMap = jsString(vm(), identifier.string());
2791 addConstantValue(stringInMap);
2796 JSTemplateRegistryKey* BytecodeGenerator::addTemplateRegistryKeyConstant(const TemplateRegistryKey& templateRegistryKey)
2798 JSTemplateRegistryKey*& templateRegistryKeyInMap = m_templateRegistryKeyMap.add(templateRegistryKey, nullptr).iterator->value;
2799 if (!templateRegistryKeyInMap) {
2800 templateRegistryKeyInMap = JSTemplateRegistryKey::create(*vm(), templateRegistryKey);
2801 addConstantValue(templateRegistryKeyInMap);
2803 return templateRegistryKeyInMap;
2806 RegisterID* BytecodeGenerator::emitNewArray(RegisterID* dst, ElementNode* elements, unsigned length)
2808 #if !ASSERT_DISABLED
2809 unsigned checkLength = 0;
2811 bool hadVariableExpression = false;
2813 for (ElementNode* n = elements; n; n = n->next()) {
2814 if (!n->value()->isConstant()) {
2815 hadVariableExpression = true;
2820 #if !ASSERT_DISABLED
2824 if (!hadVariableExpression) {
2825 ASSERT(length == checkLength);
2826 unsigned constantBufferIndex = addConstantBuffer(length);
2827 JSValue* constantBuffer = m_codeBlock->constantBuffer(constantBufferIndex).data();
2829 for (ElementNode* n = elements; index < length; n = n->next()) {
2830 ASSERT(n->value()->isConstant());
2831 constantBuffer[index++] = static_cast<ConstantNode*>(n->value())->jsValue(*this);
2833 emitOpcode(op_new_array_buffer);
2834 instructions().append(dst->index());
2835 instructions().append(constantBufferIndex);
2836 instructions().append(length);
2837 instructions().append(newArrayAllocationProfile());
2842 Vector<RefPtr<RegisterID>, 16, UnsafeVectorOverflow> argv;
2843 for (ElementNode* n = elements; n; n = n->next()) {
2847 ASSERT(!n->value()->isSpreadExpression());
2848 argv.append(newTemporary());
2849 // op_new_array requires the initial values to be a sequential range of registers
2850 ASSERT(argv.size() == 1 || argv[argv.size() - 1]->index() == argv[argv.size() - 2]->index() - 1);
2851 emitNode(argv.last().get(), n->value());
2854 emitOpcode(op_new_array);
2855 instructions().append(dst->index());
2856 instructions().append(argv.size() ? argv[0]->index() : 0); // argv
2857 instructions().append(argv.size()); // argc
2858 instructions().append(newArrayAllocationProfile());
2862 RegisterID* BytecodeGenerator::emitNewArrayWithSize(RegisterID* dst, RegisterID* length)
2864 emitOpcode(op_new_array_with_size);
2865 instructions().append(dst->index());
2866 instructions().append(length->index());
2867 instructions().append(newArrayAllocationProfile());
2872 RegisterID* BytecodeGenerator::emitNewRegExp(RegisterID* dst, RegExp* regExp)
2874 emitOpcode(op_new_regexp);
2875 instructions().append(dst->index());
2876 instructions().append(addRegExp(regExp));
2880 void BytecodeGenerator::emitNewFunctionExpressionCommon(RegisterID* dst, FunctionMetadataNode* function)
2882 unsigned index = m_codeBlock->addFunctionExpr(makeFunction(function));
2884 OpcodeID opcodeID = op_new_func_exp;
2885 switch (function->parseMode()) {
2886 case SourceParseMode::GeneratorWrapperFunctionMode:
2887 opcodeID = op_new_generator_func_exp;
2893 emitOpcode(opcodeID);
2894 instructions().append(dst->index());
2895 instructions().append(scopeRegister()->index());
2896 instructions().append(index);
2899 RegisterID* BytecodeGenerator::emitNewFunctionExpression(RegisterID* dst, FuncExprNode* func)
2901 emitNewFunctionExpressionCommon(dst, func->metadata());
2905 RegisterID* BytecodeGenerator::emitNewArrowFunctionExpression(RegisterID* dst, ArrowFuncExprNode* func)
2907 ASSERT(func->metadata()->parseMode() == SourceParseMode::ArrowFunctionMode);
2908 emitNewFunctionExpressionCommon(dst, func->metadata());
2912 RegisterID* BytecodeGenerator::emitNewMethodDefinition(RegisterID* dst, MethodDefinitionNode* func)
2914 ASSERT(func->metadata()->parseMode() == SourceParseMode::GeneratorWrapperFunctionMode
2915 || func->metadata()->parseMode() == SourceParseMode::GetterMode
2916 || func->metadata()->parseMode() == SourceParseMode::SetterMode
2917 || func->metadata()->parseMode() == SourceParseMode::MethodMode);
2918 emitNewFunctionExpressionCommon(dst, func->metadata());
2922 RegisterID* BytecodeGenerator::emitNewDefaultConstructor(RegisterID* dst, ConstructorKind constructorKind, const Identifier& name,
2923 const Identifier& ecmaName, const SourceCode& classSource)
2925 UnlinkedFunctionExecutable* executable = m_vm->builtinExecutables()->createDefaultConstructor(constructorKind, name);
2926 executable->setInvalidTypeProfilingOffsets();
2927 executable->setEcmaName(ecmaName);
2928 executable->setClassSource(classSource);
2930 unsigned index = m_codeBlock->addFunctionExpr(executable);
2932 emitOpcode(op_new_func_exp);
2933 instructions().append(dst->index());
2934 instructions().append(scopeRegister()->index());
2935 instructions().append(index);
2939 RegisterID* BytecodeGenerator::emitNewFunction(RegisterID* dst, FunctionMetadataNode* function)
2941 unsigned index = m_codeBlock->addFunctionDecl(makeFunction(function));
2942 if (function->parseMode() == SourceParseMode::GeneratorWrapperFunctionMode)
2943 emitOpcode(op_new_generator_func);
2945 emitOpcode(op_new_func);
2946 instructions().append(dst->index());
2947 instructions().append(scopeRegister()->index());
2948 instructions().append(index);
2952 void BytecodeGenerator::emitSetFunctionNameIfNeeded(ExpressionNode* valueNode, RegisterID* value, RegisterID* name)
2954 if (valueNode->isFuncExprNode()) {
2955 FunctionMetadataNode* metadata = static_cast<FuncExprNode*>(valueNode)->metadata();
2956 if (!metadata->ecmaName().isNull())
2958 } else if (valueNode->isClassExprNode()) {
2959 ClassExprNode* classExprNode = static_cast<ClassExprNode*>(valueNode);
2960 if (!classExprNode->ecmaName().isNull())
2962 if (classExprNode->hasStaticProperty(m_vm->propertyNames->name))
2967 // FIXME: We should use an op_call to an internal function here instead.
2968 // https://bugs.webkit.org/show_bug.cgi?id=155547
2969 emitOpcode(op_set_function_name);
2970 instructions().append(value->index());
2971 instructions().append(name->index());
2974 RegisterID* BytecodeGenerator::emitCall(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd)
2976 return emitCall(op_call, dst, func, expectedFunction, callArguments, divot, divotStart, divotEnd);
2979 RegisterID* BytecodeGenerator::emitCallInTailPosition(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd)
2981 return emitCall(m_inTailPosition ? op_tail_call : op_call, dst, func, expectedFunction, callArguments, divot, divotStart, divotEnd);
2984 RegisterID* BytecodeGenerator::emitCallEval(RegisterID* dst, RegisterID* func, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd)
2986 return emitCall(op_call_eval, dst, func, NoExpectedFunction, callArguments, divot, divotStart, divotEnd);
2989 ExpectedFunction BytecodeGenerator::expectedFunctionForIdentifier(const Identifier& identifier)
2991 if (identifier == m_vm->propertyNames->Object || identifier == m_vm->propertyNames->ObjectPrivateName)
2992 return ExpectObjectConstructor;
2993 if (identifier == m_vm->propertyNames->Array || identifier == m_vm->propertyNames->ArrayPrivateName)
2994 return ExpectArrayConstructor;
2995 return NoExpectedFunction;
2998 ExpectedFunction BytecodeGenerator::emitExpectedFunctionSnippet(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, Label* done)
3000 RefPtr<Label> realCall = newLabel();
3001 switch (expectedFunction) {
3002 case ExpectObjectConstructor: {
3003 // If the number of arguments is non-zero, then we can't do anything interesting.
3004 if (callArguments.argumentCountIncludingThis() >= 2)
3005 return NoExpectedFunction;
3007 size_t begin = instructions().size();
3008 emitOpcode(op_jneq_ptr);
3009 instructions().append(func->index());
3010 instructions().append(Special::ObjectConstructor);
3011 instructions().append(realCall->bind(begin, instructions().size()));
3013 if (dst != ignoredResult())
3018 case ExpectArrayConstructor: {
3019 // If you're doing anything other than "new Array()" or "new Array(foo)" then we
3020 // don't do inline it, for now. The only reason is that call arguments are in
3021 // the opposite order of what op_new_array expects, so we'd either need to change
3022 // how op_new_array works or we'd need an op_new_array_reverse. Neither of these
3023 // things sounds like it's worth it.
3024 if (callArguments.argumentCountIncludingThis() > 2)
3025 return NoExpectedFunction;
3027 size_t begin = instructions().size();
3028 emitOpcode(op_jneq_ptr);
3029 instructions().append(func->index());
3030 instructions().append(Special::ArrayConstructor);
3031 instructions().append(realCall->bind(begin, instructions().size()));
3033 if (dst != ignoredResult()) {
3034 if (callArguments.argumentCountIncludingThis() == 2)
3035 emitNewArrayWithSize(dst, callArguments.argumentRegister(0));
3037 ASSERT(callArguments.argumentCountIncludingThis() == 1);
3038 emitOpcode(op_new_array);
3039 instructions().append(dst->index());
3040 instructions().append(0);
3041 instructions().append(0);
3042 instructions().append(newArrayAllocationProfile());
3049 ASSERT(expectedFunction == NoExpectedFunction);
3050 return NoExpectedFunction;
3053 size_t begin = instructions().size();
3055 instructions().append(done->bind(begin, instructions().size()));
3056 emitLabel(realCall.get());
3058 return expectedFunction;
3061 RegisterID* BytecodeGenerator::emitCall(OpcodeID opcodeID, RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd)
3063 ASSERT(opcodeID == op_call || opcodeID == op_call_eval || opcodeID == op_tail_call);
3064 ASSERT(func->refCount());
3066 // Generate code for arguments.
3067 unsigned argument = 0;
3068 if (callArguments.argumentsNode()) {
3069 ArgumentListNode* n = callArguments.argumentsNode()->m_listNode;
3070 if (n && n->m_expr->isSpreadExpression()) {
3071 RELEASE_ASSERT(!n->m_next);
3072 auto expression = static_cast<SpreadExpressionNode*>(n->m_expr)->expression();
3073 RefPtr<RegisterID> argumentRegister;
3074 argumentRegister = expression->emitBytecode(*this, callArguments.argumentRegister(0));
3075 RefPtr<RegisterID> thisRegister = emitMove(newTemporary(), callArguments.thisRegister());
3076 return emitCallVarargs(opcodeID == op_tail_call ? op_tail_call_varargs : op_call_varargs, dst, func, callArguments.thisRegister(), argumentRegister.get(), newTemporary(), 0, divot, divotStart, divotEnd);
3078 for (; n; n = n->m_next)
3079 emitNode(callArguments.argumentRegister(argument++), n);
3082 // Reserve space for call frame.
3083 Vector<RefPtr<RegisterID>, JSStack::CallFrameHeaderSize, UnsafeVectorOverflow> callFrame;
3084 for (int i = 0; i < JSStack::CallFrameHeaderSize; ++i)
3085 callFrame.append(newTemporary());
3087 emitExpressionInfo(divot, divotStart, divotEnd);
3089 RefPtr<Label> done = newLabel();
3090 expectedFunction = emitExpectedFunctionSnippet(dst, func, expectedFunction, callArguments, done.get());
3092 if (opcodeID == op_tail_call)
3093 emitLogShadowChickenTailIfNecessary();
3096 UnlinkedArrayProfile arrayProfile = newArrayProfile();
3097 UnlinkedValueProfile profile = emitProfiledOpcode(opcodeID);
3099 ASSERT(dst != ignoredResult());
3100 instructions().append(dst->index());
3101 instructions().append(func->index());
3102 instructions().append(callArguments.argumentCountIncludingThis());
3103 instructions().append(callArguments.stackOffset());
3104 instructions().append(m_codeBlock->addLLIntCallLinkInfo());
3105 instructions().append(0);
3106 instructions().append(arrayProfile);
3107 instructions().append(profile);
3109 if (expectedFunction != NoExpectedFunction)
3110 emitLabel(done.get());
3115 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)
3117 return emitCallVarargs(op_call_varargs, dst, func, thisRegister, arguments, firstFreeRegister, firstVarArgOffset, divot, divotStart, divotEnd);
3120 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)
3122 return emitCallVarargs(m_inTailPosition ? op_tail_call_varargs : op_call_varargs, dst, func, thisRegister, arguments, firstFreeRegister, firstVarArgOffset, divot, divotStart, divotEnd);
3125 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)
3127 return emitCallVarargs(op_construct_varargs, dst, func, thisRegister, arguments, firstFreeRegister, firstVarArgOffset, divot, divotStart, divotEnd);
3130 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)
3132 emitExpressionInfo(divot, divotStart, divotEnd);
3134 if (opcode == op_tail_call_varargs)
3135 emitLogShadowChickenTailIfNecessary();
3138 UnlinkedArrayProfile arrayProfile = newArrayProfile();
3139 UnlinkedValueProfile profile = emitProfiledOpcode(opcode);
3140 ASSERT(dst != ignoredResult());
3141 instructions().append(dst->index());
3142 instructions().append(func->index());
3143 instructions().append(thisRegister ? thisRegister->index() : 0);
3144 instructions().append(arguments->index());
3145 instructions().append(firstFreeRegister->index());
3146 instructions().append(firstVarArgOffset);
3147 instructions().append(arrayProfile);
3148 instructions().append(profile);
3152 void BytecodeGenerator::emitLogShadowChickenPrologueIfNecessary()
3154 if (!m_shouldEmitDebugHooks && !Options::alwaysUseShadowChicken())
3156 emitOpcode(op_log_shadow_chicken_prologue);
3157 instructions().append(scopeRegister()->index());
3160 void BytecodeGenerator::emitLogShadowChickenTailIfNecessary()
3162 if (!m_shouldEmitDebugHooks && !Options::alwaysUseShadowChicken())
3164 emitOpcode(op_log_shadow_chicken_tail);
3165 instructions().append(thisRegister()->index());
3166 instructions().append(scopeRegister()->index());
3169 void BytecodeGenerator::emitCallDefineProperty(RegisterID* newObj, RegisterID* propertyNameRegister,
3170 RegisterID* valueRegister, RegisterID* getterRegister, RegisterID* setterRegister, unsigned options, const JSTextPosition& position)
3172 RefPtr<RegisterID> descriptorRegister = emitNewObject(newTemporary());
3174 RefPtr<RegisterID> trueRegister = emitLoad(newTemporary(), true);
3175 if (options & PropertyConfigurable)
3176 emitDirectPutById(descriptorRegister.get(), propertyNames().configurable, trueRegister.get(), PropertyNode::Unknown);
3177 if (options & PropertyWritable)
3178 emitDirectPutById(descriptorRegister.get(), propertyNames().writable, trueRegister.get(), PropertyNode::Unknown);
3179 else if (valueRegister) {
3180 RefPtr<RegisterID> falseRegister = emitLoad(newTemporary(), false);
3181 emitDirectPutById(descriptorRegister.get(), propertyNames().writable, falseRegister.get(), PropertyNode::Unknown);
3183 if (options & PropertyEnumerable)
3184 emitDirectPutById(descriptorRegister.get(), propertyNames().enumerable, trueRegister.get(), PropertyNode::Unknown);
3187 emitDirectPutById(descriptorRegister.get(), propertyNames().value, valueRegister, PropertyNode::Unknown);
3189 emitDirectPutById(descriptorRegister.get(), propertyNames().get, getterRegister, PropertyNode::Unknown);
3191 emitDirectPutById(descriptorRegister.get(), propertyNames().set, setterRegister, PropertyNode::Unknown);
3193 RefPtr<RegisterID> definePropertyRegister = emitMoveLinkTimeConstant(newTemporary(), LinkTimeConstant::DefinePropertyFunction);
3195 CallArguments callArguments(*this, nullptr, 3);
3196 emitLoad(callArguments.thisRegister(), jsUndefined());
3197 emitMove(callArguments.argumentRegister(0), newObj);
3198 emitMove(callArguments.argumentRegister(1), propertyNameRegister);
3199 emitMove(callArguments.argumentRegister(2), descriptorRegister.get());
3201 emitCall(newTemporary(), definePropertyRegister.get(), NoExpectedFunction, callArguments, position, position, position);
3204 RegisterID* BytecodeGenerator::emitReturn(RegisterID* src)
3206 if (isConstructor()) {
3207 bool derived = constructorKind() == ConstructorKind::Derived;
3208 bool srcIsThis = src->index() == m_thisRegister.index();
3210 if (derived && srcIsThis)
3214 RefPtr<Label> isObjectLabel = newLabel();
3215 emitJumpIfTrue(emitIsObject(newTemporary(), src), isObjectLabel.get());
3218 RefPtr<Label> isUndefinedLabel = newLabel();
3219 emitJumpIfTrue(emitIsUndefined(newTemporary(), src), isUndefinedLabel.get());
3220 emitThrowTypeError("Cannot return a non-object type in the constructor of a derived class.");
3221 emitLabel(isUndefinedLabel.get());
3222 emitTDZCheck(&m_thisRegister);
3225 emitUnaryNoDstOp(op_ret, &m_thisRegister);
3226 emitLabel(isObjectLabel.get());
3230 return emitUnaryNoDstOp(op_ret, src);
3233 RegisterID* BytecodeGenerator::emitUnaryNoDstOp(OpcodeID opcodeID, RegisterID* src)
3235 emitOpcode(opcodeID);
3236 instructions().append(src->index());
3240 RegisterID* BytecodeGenerator::emitConstruct(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd)
3242 ASSERT(func->refCount());
3244 // Generate code for arguments.
3245 unsigned argument = 0;
3246 if (ArgumentsNode* argumentsNode = callArguments.argumentsNode()) {
3248 ArgumentListNode* n = callArguments.argumentsNode()->m_listNode;
3249 if (n && n->m_expr->isSpreadExpression()) {
3250 RELEASE_ASSERT(!n->m_next);
3251 auto expression = static_cast<SpreadExpressionNode*>(n->m_expr)->expression();
3252 RefPtr<RegisterID> argumentRegister;
3253 argumentRegister = expression->emitBytecode(*this, callArguments.argumentRegister(0));
3254 return emitConstructVarargs(dst, func, callArguments.thisRegister(), argumentRegister.get(), newTemporary(), 0, divot, divotStart, divotEnd);
3257 for (ArgumentListNode* n = argumentsNode->m_listNode; n; n = n->m_next)
3258 emitNode(callArguments.argumentRegister(argument++), n);
3261 // Reserve space for call frame.
3262 Vector<RefPtr<RegisterID>, JSStack::CallFrameHeaderSize, UnsafeVectorOverflow> callFrame;
3263 for (int i = 0; i < JSStack::CallFrameHeaderSize; ++i)
3264 callFrame.append(newTemporary());
3266 emitExpressionInfo(divot, divotStart, divotEnd);
3268 RefPtr<Label> done = newLabel();
3269 expectedFunction = emitExpectedFunctionSnippet(dst, func, expectedFunction, callArguments, done.get());
3271 UnlinkedValueProfile profile = emitProfiledOpcode(op_construct);
3272 ASSERT(dst != ignoredResult());
3273 instructions().append(dst->index());
3274 instructions().append(func->index());
3275 instructions().append(callArguments.argumentCountIncludingThis());
3276 instructions().append(callArguments.stackOffset());
3277 instructions().append(m_codeBlock->addLLIntCallLinkInfo());
3278 instructions().append(0);
3279 instructions().append(0);
3280 instructions().append(profile);
3282 if (expectedFunction != NoExpectedFunction)
3283 emitLabel(done.get());
3288 RegisterID* BytecodeGenerator::emitStrcat(RegisterID* dst, RegisterID* src, int count)
3290 emitOpcode(op_strcat);
3291 instructions().append(dst->index());
3292 instructions().append(src->index());
3293 instructions().append(count);
3298 void BytecodeGenerator::emitToPrimitive(RegisterID* dst, RegisterID* src)
3300 emitOpcode(op_to_primitive);
3301 instructions().append(dst->index());
3302 instructions().append(src->index());
3305 void BytecodeGenerator::emitGetScope()
3307 emitOpcode(op_get_scope);
3308 instructions().append(scopeRegister()->index());
3311 RegisterID* BytecodeGenerator::emitPushWithScope(RegisterID* objectScope)
3313 pushScopedControlFlowContext();
3314 RegisterID* newScope = newBlockScopeVariable();
3317 emitOpcode(op_push_with_scope);
3318 instructions().append(newScope->index());
3319 instructions().append(objectScope->index());
3320 instructions().append(scopeRegister()->index());
3322 emitMove(scopeRegister(), newScope);
3323 m_symbolTableStack.append(SymbolTableStackEntry{ nullptr, newScope, true, 0 });
3328 RegisterID* BytecodeGenerator::emitGetParentScope(RegisterID* dst, RegisterID* scope)
3330 emitOpcode(op_get_parent_scope);
3331 instructions().append(dst->index());
3332 instructions().append(scope->index());
3336 void BytecodeGenerator::emitPopScope(RegisterID* dst, RegisterID* scope)
3338 RefPtr<RegisterID> parentScope = emitGetParentScope(newTemporary(), scope);
3339 emitMove(dst, parentScope.get());
3342 void BytecodeGenerator::emitPopWithScope()
3344 emitPopScope(scopeRegister(), scopeRegister());
3345 popScopedControlFlowContext();
3346 SymbolTableStackEntry stackEntry = m_symbolTableStack.takeLast();
3347 stackEntry.m_scope->deref();
3348 RELEASE_ASSERT(stackEntry.m_isWithScope);
3351 void BytecodeGenerator::emitDebugHook(DebugHookID debugHookID, unsigned line, unsigned charOffset, unsigned lineStart)
3353 #if ENABLE(DEBUG_WITH_BREAKPOINT)
3354 if (debugHookID != DidReachBreakpoint)
3357 if (!m_shouldEmitDebugHooks)
3360 JSTextPosition divot(line, charOffset, lineStart);
3361 emitExpressionInfo(divot, divot, divot);
3362 emitOpcode(op_debug);
3363 instructions().append(debugHookID);
3364 instructions().append(false);
3367 void BytecodeGenerator::pushFinallyContext(StatementNode* finallyBlock)
3369 // Reclaim free label scopes.
3370 while (m_labelScopes.size() && !m_labelScopes.last().refCount())
3371 m_labelScopes.removeLast();
3373 ControlFlowContext scope;
3374 scope.isFinallyBlock = true;
3375 FinallyContext context = {
3379 static_cast<unsigned>(m_scopeContextStack.size()),
3380 static_cast<unsigned>(m_switchContextStack.size()),
3381 static_cast<unsigned>(m_forInContextStack.size()),
3382 static_cast<unsigned>(m_tryContextStack.size()),
3383 static_cast<unsigned>(m_labelScopes.size()),
3384 static_cast<unsigned>(m_symbolTableStack.size()),
3388 scope.finallyContext = context;
3389 m_scopeContextStack.append(scope);
3393 void BytecodeGenerator::pushIteratorCloseContext(RegisterID* iterator, ThrowableExpressionData* node)
3395 // Reclaim free label scopes.
3396 while (m_labelScopes.size() && !m_labelScopes.last().refCount())
3397 m_labelScopes.removeLast();
3399 ControlFlowContext scope;
3400 scope.isFinallyBlock = true;
3401 FinallyContext context = {
3405 static_cast<unsigned>(m_scopeContextStack.size()),
3406 static_cast<unsigned>(m_switchContextStack.size()),
3407 static_cast<unsigned>(m_forInContextStack.size()),
3408 static_cast<unsigned>(m_tryContextStack.size()),
3409 static_cast<unsigned>(m_labelScopes.size()),
3410 static_cast<unsigned>(m_symbolTableStack.size()),
3414 scope.finallyContext = context;
3415 m_scopeContextStack.append(scope);
3419 void BytecodeGenerator::popFinallyContext()
3421 ASSERT(m_scopeContextStack.size());
3422 ASSERT(m_scopeContextStack.last().isFinallyBlock);
3423 ASSERT(m_scopeContextStack.last().finallyContext.finallyBlock);
3424 ASSERT(!m_scopeContextStack.last().finallyContext.iterator);
3425 ASSERT(!m_scopeContextStack.last().finallyContext.enumerationNode);
3426 ASSERT(m_finallyDepth > 0);
3427 m_scopeContextStack.removeLast();
3431 void BytecodeGenerator::popIteratorCloseContext()
3433 ASSERT(m_scopeContextStack.size());
3434 ASSERT(m_scopeContextStack.last().isFinallyBlock);
3435 ASSERT(!m_scopeContextStack.last().finallyContext.finallyBlock);
3436 ASSERT(m_scopeContextStack.last().finallyContext.iterator);
3437 ASSERT(m_scopeContextStack.last().finallyContext.enumerationNode);
3438 ASSERT(m_finallyDepth > 0);
3439 m_scopeContextStack.removeLast();
3443 LabelScopePtr BytecodeGenerator::breakTarget(const Identifier& name)
3445 // Reclaim free label scopes.
3447 // The condition was previously coded as 'm_labelScopes.size() && !m_labelScopes.last().refCount()',
3448 // however sometimes this appears to lead to GCC going a little haywire and entering the loop with
3449 // size 0, leading to segfaulty badness. We are yet to identify a valid cause within our code to
3450 // cause the GCC codegen to misbehave in this fashion, and as such the following refactoring of the
3451 // loop condition is a workaround.
3452 while (m_labelScopes.size()) {
3453 if (m_labelScopes.last().refCount())
3455 m_labelScopes.removeLast();
3458 if (!m_labelScopes.size())
3459 return LabelScopePtr::null();
3461 // We special-case the following, which is a syntax error in Firefox:
3464 if (name.isEmpty()) {
3465 for (int i = m_labelScopes.size() - 1; i >= 0; --i) {
3466 LabelScope* scope = &m_labelScopes[i];
3467 if (scope->type() != LabelScope::NamedLabel) {
3468 ASSERT(scope->breakTarget());
3469 return LabelScopePtr(m_labelScopes, i);
3472 return LabelScopePtr::null();
3475 for (int i = m_labelScopes.size() - 1; i >= 0; --i) {
3476 LabelScope* scope = &m_labelScopes[i];
3477 if (scope->name() && *scope->name() == name) {
3478 ASSERT(scope->breakTarget());
3479 return LabelScopePtr(m_labelScopes, i);
3482 return LabelScopePtr::null();
3485 LabelScopePtr BytecodeGenerator::continueTarget(const Identifier& name)
3487 // Reclaim free label scopes.
3488 while (m_labelScopes.size() && !m_labelScopes.last().refCount())
3489 m_labelScopes.removeLast();
3491 if (!m_labelScopes.size())
3492 return LabelScopePtr::null();
3494 if (name.isEmpty()) {
3495 for (int i = m_labelScopes.size() - 1; i >= 0; --i) {
3496 LabelScope* scope = &m_labelScopes[i];
3497 if (scope->type() == LabelScope::Loop) {
3498 ASSERT(scope->continueTarget());
3499 return LabelScopePtr(m_labelScopes, i);
3502 return LabelScopePtr::null();
3505 // Continue to the loop nested nearest to the label scope that matches
3507 LabelScopePtr result = LabelScopePtr::null();
3508 for (int i = m_labelScopes.size() - 1; i >= 0; --i) {
3509 LabelScope* scope = &m_labelScopes[i];
3510 if (scope->type() == LabelScope::Loop) {
3511 ASSERT(scope->continueTarget());
3512 result = LabelScopePtr(m_labelScopes, i);
3514 if (scope->name() && *scope->name() == name)
3515 return result; // may be null.
3517 return LabelScopePtr::null();
3520 void BytecodeGenerator::allocateCalleeSaveSpace()
3522 size_t virtualRegisterCountForCalleeSaves = CodeBlock::llintBaselineCalleeSaveSpaceAsVirtualRegisters();
3524 for (size_t i = 0; i < virtualRegisterCountForCalleeSaves; i++) {
3525 RegisterID* localRegister = addVar();
3526 localRegister->ref();
3527 m_localRegistersForCalleeSaveRegisters.append(localRegister);
3531 void BytecodeGenerator::allocateAndEmitScope()
3533 m_scopeRegister = addVar();
3534 m_scopeRegister->ref();
3535 m_codeBlock->setScopeRegister(scopeRegister()->virtualRegister());
3537 m_topMostScope = addVar();
3538 emitMove(m_topMostScope, scopeRegister());
3541 void BytecodeGenerator::emitComplexPopScopes(RegisterID* scope, ControlFlowContext* topScope, ControlFlowContext* bottomScope)
3543 while (topScope > bottomScope) {
3544 // First we count the number of dynamic scopes we need to remove to get
3545 // to a finally block.
3546 int nNormalScopes = 0;
3547 while (topScope > bottomScope) {
3548 if (topScope->isFinallyBlock)
3554 if (nNormalScopes) {
3555 // We need to remove a number of dynamic scopes to get to the next
3557 RefPtr<RegisterID> parentScope = newTemporary();
3558 while (nNormalScopes--) {
3559 parentScope = emitGetParentScope(parentScope.get(), scope);
3560 emitMove(scope, parentScope.get());
3563 // If topScope == bottomScope then there isn't a finally block left to emit.
3564 if (topScope == bottomScope)
3568 Vector<ControlFlowContext> savedScopeContextStack;
3569 Vector<SwitchInfo> savedSwitchContextStack;
3570 Vector<std::unique_ptr<ForInContext>> savedForInContextStack;
3571 Vector<TryContext> poppedTryContexts;
3572 Vector<SymbolTableStackEntry> savedSymbolTableStack;
3573 LabelScopeStore savedLabelScopes;
3574 while (topScope > bottomScope && topScope->isFinallyBlock) {
3575 RefPtr<Label> beforeFinally = emitLabel(newLabel().get());
3577 // Save the current state of the world while instating the state of the world
3578 // for the finally block.
3579 FinallyContext finallyContext = topScope->finallyContext;
3580 bool flipScopes = finallyContext.scopeContextStackSize != m_scopeContextStack.size();
3581 bool flipSwitches = finallyContext.switchContextStackSize != m_switchContextStack.size();
3582 bool flipForIns = finallyContext.forInContextStackSize != m_forInContextStack.size();
3583 bool flipTries = finallyContext.tryContextStackSize != m_tryContextStack.size();
3584 bool flipLabelScopes = finallyContext.labelScopesSize != m_labelScopes.size();
3585 bool flipSymbolTableStack = finallyContext.symbolTableStackSize != m_symbolTableStack.size();
3586 int topScopeIndex = -1;
3587 int bottomScopeIndex = -1;
3589 topScopeIndex = topScope - m_scopeContextStack.begin();
3590 bottomScopeIndex = bottomScope - m_scopeContextStack.begin();
3591 savedScopeContextStack = m_scopeContextStack;
3592 m_scopeContextStack.shrink(finallyContext.scopeContextStackSize);
3595 savedSwitchContextStack = m_switchContextStack;
3596 m_switchContextStack.shrink(finallyContext.switchContextStackSize);
3599 savedForInContextStack.swap(m_forInContextStack);
3600 m_forInContextStack.shrink(finallyContext.forInContextStackSize);
3603 while (m_tryContextStack.size() != finallyContext.tryContextStackSize) {
3604 ASSERT(m_tryContextStack.size() > finallyContext.tryContextStackSize);
3605 TryContext context = m_tryContextStack.last();
3606 m_tryContextStack.removeLast();
3608 range.start = context.start;
3609 range.end = beforeFinally;
3610 range.tryData = context.tryData;
3611 m_tryRanges.append(range);
3612 poppedTryContexts.append(context);
3615 if (flipLabelScopes) {
3616 savedLabelScopes = m_labelScopes;
3617 while (m_labelScopes.size() > finallyContext.labelScopesSize)
3618 m_labelScopes.removeLast();
3620 if (flipSymbolTableStack) {
3621 savedSymbolTableStack = m_symbolTableStack;
3622 m_symbolTableStack.shrink(finallyContext.symbolTableStackSize);
3624 int savedFinallyDepth = m_finallyDepth;
3625 m_finallyDepth = finallyContext.finallyDepth;
3626 int savedDynamicScopeDepth = m_localScopeDepth;
3627 m_localScopeDepth = finallyContext.dynamicScopeDepth;
3629 if (finallyContext.finallyBlock) {
3630 // Emit the finally block.
3631 emitNode(finallyContext.finallyBlock);
3633 // Emit the IteratorClose block.
3634 ASSERT(finallyContext.iterator);
3635 emitIteratorClose(finallyContext.iterator, finallyContext.enumerationNode);
3638 RefPtr<Label> afterFinally = emitLabel(newLabel().get());
3640 // Restore the state of the world.
3642 m_scopeContextStack = savedScopeContextStack;
3643 topScope = &m_scopeContextStack[topScopeIndex]; // assert it's within bounds
3644 bottomScope = m_scopeContextStack.begin() + bottomScopeIndex; // don't assert, since it the index might be -1.
3647 m_switchContextStack = savedSwitchContextStack;
3649 m_forInContextStack.swap(savedForInContextStack);
3651 ASSERT(m_tryContextStack.size() == finallyContext.tryContextStackSize);
3652 for (unsigned i = poppedTryContexts.size(); i--;) {
3653 TryContext context = poppedTryContexts[i];
3654 context.start = afterFinally;
3655 m_tryContextStack.append(context);
3657 poppedTryContexts.clear();
3659 if (flipLabelScopes)
3660 m_labelScopes = savedLabelScopes;
3661 if (flipSymbolTableStack)
3662 m_symbolTableStack = savedSymbolTableStack;
3663 m_finallyDepth = savedFinallyDepth;
3664 m_localScopeDepth = savedDynamicScopeDepth;