diff options
Diffstat (limited to 'Source/JavaScriptCore/bytecompiler')
-rw-r--r-- | Source/JavaScriptCore/bytecompiler/BytecodeGenerator.cpp | 3544 | ||||
-rw-r--r-- | Source/JavaScriptCore/bytecompiler/BytecodeGenerator.h | 831 | ||||
-rw-r--r-- | Source/JavaScriptCore/bytecompiler/Label.h | 91 | ||||
-rw-r--r-- | Source/JavaScriptCore/bytecompiler/LabelScope.h | 136 | ||||
-rw-r--r-- | Source/JavaScriptCore/bytecompiler/NodesCodegen.cpp | 3331 | ||||
-rw-r--r-- | Source/JavaScriptCore/bytecompiler/RegisterID.h | 138 | ||||
-rw-r--r-- | Source/JavaScriptCore/bytecompiler/StaticPropertyAnalysis.h | 67 | ||||
-rw-r--r-- | Source/JavaScriptCore/bytecompiler/StaticPropertyAnalyzer.h | 170 |
8 files changed, 8308 insertions, 0 deletions
diff --git a/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.cpp b/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.cpp new file mode 100644 index 000000000..60e060553 --- /dev/null +++ b/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.cpp @@ -0,0 +1,3544 @@ +/* + * Copyright (C) 2008, 2009, 2012-2015 Apple Inc. All rights reserved. + * Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca> + * Copyright (C) 2012 Igalia, S.L. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "BytecodeGenerator.h" + +#include "BuiltinExecutables.h" +#include "Interpreter.h" +#include "JSFunction.h" +#include "JSLexicalEnvironment.h" +#include "JSTemplateRegistryKey.h" +#include "LowLevelInterpreter.h" +#include "JSCInlines.h" +#include "Options.h" +#include "StackAlignment.h" +#include "StrongInlines.h" +#include "UnlinkedCodeBlock.h" +#include "UnlinkedInstructionStream.h" +#include <wtf/StdLibExtras.h> +#include <wtf/text/WTFString.h> + +using namespace std; + +namespace JSC { + +void Label::setLocation(unsigned location) +{ + m_location = location; + + unsigned size = m_unresolvedJumps.size(); + for (unsigned i = 0; i < size; ++i) + m_generator.instructions()[m_unresolvedJumps[i].second].u.operand = m_location - m_unresolvedJumps[i].first; +} + +ParserError BytecodeGenerator::generate() +{ + SamplingRegion samplingRegion("Bytecode Generation"); + + m_codeBlock->setThisRegister(m_thisRegister.virtualRegister()); + + // If we have declared a variable named "arguments" and we are using arguments then we should + // perform that assignment now. + if (m_needToInitializeArguments) + initializeVariable(variable(propertyNames().arguments), m_argumentsRegister); + + pushLexicalScope(m_scopeNode, true); + + { + RefPtr<RegisterID> temp = newTemporary(); + RefPtr<RegisterID> globalScope = m_topMostScope; + for (auto functionPair : m_functionsToInitialize) { + FunctionMetadataNode* metadata = functionPair.first; + FunctionVariableType functionType = functionPair.second; + emitNewFunction(temp.get(), metadata); + if (functionType == NormalFunctionVariable) + initializeVariable(variable(metadata->ident()) , temp.get()); + else if (functionType == GlobalFunctionVariable) + emitPutToScope(globalScope.get(), Variable(metadata->ident()), temp.get(), ThrowIfNotFound); + else + RELEASE_ASSERT_NOT_REACHED(); + } + } + + bool callingClassConstructor = constructorKind() != ConstructorKind::None && !isConstructor(); + if (!callingClassConstructor) + m_scopeNode->emitBytecode(*this); + + m_staticPropertyAnalyzer.kill(); + + for (unsigned i = 0; i < m_tryRanges.size(); ++i) { + TryRange& range = m_tryRanges[i]; + int start = range.start->bind(); + int end = range.end->bind(); + + // This will happen for empty try blocks and for some cases of finally blocks: + // + // try { + // try { + // } finally { + // return 42; + // // *HERE* + // } + // } finally { + // print("things"); + // } + // + // The return will pop scopes to execute the outer finally block. But this includes + // popping the try context for the inner try. The try context is live in the fall-through + // part of the finally block not because we will emit a handler that overlaps the finally, + // but because we haven't yet had a chance to plant the catch target. Then when we finish + // emitting code for the outer finally block, we repush the try contex, this time with a + // new start index. But that means that the start index for the try range corresponding + // to the inner-finally-following-the-return (marked as "*HERE*" above) will be greater + // than the end index of the try block. This is harmless since end < start handlers will + // never get matched in our logic, but we do the runtime a favor and choose to not emit + // such handlers at all. + if (end <= start) + continue; + + ASSERT(range.tryData->handlerType != HandlerType::Illegal); + UnlinkedHandlerInfo info(static_cast<uint32_t>(start), static_cast<uint32_t>(end), + static_cast<uint32_t>(range.tryData->target->bind()), range.tryData->handlerType); + m_codeBlock->addExceptionHandler(info); + } + + m_codeBlock->setInstructions(std::make_unique<UnlinkedInstructionStream>(m_instructions)); + + m_codeBlock->shrinkToFit(); + + if (m_expressionTooDeep) + return ParserError(ParserError::OutOfMemory); + return ParserError(ParserError::ErrorNone); +} + +BytecodeGenerator::BytecodeGenerator(VM& vm, ProgramNode* programNode, UnlinkedProgramCodeBlock* codeBlock, DebuggerMode debuggerMode, ProfilerMode profilerMode, const VariableEnvironment* parentScopeTDZVariables) + : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn) + , m_shouldEmitProfileHooks(Options::forceProfilerBytecodeGeneration() || profilerMode == ProfilerOn) + , m_scopeNode(programNode) + , m_codeBlock(vm, codeBlock) + , m_thisRegister(CallFrame::thisArgumentOffset()) + , m_codeType(GlobalCode) + , m_vm(&vm) +{ + ASSERT_UNUSED(parentScopeTDZVariables, !parentScopeTDZVariables->size()); + + for (auto& constantRegister : m_linkTimeConstantRegisters) + constantRegister = nullptr; + + m_codeBlock->setNumParameters(1); // Allocate space for "this" + + emitOpcode(op_enter); + + allocateAndEmitScope(); + + const FunctionStack& functionStack = programNode->functionStack(); + + for (size_t i = 0; i < functionStack.size(); ++i) { + FunctionMetadataNode* function = functionStack[i]; + m_functionsToInitialize.append(std::make_pair(function, GlobalFunctionVariable)); + } + if (Options::validateBytecode()) { + for (auto& entry : programNode->varDeclarations()) + RELEASE_ASSERT(entry.value.isVar()); + } + codeBlock->setVariableDeclarations(programNode->varDeclarations()); +} + +BytecodeGenerator::BytecodeGenerator(VM& vm, FunctionNode* functionNode, UnlinkedFunctionCodeBlock* codeBlock, DebuggerMode debuggerMode, ProfilerMode profilerMode, const VariableEnvironment* parentScopeTDZVariables) + : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn) + , m_shouldEmitProfileHooks(Options::forceProfilerBytecodeGeneration() || profilerMode == ProfilerOn) + , m_scopeNode(functionNode) + , m_codeBlock(vm, codeBlock) + , m_codeType(FunctionCode) + , m_vm(&vm) + , m_isBuiltinFunction(codeBlock->isBuiltinFunction()) + , m_usesNonStrictEval(codeBlock->usesEval() && !codeBlock->isStrictMode()) +{ + for (auto& constantRegister : m_linkTimeConstantRegisters) + constantRegister = nullptr; + + if (m_isBuiltinFunction) + m_shouldEmitDebugHooks = false; + + SymbolTable* functionSymbolTable = SymbolTable::create(*m_vm); + functionSymbolTable->setUsesNonStrictEval(m_usesNonStrictEval); + int symbolTableConstantIndex = addConstantValue(functionSymbolTable)->index(); + + Vector<Identifier> boundParameterProperties; + FunctionParameters& parameters = *functionNode->parameters(); + if (!parameters.hasDefaultParameterValues()) { + // If we do have default parameters, they will be allocated in a separate scope. + for (size_t i = 0; i < parameters.size(); i++) { + auto pattern = parameters.at(i).first; + if (pattern->isBindingNode()) + continue; + pattern->collectBoundIdentifiers(boundParameterProperties); + } + } + + bool shouldCaptureSomeOfTheThings = m_shouldEmitDebugHooks || m_codeBlock->needsFullScopeChain(); + bool shouldCaptureAllOfTheThings = m_shouldEmitDebugHooks || codeBlock->usesEval(); + bool needsArguments = functionNode->usesArguments() || codeBlock->usesEval(); + if (shouldCaptureAllOfTheThings) + functionNode->varDeclarations().markAllVariablesAsCaptured(); + + auto captures = [&] (UniquedStringImpl* uid) -> bool { + if (!shouldCaptureSomeOfTheThings) + return false; + if (needsArguments && uid == propertyNames().arguments.impl()) { + // Actually, we only need to capture the arguments object when we "need full activation" + // because of name scopes. But historically we did it this way, so for now we just preserve + // the old behavior. + // FIXME: https://bugs.webkit.org/show_bug.cgi?id=143072 + return true; + } + return functionNode->captures(uid); + }; + auto varKind = [&] (UniquedStringImpl* uid) -> VarKind { + return captures(uid) ? VarKind::Scope : VarKind::Stack; + }; + + emitOpcode(op_enter); + + allocateAndEmitScope(); + + m_calleeRegister.setIndex(JSStack::Callee); + + if (functionNameIsInScope(functionNode->ident(), functionNode->functionMode()) + && functionNameScopeIsDynamic(codeBlock->usesEval(), codeBlock->isStrictMode())) { + emitPushFunctionNameScope(functionNode->ident(), &m_calleeRegister); + } + + if (shouldCaptureSomeOfTheThings) { + m_lexicalEnvironmentRegister = addVar(); + // We can allocate the "var" environment if we don't have default parameter expressions. If we have + // default parameter expressions, we have to hold off on allocating the "var" environment because + // the parent scope of the "var" environment is the parameter environment. + if (!parameters.hasDefaultParameterValues()) + initializeVarLexicalEnvironment(symbolTableConstantIndex); + } + + // Make sure the code block knows about all of our parameters, and make sure that parameters + // needing destructuring are noted. + m_parameters.grow(parameters.size() + 1); // reserve space for "this" + m_thisRegister.setIndex(initializeNextParameter()->index()); // this + for (unsigned i = 0; i < parameters.size(); ++i) + initializeNextParameter(); + + // Figure out some interesting facts about our arguments. + bool capturesAnyArgumentByName = false; + if (functionNode->hasCapturedVariables()) { + FunctionParameters& parameters = *functionNode->parameters(); + for (size_t i = 0; i < parameters.size(); ++i) { + auto pattern = parameters.at(i).first; + if (!pattern->isBindingNode()) + continue; + const Identifier& ident = static_cast<const BindingNode*>(pattern)->boundProperty(); + capturesAnyArgumentByName |= captures(ident.impl()); + } + } + + if (capturesAnyArgumentByName) + ASSERT(m_lexicalEnvironmentRegister); + + // Need to know what our functions are called. Parameters have some goofy behaviors when it + // comes to functions of the same name. + for (FunctionMetadataNode* function : functionNode->functionStack()) + m_functions.add(function->ident().impl()); + + if (needsArguments) { + // Create the arguments object now. We may put the arguments object into the activation if + // it is captured. Either way, we create two arguments object variables: one is our + // private variable that is immutable, and another that is the user-visible variable. The + // immutable one is only used here, or during formal parameter resolutions if we opt for + // DirectArguments. + + m_argumentsRegister = addVar(); + m_argumentsRegister->ref(); + } + + if (needsArguments && !codeBlock->isStrictMode() && !parameters.hasDefaultParameterValues()) { + // If we captured any formal parameter by name, then we use ScopedArguments. Otherwise we + // use DirectArguments. With ScopedArguments, we lift all of our arguments into the + // activation. + + if (capturesAnyArgumentByName) { + functionSymbolTable->setArgumentsLength(vm, parameters.size()); + + // For each parameter, we have two possibilities: + // Either it's a binding node with no function overlap, in which case it gets a name + // in the symbol table - or it just gets space reserved in the symbol table. Either + // way we lift the value into the scope. + for (unsigned i = 0; i < parameters.size(); ++i) { + ScopeOffset offset = functionSymbolTable->takeNextScopeOffset(); + functionSymbolTable->setArgumentOffset(vm, i, offset); + if (UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first)) { + VarOffset varOffset(offset); + SymbolTableEntry entry(varOffset); + // Stores to these variables via the ScopedArguments object will not do + // notifyWrite(), since that would be cumbersome. Also, watching formal + // parameters when "arguments" is in play is unlikely to be super profitable. + // So, we just disable it. + entry.disableWatching(); + functionSymbolTable->set(name, entry); + } + emitOpcode(op_put_to_scope); + instructions().append(m_lexicalEnvironmentRegister->index()); + instructions().append(UINT_MAX); + instructions().append(virtualRegisterForArgument(1 + i).offset()); + instructions().append(ResolveModeAndType(ThrowIfNotFound, LocalClosureVar).operand()); + instructions().append(symbolTableConstantIndex); + instructions().append(offset.offset()); + } + + // This creates a scoped arguments object and copies the overflow arguments into the + // scope. It's the equivalent of calling ScopedArguments::createByCopying(). + emitOpcode(op_create_scoped_arguments); + instructions().append(m_argumentsRegister->index()); + instructions().append(m_lexicalEnvironmentRegister->index()); + } else { + // We're going to put all parameters into the DirectArguments object. First ensure + // that the symbol table knows that this is happening. + for (unsigned i = 0; i < parameters.size(); ++i) { + if (UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first)) + functionSymbolTable->set(name, SymbolTableEntry(VarOffset(DirectArgumentsOffset(i)))); + } + + emitOpcode(op_create_direct_arguments); + instructions().append(m_argumentsRegister->index()); + } + } else if (!parameters.hasDefaultParameterValues()) { + // Create the formal parameters the normal way. Any of them could be captured, or not. If + // captured, lift them into the scope. We can not do this if we have default parameter expressions + // because when default parameter expressions exist, they belong in their own lexical environment + // separate from the "var" lexical environment. + for (unsigned i = 0; i < parameters.size(); ++i) { + UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first); + if (!name) + continue; + + if (!captures(name)) { + // This is the easy case - just tell the symbol table about the argument. It will + // be accessed directly. + functionSymbolTable->set(name, SymbolTableEntry(VarOffset(virtualRegisterForArgument(1 + i)))); + continue; + } + + ScopeOffset offset = functionSymbolTable->takeNextScopeOffset(); + const Identifier& ident = + static_cast<const BindingNode*>(parameters.at(i).first)->boundProperty(); + functionSymbolTable->set(name, SymbolTableEntry(VarOffset(offset))); + + emitOpcode(op_put_to_scope); + instructions().append(m_lexicalEnvironmentRegister->index()); + instructions().append(addConstant(ident)); + instructions().append(virtualRegisterForArgument(1 + i).offset()); + instructions().append(ResolveModeAndType(ThrowIfNotFound, LocalClosureVar).operand()); + instructions().append(symbolTableConstantIndex); + instructions().append(offset.offset()); + } + } + + if (needsArguments && (codeBlock->isStrictMode() || parameters.hasDefaultParameterValues())) { + // Allocate an out-of-bands arguments object. + emitOpcode(op_create_out_of_band_arguments); + instructions().append(m_argumentsRegister->index()); + } + + // Now declare all variables. + for (const Identifier& ident : boundParameterProperties) { + ASSERT(!parameters.hasDefaultParameterValues()); + createVariable(ident, varKind(ident.impl()), functionSymbolTable); + } + for (FunctionMetadataNode* function : functionNode->functionStack()) { + const Identifier& ident = function->ident(); + createVariable(ident, varKind(ident.impl()), functionSymbolTable); + m_functionsToInitialize.append(std::make_pair(function, NormalFunctionVariable)); + } + for (auto& entry : functionNode->varDeclarations()) { + ASSERT(!entry.value.isLet() && !entry.value.isConst()); + if (!entry.value.isVar()) // This is either a parameter or callee. + continue; + // Variables named "arguments" are never const. + createVariable(Identifier::fromUid(m_vm, entry.key.get()), varKind(entry.key.get()), functionSymbolTable, IgnoreExisting); + } + + // There are some variables that need to be preinitialized to something other than Undefined: + // + // - "arguments": unless it's used as a function or parameter, this should refer to the + // arguments object. + // + // - callee: unless it's used as a var, function, or parameter, this should refer to the + // callee (i.e. our function). + // + // - functions: these always override everything else. + // + // The most logical way to do all of this is to initialize none of the variables until now, + // and then initialize them in BytecodeGenerator::generate() in such an order that the rules + // for how these things override each other end up holding. We would initialize the callee + // first, then "arguments", then all arguments, then the functions. + // + // But some arguments are already initialized by default, since if they aren't captured and we + // don't have "arguments" then we just point the symbol table at the stack slot of those + // arguments. We end up initializing the rest of the arguments that have an uncomplicated + // binding (i.e. don't involve destructuring) above when figuring out how to lay them out, + // because that's just the simplest thing. This means that when we initialize them, we have to + // watch out for the things that override arguments (namely, functions). + // + // We also initialize callee here as well, just because it's so weird. We know whether we want + // to do this because we can just check if it's in the symbol table. + if (functionNameIsInScope(functionNode->ident(), functionNode->functionMode()) + && !functionNameScopeIsDynamic(codeBlock->usesEval(), codeBlock->isStrictMode()) + && functionSymbolTable->get(functionNode->ident().impl()).isNull()) { + if (captures(functionNode->ident().impl())) { + ScopeOffset offset; + { + ConcurrentJITLocker locker(functionSymbolTable->m_lock); + offset = functionSymbolTable->takeNextScopeOffset(locker); + functionSymbolTable->add( + locker, functionNode->ident().impl(), + SymbolTableEntry(VarOffset(offset), ReadOnly)); + } + + emitOpcode(op_put_to_scope); + instructions().append(m_lexicalEnvironmentRegister->index()); + instructions().append(addConstant(functionNode->ident())); + instructions().append(m_calleeRegister.index()); + instructions().append(ResolveModeAndType(ThrowIfNotFound, LocalClosureVar).operand()); + instructions().append(symbolTableConstantIndex); + instructions().append(offset.offset()); + } else { + functionSymbolTable->add( + functionNode->ident().impl(), + SymbolTableEntry(VarOffset(m_calleeRegister.virtualRegister()), ReadOnly)); + } + } + + // This is our final act of weirdness. "arguments" is overridden by everything except the + // callee. We add it to the symbol table if it's not already there and it's not an argument. + if (needsArguments) { + // If "arguments" is overridden by a function or destructuring parameter name, then it's + // OK for us to call createVariable() because it won't change anything. It's also OK for + // us to them tell BytecodeGenerator::generate() to write to it because it will do so + // before it initializes functions and destructuring parameters. But if "arguments" is + // overridden by a "simple" function parameter, then we have to bail: createVariable() + // would assert and BytecodeGenerator::generate() would write the "arguments" after the + // argument value had already been properly initialized. + + bool haveParameterNamedArguments = false; + for (unsigned i = 0; i < parameters.size(); ++i) { + UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first); + if (name == propertyNames().arguments.impl()) { + haveParameterNamedArguments = true; + break; + } + } + + if (!haveParameterNamedArguments) { + createVariable( + propertyNames().arguments, varKind(propertyNames().arguments.impl()), functionSymbolTable); + m_needToInitializeArguments = true; + } + } + + m_newTargetRegister = addVar(); + if (isConstructor()) { + emitMove(m_newTargetRegister, &m_thisRegister); + if (constructorKind() == ConstructorKind::Derived) { + emitMoveEmptyValue(&m_thisRegister); + } else + emitCreateThis(&m_thisRegister); + } else if (constructorKind() != ConstructorKind::None) { + emitThrowTypeError("Cannot call a class constructor"); + } else if (functionNode->usesThis() || codeBlock->usesEval()) { + m_codeBlock->addPropertyAccessInstruction(instructions().size()); + emitOpcode(op_to_this); + instructions().append(kill(&m_thisRegister)); + instructions().append(0); + instructions().append(0); + } + + // All "addVar()"s needs to happen before "initializeDefaultParameterValuesAndSetupFunctionScopeStack()" is called + // because a function's default parameter ExpressionNodes will use temporary registers. + m_TDZStack.append(std::make_pair(*parentScopeTDZVariables, false)); + initializeDefaultParameterValuesAndSetupFunctionScopeStack(parameters, functionNode, functionSymbolTable, symbolTableConstantIndex, captures); +} + +BytecodeGenerator::BytecodeGenerator(VM& vm, EvalNode* evalNode, UnlinkedEvalCodeBlock* codeBlock, DebuggerMode debuggerMode, ProfilerMode profilerMode, const VariableEnvironment* parentScopeTDZVariables) + : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn) + , m_shouldEmitProfileHooks(Options::forceProfilerBytecodeGeneration() || profilerMode == ProfilerOn) + , m_scopeNode(evalNode) + , m_codeBlock(vm, codeBlock) + , m_thisRegister(CallFrame::thisArgumentOffset()) + , m_codeType(EvalCode) + , m_vm(&vm) + , m_usesNonStrictEval(codeBlock->usesEval() && !codeBlock->isStrictMode()) +{ + for (auto& constantRegister : m_linkTimeConstantRegisters) + constantRegister = nullptr; + + m_codeBlock->setNumParameters(1); + + emitOpcode(op_enter); + + allocateAndEmitScope(); + + const DeclarationStacks::FunctionStack& functionStack = evalNode->functionStack(); + for (size_t i = 0; i < functionStack.size(); ++i) + m_codeBlock->addFunctionDecl(makeFunction(functionStack[i])); + + const VariableEnvironment& varDeclarations = evalNode->varDeclarations(); + unsigned numVariables = varDeclarations.size(); + Vector<Identifier, 0, UnsafeVectorOverflow> variables; + variables.reserveCapacity(numVariables); + for (auto& entry : varDeclarations) { + ASSERT(entry.value.isVar()); + ASSERT(entry.key->isAtomic() || entry.key->isSymbol()); + variables.append(Identifier::fromUid(m_vm, entry.key.get())); + } + codeBlock->adoptVariables(variables); + + m_TDZStack.append(std::make_pair(*parentScopeTDZVariables, false)); +} + +BytecodeGenerator::~BytecodeGenerator() +{ +} + +void BytecodeGenerator::initializeDefaultParameterValuesAndSetupFunctionScopeStack( + FunctionParameters& parameters, FunctionNode* functionNode, SymbolTable* functionSymbolTable, + int symbolTableConstantIndex, const std::function<bool (UniquedStringImpl*)>& captures) +{ + Vector<std::pair<Identifier, RefPtr<RegisterID>>> valuesToMoveIntoVars; + if (parameters.hasDefaultParameterValues()) { + // Refer to the ES6 spec section 9.2.12: http://www.ecma-international.org/ecma-262/6.0/index.html#sec-functiondeclarationinstantiation + // This implements step 21. + VariableEnvironment environment; + Vector<Identifier> allParameterNames; + for (unsigned i = 0; i < parameters.size(); i++) + parameters.at(i).first->collectBoundIdentifiers(allParameterNames); + IdentifierSet parameterSet; + for (auto& ident : allParameterNames) { + parameterSet.add(ident.impl()); + auto addResult = environment.add(ident); + addResult.iterator->value.setIsLet(); // When we have default parameter expressions, parameters act like "let" variables. + if (captures(ident.impl())) + addResult.iterator->value.setIsCaptured(); + } + + // This implements step 25 of section 9.2.12. + pushLexicalScopeInternal(environment, true, nullptr, TDZRequirement::UnderTDZ, ScopeType::LetConstScope, ScopeRegisterType::Block); + + RefPtr<RegisterID> temp = newTemporary(); + for (unsigned i = 0; i < parameters.size(); i++) { + std::pair<DestructuringPatternNode*, ExpressionNode*> parameter = parameters.at(i); + RefPtr<RegisterID> parameterValue = ®isterFor(virtualRegisterForArgument(1 + i)); + emitMove(temp.get(), parameterValue.get()); + if (parameter.second) { + RefPtr<RegisterID> condition = emitIsUndefined(newTemporary(), parameterValue.get()); + RefPtr<Label> skipDefaultParameterBecauseNotUndefined = newLabel(); + emitJumpIfFalse(condition.get(), skipDefaultParameterBecauseNotUndefined.get()); + emitNode(temp.get(), parameter.second); + emitLabel(skipDefaultParameterBecauseNotUndefined.get()); + } + + parameter.first->bindValue(*this, temp.get()); + } + + // Final act of weirdness for default parameters. If a "var" also + // has the same name as a parameter, it should start out as the + // value of that parameter. Note, though, that they will be distinct + // bindings. + // This is step 28 of section 9.2.12. + for (auto& entry : functionNode->varDeclarations()) { + if (!entry.value.isVar()) // This is either a parameter or callee. + continue; + + if (parameterSet.contains(entry.key)) { + Identifier ident = Identifier::fromUid(m_vm, entry.key.get()); + Variable var = variable(ident); + RegisterID* scope = emitResolveScope(nullptr, var); + RefPtr<RegisterID> value = emitGetFromScope(newTemporary(), scope, var, DoNotThrowIfNotFound); + valuesToMoveIntoVars.append(std::make_pair(ident, value)); + } + } + + // Functions with default parameter expressions must have a separate environment + // record for parameters and "var"s. The "var" environment record must have the + // parameter environment record as its parent. + // See step 28 of section 9.2.12. + if (m_lexicalEnvironmentRegister) + initializeVarLexicalEnvironment(symbolTableConstantIndex); + } + + if (m_lexicalEnvironmentRegister) + pushScopedControlFlowContext(); + m_symbolTableStack.append(SymbolTableStackEntry{ Strong<SymbolTable>(*m_vm, functionSymbolTable), m_lexicalEnvironmentRegister, false, symbolTableConstantIndex }); + + // This completes step 28 of section 9.2.12. + for (unsigned i = 0; i < valuesToMoveIntoVars.size(); i++) { + ASSERT(parameters.hasDefaultParameterValues()); + Variable var = variable(valuesToMoveIntoVars[i].first); + RegisterID* scope = emitResolveScope(nullptr, var); + emitPutToScope(scope, var, valuesToMoveIntoVars[i].second.get(), DoNotThrowIfNotFound); + } + + if (!parameters.hasDefaultParameterValues()) { + ASSERT(!valuesToMoveIntoVars.size()); + // Initialize destructuring parameters the old way as if we don't have any default parameter values. + // If we have default parameter values, we handle this case above. + for (unsigned i = 0; i < parameters.size(); i++) { + DestructuringPatternNode* pattern = parameters.at(i).first; + if (!pattern->isBindingNode()) { + RefPtr<RegisterID> parameterValue = ®isterFor(virtualRegisterForArgument(1 + i)); + pattern->bindValue(*this, parameterValue.get()); + } + } + } +} + +RegisterID* BytecodeGenerator::initializeNextParameter() +{ + VirtualRegister reg = virtualRegisterForArgument(m_codeBlock->numParameters()); + RegisterID& parameter = registerFor(reg); + parameter.setIndex(reg.offset()); + m_codeBlock->addParameter(); + return ¶meter; +} + +void BytecodeGenerator::initializeVarLexicalEnvironment(int symbolTableConstantIndex) +{ + RELEASE_ASSERT(m_lexicalEnvironmentRegister); + m_codeBlock->setActivationRegister(m_lexicalEnvironmentRegister->virtualRegister()); + emitOpcode(op_create_lexical_environment); + instructions().append(m_lexicalEnvironmentRegister->index()); + instructions().append(scopeRegister()->index()); + instructions().append(symbolTableConstantIndex); + instructions().append(addConstantValue(jsUndefined())->index()); + + emitOpcode(op_mov); + instructions().append(scopeRegister()->index()); + instructions().append(m_lexicalEnvironmentRegister->index()); +} + +UniquedStringImpl* BytecodeGenerator::visibleNameForParameter(DestructuringPatternNode* pattern) +{ + if (pattern->isBindingNode()) { + const Identifier& ident = static_cast<const BindingNode*>(pattern)->boundProperty(); + if (!m_functions.contains(ident.impl())) + return ident.impl(); + } + return nullptr; +} + +RegisterID* BytecodeGenerator::newRegister() +{ + m_calleeRegisters.append(virtualRegisterForLocal(m_calleeRegisters.size())); + int numCalleeRegisters = max<int>(m_codeBlock->m_numCalleeRegisters, m_calleeRegisters.size()); + numCalleeRegisters = WTF::roundUpToMultipleOf(stackAlignmentRegisters(), numCalleeRegisters); + m_codeBlock->m_numCalleeRegisters = numCalleeRegisters; + return &m_calleeRegisters.last(); +} + +void BytecodeGenerator::reclaimFreeRegisters() +{ + while (m_calleeRegisters.size() && !m_calleeRegisters.last().refCount()) + m_calleeRegisters.removeLast(); +} + +RegisterID* BytecodeGenerator::newBlockScopeVariable() +{ + reclaimFreeRegisters(); + + return newRegister(); +} + +RegisterID* BytecodeGenerator::newTemporary() +{ + reclaimFreeRegisters(); + + RegisterID* result = newRegister(); + result->setTemporary(); + return result; +} + +LabelScopePtr BytecodeGenerator::newLabelScope(LabelScope::Type type, const Identifier* name) +{ + // Reclaim free label scopes. + while (m_labelScopes.size() && !m_labelScopes.last().refCount()) + m_labelScopes.removeLast(); + + // Allocate new label scope. + LabelScope scope(type, name, labelScopeDepth(), newLabel(), type == LabelScope::Loop ? newLabel() : PassRefPtr<Label>()); // Only loops have continue targets. + m_labelScopes.append(scope); + return LabelScopePtr(m_labelScopes, m_labelScopes.size() - 1); +} + +PassRefPtr<Label> BytecodeGenerator::newLabel() +{ + // Reclaim free label IDs. + while (m_labels.size() && !m_labels.last().refCount()) + m_labels.removeLast(); + + // Allocate new label ID. + m_labels.append(*this); + return &m_labels.last(); +} + +PassRefPtr<Label> BytecodeGenerator::emitLabel(Label* l0) +{ + unsigned newLabelIndex = instructions().size(); + l0->setLocation(newLabelIndex); + + if (m_codeBlock->numberOfJumpTargets()) { + unsigned lastLabelIndex = m_codeBlock->lastJumpTarget(); + ASSERT(lastLabelIndex <= newLabelIndex); + if (newLabelIndex == lastLabelIndex) { + // Peephole optimizations have already been disabled by emitting the last label + return l0; + } + } + + m_codeBlock->addJumpTarget(newLabelIndex); + + // This disables peephole optimizations when an instruction is a jump target + m_lastOpcodeID = op_end; + return l0; +} + +void BytecodeGenerator::emitOpcode(OpcodeID opcodeID) +{ +#ifndef NDEBUG + size_t opcodePosition = instructions().size(); + ASSERT(opcodePosition - m_lastOpcodePosition == opcodeLength(m_lastOpcodeID) || m_lastOpcodeID == op_end); + m_lastOpcodePosition = opcodePosition; +#endif + instructions().append(opcodeID); + m_lastOpcodeID = opcodeID; +} + +UnlinkedArrayProfile BytecodeGenerator::newArrayProfile() +{ + return m_codeBlock->addArrayProfile(); +} + +UnlinkedArrayAllocationProfile BytecodeGenerator::newArrayAllocationProfile() +{ + return m_codeBlock->addArrayAllocationProfile(); +} + +UnlinkedObjectAllocationProfile BytecodeGenerator::newObjectAllocationProfile() +{ + return m_codeBlock->addObjectAllocationProfile(); +} + +UnlinkedValueProfile BytecodeGenerator::emitProfiledOpcode(OpcodeID opcodeID) +{ + UnlinkedValueProfile result = m_codeBlock->addValueProfile(); + emitOpcode(opcodeID); + return result; +} + +void BytecodeGenerator::emitLoopHint() +{ + emitOpcode(op_loop_hint); +} + +void BytecodeGenerator::retrieveLastBinaryOp(int& dstIndex, int& src1Index, int& src2Index) +{ + ASSERT(instructions().size() >= 4); + size_t size = instructions().size(); + dstIndex = instructions().at(size - 3).u.operand; + src1Index = instructions().at(size - 2).u.operand; + src2Index = instructions().at(size - 1).u.operand; +} + +void BytecodeGenerator::retrieveLastUnaryOp(int& dstIndex, int& srcIndex) +{ + ASSERT(instructions().size() >= 3); + size_t size = instructions().size(); + dstIndex = instructions().at(size - 2).u.operand; + srcIndex = instructions().at(size - 1).u.operand; +} + +void ALWAYS_INLINE BytecodeGenerator::rewindBinaryOp() +{ + ASSERT(instructions().size() >= 4); + instructions().shrink(instructions().size() - 4); + m_lastOpcodeID = op_end; +} + +void ALWAYS_INLINE BytecodeGenerator::rewindUnaryOp() +{ + ASSERT(instructions().size() >= 3); + instructions().shrink(instructions().size() - 3); + m_lastOpcodeID = op_end; +} + +PassRefPtr<Label> BytecodeGenerator::emitJump(Label* target) +{ + size_t begin = instructions().size(); + emitOpcode(op_jmp); + instructions().append(target->bind(begin, instructions().size())); + return target; +} + +PassRefPtr<Label> BytecodeGenerator::emitJumpIfTrue(RegisterID* cond, Label* target) +{ + if (m_lastOpcodeID == op_less) { + int dstIndex; + int src1Index; + int src2Index; + + retrieveLastBinaryOp(dstIndex, src1Index, src2Index); + + if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) { + rewindBinaryOp(); + + size_t begin = instructions().size(); + emitOpcode(op_jless); + instructions().append(src1Index); + instructions().append(src2Index); + instructions().append(target->bind(begin, instructions().size())); + return target; + } + } else if (m_lastOpcodeID == op_lesseq) { + int dstIndex; + int src1Index; + int src2Index; + + retrieveLastBinaryOp(dstIndex, src1Index, src2Index); + + if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) { + rewindBinaryOp(); + + size_t begin = instructions().size(); + emitOpcode(op_jlesseq); + instructions().append(src1Index); + instructions().append(src2Index); + instructions().append(target->bind(begin, instructions().size())); + return target; + } + } else if (m_lastOpcodeID == op_greater) { + int dstIndex; + int src1Index; + int src2Index; + + retrieveLastBinaryOp(dstIndex, src1Index, src2Index); + + if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) { + rewindBinaryOp(); + + size_t begin = instructions().size(); + emitOpcode(op_jgreater); + instructions().append(src1Index); + instructions().append(src2Index); + instructions().append(target->bind(begin, instructions().size())); + return target; + } + } else if (m_lastOpcodeID == op_greatereq) { + int dstIndex; + int src1Index; + int src2Index; + + retrieveLastBinaryOp(dstIndex, src1Index, src2Index); + + if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) { + rewindBinaryOp(); + + size_t begin = instructions().size(); + emitOpcode(op_jgreatereq); + instructions().append(src1Index); + instructions().append(src2Index); + instructions().append(target->bind(begin, instructions().size())); + return target; + } + } else if (m_lastOpcodeID == op_eq_null && target->isForward()) { + int dstIndex; + int srcIndex; + + retrieveLastUnaryOp(dstIndex, srcIndex); + + if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) { + rewindUnaryOp(); + + size_t begin = instructions().size(); + emitOpcode(op_jeq_null); + instructions().append(srcIndex); + instructions().append(target->bind(begin, instructions().size())); + return target; + } + } else if (m_lastOpcodeID == op_neq_null && target->isForward()) { + int dstIndex; + int srcIndex; + + retrieveLastUnaryOp(dstIndex, srcIndex); + + if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) { + rewindUnaryOp(); + + size_t begin = instructions().size(); + emitOpcode(op_jneq_null); + instructions().append(srcIndex); + instructions().append(target->bind(begin, instructions().size())); + return target; + } + } + + size_t begin = instructions().size(); + + emitOpcode(op_jtrue); + instructions().append(cond->index()); + instructions().append(target->bind(begin, instructions().size())); + return target; +} + +PassRefPtr<Label> BytecodeGenerator::emitJumpIfFalse(RegisterID* cond, Label* target) +{ + if (m_lastOpcodeID == op_less && target->isForward()) { + int dstIndex; + int src1Index; + int src2Index; + + retrieveLastBinaryOp(dstIndex, src1Index, src2Index); + + if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) { + rewindBinaryOp(); + + size_t begin = instructions().size(); + emitOpcode(op_jnless); + instructions().append(src1Index); + instructions().append(src2Index); + instructions().append(target->bind(begin, instructions().size())); + return target; + } + } else if (m_lastOpcodeID == op_lesseq && target->isForward()) { + int dstIndex; + int src1Index; + int src2Index; + + retrieveLastBinaryOp(dstIndex, src1Index, src2Index); + + if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) { + rewindBinaryOp(); + + size_t begin = instructions().size(); + emitOpcode(op_jnlesseq); + instructions().append(src1Index); + instructions().append(src2Index); + instructions().append(target->bind(begin, instructions().size())); + return target; + } + } else if (m_lastOpcodeID == op_greater && target->isForward()) { + int dstIndex; + int src1Index; + int src2Index; + + retrieveLastBinaryOp(dstIndex, src1Index, src2Index); + + if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) { + rewindBinaryOp(); + + size_t begin = instructions().size(); + emitOpcode(op_jngreater); + instructions().append(src1Index); + instructions().append(src2Index); + instructions().append(target->bind(begin, instructions().size())); + return target; + } + } else if (m_lastOpcodeID == op_greatereq && target->isForward()) { + int dstIndex; + int src1Index; + int src2Index; + + retrieveLastBinaryOp(dstIndex, src1Index, src2Index); + + if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) { + rewindBinaryOp(); + + size_t begin = instructions().size(); + emitOpcode(op_jngreatereq); + instructions().append(src1Index); + instructions().append(src2Index); + instructions().append(target->bind(begin, instructions().size())); + return target; + } + } else if (m_lastOpcodeID == op_not) { + int dstIndex; + int srcIndex; + + retrieveLastUnaryOp(dstIndex, srcIndex); + + if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) { + rewindUnaryOp(); + + size_t begin = instructions().size(); + emitOpcode(op_jtrue); + instructions().append(srcIndex); + instructions().append(target->bind(begin, instructions().size())); + return target; + } + } else if (m_lastOpcodeID == op_eq_null && target->isForward()) { + int dstIndex; + int srcIndex; + + retrieveLastUnaryOp(dstIndex, srcIndex); + + if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) { + rewindUnaryOp(); + + size_t begin = instructions().size(); + emitOpcode(op_jneq_null); + instructions().append(srcIndex); + instructions().append(target->bind(begin, instructions().size())); + return target; + } + } else if (m_lastOpcodeID == op_neq_null && target->isForward()) { + int dstIndex; + int srcIndex; + + retrieveLastUnaryOp(dstIndex, srcIndex); + + if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) { + rewindUnaryOp(); + + size_t begin = instructions().size(); + emitOpcode(op_jeq_null); + instructions().append(srcIndex); + instructions().append(target->bind(begin, instructions().size())); + return target; + } + } + + size_t begin = instructions().size(); + emitOpcode(op_jfalse); + instructions().append(cond->index()); + instructions().append(target->bind(begin, instructions().size())); + return target; +} + +PassRefPtr<Label> BytecodeGenerator::emitJumpIfNotFunctionCall(RegisterID* cond, Label* target) +{ + size_t begin = instructions().size(); + + emitOpcode(op_jneq_ptr); + instructions().append(cond->index()); + instructions().append(Special::CallFunction); + instructions().append(target->bind(begin, instructions().size())); + return target; +} + +PassRefPtr<Label> BytecodeGenerator::emitJumpIfNotFunctionApply(RegisterID* cond, Label* target) +{ + size_t begin = instructions().size(); + + emitOpcode(op_jneq_ptr); + instructions().append(cond->index()); + instructions().append(Special::ApplyFunction); + instructions().append(target->bind(begin, instructions().size())); + return target; +} + +bool BytecodeGenerator::hasConstant(const Identifier& ident) const +{ + UniquedStringImpl* rep = ident.impl(); + return m_identifierMap.contains(rep); +} + +unsigned BytecodeGenerator::addConstant(const Identifier& ident) +{ + UniquedStringImpl* rep = ident.impl(); + IdentifierMap::AddResult result = m_identifierMap.add(rep, m_codeBlock->numberOfIdentifiers()); + if (result.isNewEntry) + m_codeBlock->addIdentifier(ident); + + return result.iterator->value; +} + +// We can't hash JSValue(), so we use a dedicated data member to cache it. +RegisterID* BytecodeGenerator::addConstantEmptyValue() +{ + if (!m_emptyValueRegister) { + int index = m_nextConstantOffset; + m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset); + ++m_nextConstantOffset; + m_codeBlock->addConstant(JSValue()); + m_emptyValueRegister = &m_constantPoolRegisters[index]; + } + + return m_emptyValueRegister; +} + +RegisterID* BytecodeGenerator::addConstantValue(JSValue v, SourceCodeRepresentation sourceCodeRepresentation) +{ + if (!v) + return addConstantEmptyValue(); + + int index = m_nextConstantOffset; + + EncodedJSValueWithRepresentation valueMapKey { JSValue::encode(v), sourceCodeRepresentation }; + JSValueMap::AddResult result = m_jsValueMap.add(valueMapKey, m_nextConstantOffset); + if (result.isNewEntry) { + m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset); + ++m_nextConstantOffset; + m_codeBlock->addConstant(v, sourceCodeRepresentation); + } else + index = result.iterator->value; + return &m_constantPoolRegisters[index]; +} + +RegisterID* BytecodeGenerator::emitMoveLinkTimeConstant(RegisterID* dst, LinkTimeConstant type) +{ + unsigned constantIndex = static_cast<unsigned>(type); + if (!m_linkTimeConstantRegisters[constantIndex]) { + int index = m_nextConstantOffset; + m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset); + ++m_nextConstantOffset; + m_codeBlock->addConstant(type); + m_linkTimeConstantRegisters[constantIndex] = &m_constantPoolRegisters[index]; + } + + emitOpcode(op_mov); + instructions().append(dst->index()); + instructions().append(m_linkTimeConstantRegisters[constantIndex]->index()); + + return dst; +} + +unsigned BytecodeGenerator::addRegExp(RegExp* r) +{ + return m_codeBlock->addRegExp(r); +} + +RegisterID* BytecodeGenerator::emitMoveEmptyValue(RegisterID* dst) +{ + RefPtr<RegisterID> emptyValue = addConstantEmptyValue(); + + emitOpcode(op_mov); + instructions().append(dst->index()); + instructions().append(emptyValue->index()); + return dst; +} + +RegisterID* BytecodeGenerator::emitMove(RegisterID* dst, RegisterID* src) +{ + ASSERT(src != m_emptyValueRegister); + + m_staticPropertyAnalyzer.mov(dst->index(), src->index()); + emitOpcode(op_mov); + instructions().append(dst->index()); + instructions().append(src->index()); + + return dst; +} + +RegisterID* BytecodeGenerator::emitUnaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src) +{ + emitOpcode(opcodeID); + instructions().append(dst->index()); + instructions().append(src->index()); + return dst; +} + +RegisterID* BytecodeGenerator::emitInc(RegisterID* srcDst) +{ + emitOpcode(op_inc); + instructions().append(srcDst->index()); + return srcDst; +} + +RegisterID* BytecodeGenerator::emitDec(RegisterID* srcDst) +{ + emitOpcode(op_dec); + instructions().append(srcDst->index()); + return srcDst; +} + +RegisterID* BytecodeGenerator::emitBinaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2, OperandTypes types) +{ + emitOpcode(opcodeID); + instructions().append(dst->index()); + instructions().append(src1->index()); + instructions().append(src2->index()); + + if (opcodeID == op_bitor || opcodeID == op_bitand || opcodeID == op_bitxor || + opcodeID == op_add || opcodeID == op_mul || opcodeID == op_sub || opcodeID == op_div) + instructions().append(types.toInt()); + + return dst; +} + +RegisterID* BytecodeGenerator::emitEqualityOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2) +{ + if (m_lastOpcodeID == op_typeof) { + int dstIndex; + int srcIndex; + + retrieveLastUnaryOp(dstIndex, srcIndex); + + if (src1->index() == dstIndex + && src1->isTemporary() + && m_codeBlock->isConstantRegisterIndex(src2->index()) + && m_codeBlock->constantRegister(src2->index()).get().isString()) { + const String& value = asString(m_codeBlock->constantRegister(src2->index()).get())->tryGetValue(); + if (value == "undefined") { + rewindUnaryOp(); + emitOpcode(op_is_undefined); + instructions().append(dst->index()); + instructions().append(srcIndex); + return dst; + } + if (value == "boolean") { + rewindUnaryOp(); + emitOpcode(op_is_boolean); + instructions().append(dst->index()); + instructions().append(srcIndex); + return dst; + } + if (value == "number") { + rewindUnaryOp(); + emitOpcode(op_is_number); + instructions().append(dst->index()); + instructions().append(srcIndex); + return dst; + } + if (value == "string") { + rewindUnaryOp(); + emitOpcode(op_is_string); + instructions().append(dst->index()); + instructions().append(srcIndex); + return dst; + } + if (value == "object") { + rewindUnaryOp(); + emitOpcode(op_is_object_or_null); + instructions().append(dst->index()); + instructions().append(srcIndex); + return dst; + } + if (value == "function") { + rewindUnaryOp(); + emitOpcode(op_is_function); + instructions().append(dst->index()); + instructions().append(srcIndex); + return dst; + } + } + } + + emitOpcode(opcodeID); + instructions().append(dst->index()); + instructions().append(src1->index()); + instructions().append(src2->index()); + return dst; +} + +void BytecodeGenerator::emitTypeProfilerExpressionInfo(const JSTextPosition& startDivot, const JSTextPosition& endDivot) +{ + ASSERT(vm()->typeProfiler()); + + unsigned start = startDivot.offset; // Ranges are inclusive of their endpoints, AND 0 indexed. + unsigned end = endDivot.offset - 1; // End Ranges already go one past the inclusive range, so subtract 1. + unsigned instructionOffset = instructions().size() - 1; + m_codeBlock->addTypeProfilerExpressionInfo(instructionOffset, start, end); +} + +void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag flag) +{ + if (!vm()->typeProfiler()) + return; + + if (!registerToProfile) + return; + + emitOpcode(op_profile_type); + instructions().append(registerToProfile->index()); + instructions().append(0); + instructions().append(flag); + instructions().append(0); + instructions().append(resolveType()); + + // Don't emit expression info for this version of profile type. This generally means + // we're profiling information for something that isn't in the actual text of a JavaScript + // program. For example, implicit return undefined from a function call. +} + +void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, const JSTextPosition& startDivot, const JSTextPosition& endDivot) +{ + emitProfileType(registerToProfile, ProfileTypeBytecodeDoesNotHaveGlobalID, startDivot, endDivot); +} + +void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag flag, const JSTextPosition& startDivot, const JSTextPosition& endDivot) +{ + if (!vm()->typeProfiler()) + return; + + if (!registerToProfile) + return; + + // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType? + emitOpcode(op_profile_type); + instructions().append(registerToProfile->index()); + instructions().append(0); + instructions().append(flag); + instructions().append(0); + instructions().append(resolveType()); + + emitTypeProfilerExpressionInfo(startDivot, endDivot); +} + +void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, const Variable& var, const JSTextPosition& startDivot, const JSTextPosition& endDivot) +{ + if (!vm()->typeProfiler()) + return; + + if (!registerToProfile) + return; + + ProfileTypeBytecodeFlag flag; + int symbolTableOrScopeDepth; + if (var.local() || var.offset().isScope()) { + flag = ProfileTypeBytecodeLocallyResolved; + symbolTableOrScopeDepth = var.symbolTableConstantIndex(); + } else { + flag = ProfileTypeBytecodeClosureVar; + symbolTableOrScopeDepth = localScopeDepth(); + } + + // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType? + emitOpcode(op_profile_type); + instructions().append(registerToProfile->index()); + instructions().append(symbolTableOrScopeDepth); + instructions().append(flag); + instructions().append(addConstant(var.ident())); + instructions().append(resolveType()); + + emitTypeProfilerExpressionInfo(startDivot, endDivot); +} + +void BytecodeGenerator::emitProfileControlFlow(int textOffset) +{ + if (vm()->controlFlowProfiler()) { + RELEASE_ASSERT(textOffset >= 0); + size_t bytecodeOffset = instructions().size(); + m_codeBlock->addOpProfileControlFlowBytecodeOffset(bytecodeOffset); + + emitOpcode(op_profile_control_flow); + instructions().append(textOffset); + } +} + +RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, bool b) +{ + return emitLoad(dst, jsBoolean(b)); +} + +RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, const Identifier& identifier) +{ + JSString*& stringInMap = m_stringMap.add(identifier.impl(), nullptr).iterator->value; + if (!stringInMap) + stringInMap = jsOwnedString(vm(), identifier.string()); + return emitLoad(dst, JSValue(stringInMap)); +} + +RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, JSValue v, SourceCodeRepresentation sourceCodeRepresentation) +{ + RegisterID* constantID = addConstantValue(v, sourceCodeRepresentation); + if (dst) + return emitMove(dst, constantID); + return constantID; +} + +RegisterID* BytecodeGenerator::emitLoadGlobalObject(RegisterID* dst) +{ + if (!m_globalObjectRegister) { + int index = m_nextConstantOffset; + m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset); + ++m_nextConstantOffset; + m_codeBlock->addConstant(JSValue()); + m_globalObjectRegister = &m_constantPoolRegisters[index]; + m_codeBlock->setGlobalObjectRegister(VirtualRegister(index)); + } + if (dst) + emitMove(dst, m_globalObjectRegister); + return m_globalObjectRegister; +} + +void BytecodeGenerator::pushLexicalScope(VariableEnvironmentNode* node, bool canOptimizeTDZChecks, RegisterID** constantSymbolTableResult) +{ + VariableEnvironment& environment = node->lexicalVariables(); + pushLexicalScopeInternal(environment, canOptimizeTDZChecks, constantSymbolTableResult, TDZRequirement::UnderTDZ, ScopeType::LetConstScope, ScopeRegisterType::Block); +} + +void BytecodeGenerator::pushLexicalScopeInternal(VariableEnvironment& environment, bool canOptimizeTDZChecks, + RegisterID** constantSymbolTableResult, TDZRequirement tdzRequirement, ScopeType scopeType, ScopeRegisterType scopeRegisterType) +{ + if (!environment.size()) + return; + + if (m_shouldEmitDebugHooks) + environment.markAllVariablesAsCaptured(); + + Strong<SymbolTable> symbolTable(*m_vm, SymbolTable::create(*m_vm)); + switch (scopeType) { + case ScopeType::CatchScope: + symbolTable->setScopeType(SymbolTable::ScopeType::CatchScope); + break; + case ScopeType::LetConstScope: + symbolTable->setScopeType(SymbolTable::ScopeType::LexicalScope); + break; + case ScopeType::FunctionNameScope: + symbolTable->setScopeType(SymbolTable::ScopeType::FunctionNameScope); + break; + } + + bool hasCapturedVariables = false; + { + ConcurrentJITLocker locker(symbolTable->m_lock); + for (auto& entry : environment) { + ASSERT(entry.value.isLet() || entry.value.isConst()); + ASSERT(!entry.value.isVar()); + SymbolTableEntry symbolTableEntry = symbolTable->get(locker, entry.key.get()); + ASSERT(symbolTableEntry.isNull()); + + VarKind varKind = entry.value.isCaptured() ? VarKind::Scope : VarKind::Stack; + VarOffset varOffset; + if (varKind == VarKind::Scope) { + varOffset = VarOffset(symbolTable->takeNextScopeOffset(locker)); + hasCapturedVariables = true; + } else { + ASSERT(varKind == VarKind::Stack); + RegisterID* local = newBlockScopeVariable(); + local->ref(); + varOffset = VarOffset(local->virtualRegister()); + } + + SymbolTableEntry newEntry(varOffset, entry.value.isConst() ? ReadOnly : 0); + symbolTable->add(locker, entry.key.get(), newEntry); + } + } + + RegisterID* newScope = nullptr; + RegisterID* constantSymbolTable = nullptr; + int symbolTableConstantIndex = 0; + if (vm()->typeProfiler()) { + constantSymbolTable = addConstantValue(symbolTable.get()); + symbolTableConstantIndex = constantSymbolTable->index(); + } + if (hasCapturedVariables) { + if (scopeRegisterType == ScopeRegisterType::Block) { + newScope = newBlockScopeVariable(); + newScope->ref(); + } else + newScope = addVar(); + if (!constantSymbolTable) { + ASSERT(!vm()->typeProfiler()); + constantSymbolTable = addConstantValue(symbolTable->cloneScopePart(*m_vm)); + symbolTableConstantIndex = constantSymbolTable->index(); + } + if (constantSymbolTableResult) + *constantSymbolTableResult = constantSymbolTable; + + emitOpcode(op_create_lexical_environment); + instructions().append(newScope->index()); + instructions().append(scopeRegister()->index()); + instructions().append(constantSymbolTable->index()); + instructions().append(addConstantValue(tdzRequirement == TDZRequirement::UnderTDZ ? jsTDZValue() : jsUndefined())->index()); + + emitMove(scopeRegister(), newScope); + + pushScopedControlFlowContext(); + } + + m_symbolTableStack.append(SymbolTableStackEntry{ symbolTable, newScope, false, symbolTableConstantIndex }); + if (tdzRequirement == TDZRequirement::UnderTDZ) + m_TDZStack.append(std::make_pair(environment, canOptimizeTDZChecks)); + + if (tdzRequirement == TDZRequirement::UnderTDZ) { + // Prefill stack variables with the TDZ empty value. + // Scope variables will be initialized to the TDZ empty value when JSLexicalEnvironment is allocated. + for (auto& entry : environment) { + SymbolTableEntry symbolTableEntry = symbolTable->get(entry.key.get()); + ASSERT(!symbolTableEntry.isNull()); + VarOffset offset = symbolTableEntry.varOffset(); + if (offset.isScope()) { + ASSERT(newScope); + continue; + } + ASSERT(offset.isStack()); + emitMoveEmptyValue(®isterFor(offset.stackOffset())); + } + } +} + +void BytecodeGenerator::popLexicalScope(VariableEnvironmentNode* node) +{ + VariableEnvironment& environment = node->lexicalVariables(); + popLexicalScopeInternal(environment, TDZRequirement::UnderTDZ); +} + +void BytecodeGenerator::popLexicalScopeInternal(VariableEnvironment& environment, TDZRequirement tdzRequirement) +{ + if (!environment.size()) + return; + + if (m_shouldEmitDebugHooks) + environment.markAllVariablesAsCaptured(); + + SymbolTableStackEntry stackEntry = m_symbolTableStack.takeLast(); + Strong<SymbolTable> symbolTable = stackEntry.m_symbolTable; + ConcurrentJITLocker locker(symbolTable->m_lock); + bool hasCapturedVariables = false; + for (auto& entry : environment) { + if (entry.value.isCaptured()) { + hasCapturedVariables = true; + continue; + } + SymbolTableEntry symbolTableEntry = symbolTable->get(locker, entry.key.get()); + ASSERT(!symbolTableEntry.isNull()); + VarOffset offset = symbolTableEntry.varOffset(); + ASSERT(offset.isStack()); + RegisterID* local = ®isterFor(offset.stackOffset()); + local->deref(); + } + + if (hasCapturedVariables) { + RELEASE_ASSERT(stackEntry.m_scope); + emitPopScope(scopeRegister(), stackEntry.m_scope); + popScopedControlFlowContext(); + stackEntry.m_scope->deref(); + } + + if (tdzRequirement == TDZRequirement::UnderTDZ) + m_TDZStack.removeLast(); +} + +void BytecodeGenerator::prepareLexicalScopeForNextForLoopIteration(VariableEnvironmentNode* node, RegisterID* loopSymbolTable) +{ + VariableEnvironment& environment = node->lexicalVariables(); + if (!environment.size()) + return; + if (m_shouldEmitDebugHooks) + environment.markAllVariablesAsCaptured(); + if (!environment.hasCapturedVariables()) + return; + + RELEASE_ASSERT(loopSymbolTable); + + // This function needs to do setup for a for loop's activation if any of + // the for loop's lexically declared variables are captured (that is, variables + // declared in the loop header, not the loop body). This function needs to + // make a copy of the current activation and copy the values from the previous + // activation into the new activation because each iteration of a for loop + // gets a new activation. + + SymbolTableStackEntry stackEntry = m_symbolTableStack.last(); + Strong<SymbolTable> symbolTable = stackEntry.m_symbolTable; + RegisterID* loopScope = stackEntry.m_scope; + ASSERT(symbolTable->scopeSize()); + ASSERT(loopScope); + Vector<std::pair<RegisterID*, Identifier>> activationValuesToCopyOver; + + { + ConcurrentJITLocker locker(symbolTable->m_lock); + activationValuesToCopyOver.reserveInitialCapacity(symbolTable->scopeSize()); + + for (auto end = symbolTable->end(locker), ptr = symbolTable->begin(locker); ptr != end; ++ptr) { + if (!ptr->value.varOffset().isScope()) + continue; + + RefPtr<UniquedStringImpl> ident = ptr->key; + Identifier identifier = Identifier::fromUid(m_vm, ident.get()); + + RegisterID* transitionValue = newBlockScopeVariable(); + transitionValue->ref(); + emitGetFromScope(transitionValue, loopScope, variableForLocalEntry(identifier, ptr->value, loopSymbolTable->index(), true), DoNotThrowIfNotFound); + activationValuesToCopyOver.uncheckedAppend(std::make_pair(transitionValue, identifier)); + } + } + + // We need this dynamic behavior of the executing code to ensure + // each loop iteration has a new activation object. (It's pretty ugly). + // Also, this new activation needs to be assigned to the same register + // as the previous scope because the loop body is compiled under + // the assumption that the scope's register index is constant even + // though the value in that register will change on each loop iteration. + RefPtr<RegisterID> parentScope = emitGetParentScope(newTemporary(), loopScope); + emitMove(scopeRegister(), parentScope.get()); + + emitOpcode(op_create_lexical_environment); + instructions().append(loopScope->index()); + instructions().append(scopeRegister()->index()); + instructions().append(loopSymbolTable->index()); + instructions().append(addConstantValue(jsTDZValue())->index()); + + emitMove(scopeRegister(), loopScope); + + { + ConcurrentJITLocker locker(symbolTable->m_lock); + for (auto pair : activationValuesToCopyOver) { + const Identifier& identifier = pair.second; + SymbolTableEntry entry = symbolTable->get(locker, identifier.impl()); + RELEASE_ASSERT(!entry.isNull()); + RegisterID* transitionValue = pair.first; + emitPutToScope(loopScope, variableForLocalEntry(identifier, entry, loopSymbolTable->index(), true), transitionValue, DoNotThrowIfNotFound); + transitionValue->deref(); + } + } +} + +Variable BytecodeGenerator::variable(const Identifier& property) +{ + if (property == propertyNames().thisIdentifier) { + return Variable(property, VarOffset(thisRegister()->virtualRegister()), thisRegister(), + ReadOnly, Variable::SpecialVariable, 0, false); + } + + // We can optimize lookups if the lexical variable is found before a "with" or "catch" + // scope because we're guaranteed static resolution. If we have to pass through + // a "with" or "catch" scope we loose this guarantee. + // We can't optimize cases like this: + // { + // let x = ...; + // with (o) { + // doSomethingWith(x); + // } + // } + // Because we can't gaurantee static resolution on x. + // But, in this case, we are guaranteed static resolution: + // { + // let x = ...; + // with (o) { + // let x = ...; + // doSomethingWith(x); + // } + // } + for (unsigned i = m_symbolTableStack.size(); i--; ) { + SymbolTableStackEntry& stackEntry = m_symbolTableStack[i]; + if (stackEntry.m_isWithScope) + return Variable(property); + Strong<SymbolTable>& symbolTable = stackEntry.m_symbolTable; + SymbolTableEntry symbolTableEntry = symbolTable->get(property.impl()); + if (symbolTableEntry.isNull()) + continue; + if (symbolTable->scopeType() == SymbolTable::ScopeType::FunctionNameScope && m_usesNonStrictEval) { + // We don't know if an eval has introduced a "var" named the same thing as the function name scope variable name. + // We resort to dynamic lookup to answer this question. + return Variable(property); + } + return variableForLocalEntry(property, symbolTableEntry, stackEntry.m_symbolTableConstantIndex, symbolTable->scopeType() == SymbolTable::ScopeType::LexicalScope); + } + + return Variable(property); +} + +Variable BytecodeGenerator::variableForLocalEntry( + const Identifier& property, const SymbolTableEntry& entry, int symbolTableConstantIndex, bool isLexicallyScoped) +{ + VarOffset offset = entry.varOffset(); + + RegisterID* local; + if (offset.isStack()) + local = ®isterFor(offset.stackOffset()); + else + local = nullptr; + + return Variable(property, offset, local, entry.getAttributes(), Variable::NormalVariable, symbolTableConstantIndex, isLexicallyScoped); +} + +void BytecodeGenerator::createVariable( + const Identifier& property, VarKind varKind, SymbolTable* symbolTable, ExistingVariableMode existingVariableMode) +{ + ASSERT(property != propertyNames().thisIdentifier); + ConcurrentJITLocker locker(symbolTable->m_lock); + SymbolTableEntry entry = symbolTable->get(locker, property.impl()); + + if (!entry.isNull()) { + if (existingVariableMode == IgnoreExisting) + return; + + // Do some checks to ensure that the variable we're being asked to create is sufficiently + // compatible with the one we have already created. + + VarOffset offset = entry.varOffset(); + + // We can't change our minds about whether it's captured. + if (offset.kind() != varKind) { + dataLog( + "Trying to add variable called ", property, " as ", varKind, + " but it was already added as ", offset, ".\n"); + RELEASE_ASSERT_NOT_REACHED(); + } + + return; + } + + VarOffset varOffset; + if (varKind == VarKind::Scope) + varOffset = VarOffset(symbolTable->takeNextScopeOffset(locker)); + else { + ASSERT(varKind == VarKind::Stack); + varOffset = VarOffset(virtualRegisterForLocal(m_calleeRegisters.size())); + } + SymbolTableEntry newEntry(varOffset, 0); + symbolTable->add(locker, property.impl(), newEntry); + + if (varKind == VarKind::Stack) { + RegisterID* local = addVar(); + RELEASE_ASSERT(local->index() == varOffset.stackOffset().offset()); + } +} + +void BytecodeGenerator::emitCheckHasInstance(RegisterID* dst, RegisterID* value, RegisterID* base, Label* target) +{ + size_t begin = instructions().size(); + emitOpcode(op_check_has_instance); + instructions().append(dst->index()); + instructions().append(value->index()); + instructions().append(base->index()); + instructions().append(target->bind(begin, instructions().size())); +} + +// Indicates the least upper bound of resolve type based on local scope. The bytecode linker +// will start with this ResolveType and compute the least upper bound including intercepting scopes. +ResolveType BytecodeGenerator::resolveType() +{ + for (unsigned i = m_symbolTableStack.size(); i--; ) { + if (m_symbolTableStack[i].m_isWithScope) + return Dynamic; + if (m_usesNonStrictEval && m_symbolTableStack[i].m_symbolTable->scopeType() == SymbolTable::ScopeType::FunctionNameScope) { + // What we really want here is something like LocalClosureVarWithVarInjectionsCheck but it's probably + // not worth inventing just for the function name scope. + return Dynamic; + } + } + + if (m_usesNonStrictEval) + return GlobalPropertyWithVarInjectionChecks; + return GlobalProperty; +} + +RegisterID* BytecodeGenerator::emitResolveScope(RegisterID* dst, const Variable& variable) +{ + switch (variable.offset().kind()) { + case VarKind::Stack: + return nullptr; + + case VarKind::DirectArgument: + return argumentsRegister(); + + case VarKind::Scope: + // This always refers to the activation that *we* allocated, and not the current scope that code + // lives in. Note that this will change once we have proper support for block scoping. Once that + // changes, it will be correct for this code to return scopeRegister(). The only reason why we + // don't do that already is that m_lexicalEnvironment is required by ConstDeclNode. ConstDeclNode + // requires weird things because it is a shameful pile of nonsense, but block scoping would make + // that code sensible and obviate the need for us to do bad things. + for (unsigned i = m_symbolTableStack.size(); i--; ) { + SymbolTableStackEntry& stackEntry = m_symbolTableStack[i]; + // We should not resolve a variable to VarKind::Scope if a "with" scope lies in between the current + // scope and the resolved scope. + RELEASE_ASSERT(!stackEntry.m_isWithScope); + + if (stackEntry.m_symbolTable->get(variable.ident().impl()).isNull()) + continue; + + RegisterID* scope = stackEntry.m_scope; + RELEASE_ASSERT(scope); + return scope; + } + + RELEASE_ASSERT_NOT_REACHED(); + return nullptr; + + case VarKind::Invalid: + // Indicates non-local resolution. + + m_codeBlock->addPropertyAccessInstruction(instructions().size()); + + // resolve_scope dst, id, ResolveType, depth + dst = tempDestination(dst); + emitOpcode(op_resolve_scope); + instructions().append(kill(dst)); + instructions().append(scopeRegister()->index()); + instructions().append(addConstant(variable.ident())); + instructions().append(resolveType()); + instructions().append(localScopeDepth()); + instructions().append(0); + return dst; + } + + RELEASE_ASSERT_NOT_REACHED(); + return nullptr; +} + +RegisterID* BytecodeGenerator::emitGetFromScope(RegisterID* dst, RegisterID* scope, const Variable& variable, ResolveMode resolveMode) +{ + switch (variable.offset().kind()) { + case VarKind::Stack: + return emitMove(dst, variable.local()); + + case VarKind::DirectArgument: { + UnlinkedValueProfile profile = emitProfiledOpcode(op_get_from_arguments); + instructions().append(kill(dst)); + instructions().append(scope->index()); + instructions().append(variable.offset().capturedArgumentsOffset().offset()); + instructions().append(profile); + return dst; + } + + case VarKind::Scope: + case VarKind::Invalid: { + m_codeBlock->addPropertyAccessInstruction(instructions().size()); + + // get_from_scope dst, scope, id, ResolveModeAndType, Structure, Operand + UnlinkedValueProfile profile = emitProfiledOpcode(op_get_from_scope); + instructions().append(kill(dst)); + instructions().append(scope->index()); + instructions().append(addConstant(variable.ident())); + instructions().append(ResolveModeAndType(resolveMode, variable.offset().isScope() ? LocalClosureVar : resolveType()).operand()); + instructions().append(localScopeDepth()); + instructions().append(variable.offset().isScope() ? variable.offset().scopeOffset().offset() : 0); + instructions().append(profile); + return dst; + } } + + RELEASE_ASSERT_NOT_REACHED(); +} + +RegisterID* BytecodeGenerator::emitPutToScope(RegisterID* scope, const Variable& variable, RegisterID* value, ResolveMode resolveMode) +{ + switch (variable.offset().kind()) { + case VarKind::Stack: + emitMove(variable.local(), value); + return value; + + case VarKind::DirectArgument: + emitOpcode(op_put_to_arguments); + instructions().append(scope->index()); + instructions().append(variable.offset().capturedArgumentsOffset().offset()); + instructions().append(value->index()); + return value; + + case VarKind::Scope: + case VarKind::Invalid: { + m_codeBlock->addPropertyAccessInstruction(instructions().size()); + + // put_to_scope scope, id, value, ResolveModeAndType, Structure, Operand + emitOpcode(op_put_to_scope); + instructions().append(scope->index()); + instructions().append(addConstant(variable.ident())); + instructions().append(value->index()); + ScopeOffset offset; + if (variable.offset().isScope()) { + offset = variable.offset().scopeOffset(); + instructions().append(ResolveModeAndType(resolveMode, LocalClosureVar).operand()); + instructions().append(variable.symbolTableConstantIndex()); + } else { + ASSERT(resolveType() != LocalClosureVar); + instructions().append(ResolveModeAndType(resolveMode, resolveType()).operand()); + instructions().append(localScopeDepth()); + } + instructions().append(!!offset ? offset.offset() : 0); + return value; + } } + + RELEASE_ASSERT_NOT_REACHED(); +} + +RegisterID* BytecodeGenerator::initializeVariable(const Variable& variable, RegisterID* value) +{ + RELEASE_ASSERT(variable.offset().kind() != VarKind::Invalid); + RegisterID* scope = emitResolveScope(nullptr, variable); + return emitPutToScope(scope, variable, value, ThrowIfNotFound); +} + +RegisterID* BytecodeGenerator::emitInstanceOf(RegisterID* dst, RegisterID* value, RegisterID* basePrototype) +{ + emitOpcode(op_instanceof); + instructions().append(dst->index()); + instructions().append(value->index()); + instructions().append(basePrototype->index()); + return dst; +} + +RegisterID* BytecodeGenerator::emitGetById(RegisterID* dst, RegisterID* base, const Identifier& property) +{ + m_codeBlock->addPropertyAccessInstruction(instructions().size()); + + UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_id); + instructions().append(kill(dst)); + instructions().append(base->index()); + instructions().append(addConstant(property)); + instructions().append(0); + instructions().append(0); + instructions().append(0); + instructions().append(0); + instructions().append(profile); + return dst; +} + +RegisterID* BytecodeGenerator::emitPutById(RegisterID* base, const Identifier& property, RegisterID* value) +{ + unsigned propertyIndex = addConstant(property); + + m_staticPropertyAnalyzer.putById(base->index(), propertyIndex); + + m_codeBlock->addPropertyAccessInstruction(instructions().size()); + + emitOpcode(op_put_by_id); + instructions().append(base->index()); + instructions().append(propertyIndex); + instructions().append(value->index()); + instructions().append(0); + instructions().append(0); + instructions().append(0); + instructions().append(0); + instructions().append(0); + + return value; +} + +RegisterID* BytecodeGenerator::emitDirectPutById(RegisterID* base, const Identifier& property, RegisterID* value, PropertyNode::PutType putType) +{ + ASSERT(!parseIndex(property)); + unsigned propertyIndex = addConstant(property); + + m_staticPropertyAnalyzer.putById(base->index(), propertyIndex); + + m_codeBlock->addPropertyAccessInstruction(instructions().size()); + + emitOpcode(op_put_by_id); + instructions().append(base->index()); + instructions().append(propertyIndex); + instructions().append(value->index()); + instructions().append(0); + instructions().append(0); + instructions().append(0); + instructions().append(0); + instructions().append(putType == PropertyNode::KnownDirect || property != m_vm->propertyNames->underscoreProto); + return value; +} + +void BytecodeGenerator::emitPutGetterById(RegisterID* base, const Identifier& property, RegisterID* getter) +{ + unsigned propertyIndex = addConstant(property); + m_staticPropertyAnalyzer.putById(base->index(), propertyIndex); + + emitOpcode(op_put_getter_by_id); + instructions().append(base->index()); + instructions().append(propertyIndex); + instructions().append(getter->index()); +} + +void BytecodeGenerator::emitPutSetterById(RegisterID* base, const Identifier& property, RegisterID* setter) +{ + unsigned propertyIndex = addConstant(property); + m_staticPropertyAnalyzer.putById(base->index(), propertyIndex); + + emitOpcode(op_put_setter_by_id); + instructions().append(base->index()); + instructions().append(propertyIndex); + instructions().append(setter->index()); +} + +void BytecodeGenerator::emitPutGetterSetter(RegisterID* base, const Identifier& property, RegisterID* getter, RegisterID* setter) +{ + unsigned propertyIndex = addConstant(property); + + m_staticPropertyAnalyzer.putById(base->index(), propertyIndex); + + emitOpcode(op_put_getter_setter); + instructions().append(base->index()); + instructions().append(propertyIndex); + instructions().append(getter->index()); + instructions().append(setter->index()); +} + +RegisterID* BytecodeGenerator::emitDeleteById(RegisterID* dst, RegisterID* base, const Identifier& property) +{ + emitOpcode(op_del_by_id); + instructions().append(dst->index()); + instructions().append(base->index()); + instructions().append(addConstant(property)); + return dst; +} + +RegisterID* BytecodeGenerator::emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* property) +{ + for (size_t i = m_forInContextStack.size(); i > 0; i--) { + ForInContext* context = m_forInContextStack[i - 1].get(); + if (context->local() != property) + continue; + + if (!context->isValid()) + break; + + if (context->type() == ForInContext::IndexedForInContextType) { + property = static_cast<IndexedForInContext*>(context)->index(); + break; + } + + ASSERT(context->type() == ForInContext::StructureForInContextType); + StructureForInContext* structureContext = static_cast<StructureForInContext*>(context); + UnlinkedValueProfile profile = emitProfiledOpcode(op_get_direct_pname); + instructions().append(kill(dst)); + instructions().append(base->index()); + instructions().append(property->index()); + instructions().append(structureContext->index()->index()); + instructions().append(structureContext->enumerator()->index()); + instructions().append(profile); + return dst; + } + + UnlinkedArrayProfile arrayProfile = newArrayProfile(); + UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_val); + instructions().append(kill(dst)); + instructions().append(base->index()); + instructions().append(property->index()); + instructions().append(arrayProfile); + instructions().append(profile); + return dst; +} + +RegisterID* BytecodeGenerator::emitPutByVal(RegisterID* base, RegisterID* property, RegisterID* value) +{ + UnlinkedArrayProfile arrayProfile = newArrayProfile(); + emitOpcode(op_put_by_val); + instructions().append(base->index()); + instructions().append(property->index()); + instructions().append(value->index()); + instructions().append(arrayProfile); + + return value; +} + +RegisterID* BytecodeGenerator::emitDirectPutByVal(RegisterID* base, RegisterID* property, RegisterID* value) +{ + UnlinkedArrayProfile arrayProfile = newArrayProfile(); + emitOpcode(op_put_by_val_direct); + instructions().append(base->index()); + instructions().append(property->index()); + instructions().append(value->index()); + instructions().append(arrayProfile); + return value; +} + +RegisterID* BytecodeGenerator::emitDeleteByVal(RegisterID* dst, RegisterID* base, RegisterID* property) +{ + emitOpcode(op_del_by_val); + instructions().append(dst->index()); + instructions().append(base->index()); + instructions().append(property->index()); + return dst; +} + +RegisterID* BytecodeGenerator::emitPutByIndex(RegisterID* base, unsigned index, RegisterID* value) +{ + emitOpcode(op_put_by_index); + instructions().append(base->index()); + instructions().append(index); + instructions().append(value->index()); + return value; +} + +RegisterID* BytecodeGenerator::emitCreateThis(RegisterID* dst) +{ + size_t begin = instructions().size(); + m_staticPropertyAnalyzer.createThis(m_thisRegister.index(), begin + 3); + + m_codeBlock->addPropertyAccessInstruction(instructions().size()); + emitOpcode(op_create_this); + instructions().append(m_thisRegister.index()); + instructions().append(m_thisRegister.index()); + instructions().append(0); + instructions().append(0); + return dst; +} + +void BytecodeGenerator::emitTDZCheck(RegisterID* target) +{ + emitOpcode(op_check_tdz); + instructions().append(target->index()); +} + +bool BytecodeGenerator::needsTDZCheck(const Variable& variable) +{ + for (unsigned i = m_TDZStack.size(); i--;) { + VariableEnvironment& identifiers = m_TDZStack[i].first; + if (identifiers.contains(variable.ident().impl())) + return true; + } + + return false; +} + +void BytecodeGenerator::emitTDZCheckIfNecessary(const Variable& variable, RegisterID* target, RegisterID* scope) +{ + if (needsTDZCheck(variable)) { + if (target) + emitTDZCheck(target); + else { + RELEASE_ASSERT(!variable.isLocal() && scope); + RefPtr<RegisterID> result = emitGetFromScope(newTemporary(), scope, variable, DoNotThrowIfNotFound); + emitTDZCheck(result.get()); + } + } +} + +void BytecodeGenerator::liftTDZCheckIfPossible(const Variable& variable) +{ + RefPtr<UniquedStringImpl> identifier(variable.ident().impl()); + for (unsigned i = m_TDZStack.size(); i--;) { + VariableEnvironment& environment = m_TDZStack[i].first; + if (environment.contains(identifier)) { + bool isSyntacticallyAbleToOptimizeTDZ = m_TDZStack[i].second; + if (isSyntacticallyAbleToOptimizeTDZ) { + bool wasRemoved = environment.remove(identifier); + RELEASE_ASSERT(wasRemoved); + } + break; + } + } +} + +void BytecodeGenerator::getVariablesUnderTDZ(VariableEnvironment& result) +{ + for (auto& pair : m_TDZStack) { + VariableEnvironment& environment = pair.first; + for (auto entry : environment) + result.add(entry.key.get()); + } +} + +RegisterID* BytecodeGenerator::emitNewObject(RegisterID* dst) +{ + size_t begin = instructions().size(); + m_staticPropertyAnalyzer.newObject(dst->index(), begin + 2); + + emitOpcode(op_new_object); + instructions().append(dst->index()); + instructions().append(0); + instructions().append(newObjectAllocationProfile()); + return dst; +} + +unsigned BytecodeGenerator::addConstantBuffer(unsigned length) +{ + return m_codeBlock->addConstantBuffer(length); +} + +JSString* BytecodeGenerator::addStringConstant(const Identifier& identifier) +{ + JSString*& stringInMap = m_stringMap.add(identifier.impl(), nullptr).iterator->value; + if (!stringInMap) { + stringInMap = jsString(vm(), identifier.string()); + addConstantValue(stringInMap); + } + return stringInMap; +} + +JSTemplateRegistryKey* BytecodeGenerator::addTemplateRegistryKeyConstant(const TemplateRegistryKey& templateRegistryKey) +{ + JSTemplateRegistryKey*& templateRegistryKeyInMap = m_templateRegistryKeyMap.add(templateRegistryKey, nullptr).iterator->value; + if (!templateRegistryKeyInMap) { + templateRegistryKeyInMap = JSTemplateRegistryKey::create(*vm(), templateRegistryKey); + addConstantValue(templateRegistryKeyInMap); + } + return templateRegistryKeyInMap; +} + +RegisterID* BytecodeGenerator::emitNewArray(RegisterID* dst, ElementNode* elements, unsigned length) +{ +#if !ASSERT_DISABLED + unsigned checkLength = 0; +#endif + bool hadVariableExpression = false; + if (length) { + for (ElementNode* n = elements; n; n = n->next()) { + if (!n->value()->isConstant()) { + hadVariableExpression = true; + break; + } + if (n->elision()) + break; +#if !ASSERT_DISABLED + checkLength++; +#endif + } + if (!hadVariableExpression) { + ASSERT(length == checkLength); + unsigned constantBufferIndex = addConstantBuffer(length); + JSValue* constantBuffer = m_codeBlock->constantBuffer(constantBufferIndex).data(); + unsigned index = 0; + for (ElementNode* n = elements; index < length; n = n->next()) { + ASSERT(n->value()->isConstant()); + constantBuffer[index++] = static_cast<ConstantNode*>(n->value())->jsValue(*this); + } + emitOpcode(op_new_array_buffer); + instructions().append(dst->index()); + instructions().append(constantBufferIndex); + instructions().append(length); + instructions().append(newArrayAllocationProfile()); + return dst; + } + } + + Vector<RefPtr<RegisterID>, 16, UnsafeVectorOverflow> argv; + for (ElementNode* n = elements; n; n = n->next()) { + if (!length) + break; + length--; + ASSERT(!n->value()->isSpreadExpression()); + argv.append(newTemporary()); + // op_new_array requires the initial values to be a sequential range of registers + ASSERT(argv.size() == 1 || argv[argv.size() - 1]->index() == argv[argv.size() - 2]->index() - 1); + emitNode(argv.last().get(), n->value()); + } + ASSERT(!length); + emitOpcode(op_new_array); + instructions().append(dst->index()); + instructions().append(argv.size() ? argv[0]->index() : 0); // argv + instructions().append(argv.size()); // argc + instructions().append(newArrayAllocationProfile()); + return dst; +} + +RegisterID* BytecodeGenerator::emitNewFunction(RegisterID* dst, FunctionMetadataNode* function) +{ + return emitNewFunctionInternal(dst, m_codeBlock->addFunctionDecl(makeFunction(function))); +} + +RegisterID* BytecodeGenerator::emitNewFunctionInternal(RegisterID* dst, unsigned index) +{ + emitOpcode(op_new_func); + instructions().append(dst->index()); + instructions().append(scopeRegister()->index()); + instructions().append(index); + return dst; +} + +RegisterID* BytecodeGenerator::emitNewRegExp(RegisterID* dst, RegExp* regExp) +{ + emitOpcode(op_new_regexp); + instructions().append(dst->index()); + instructions().append(addRegExp(regExp)); + return dst; +} + +RegisterID* BytecodeGenerator::emitNewFunctionExpression(RegisterID* r0, FuncExprNode* n) +{ + FunctionMetadataNode* metadata = n->metadata(); + unsigned index = m_codeBlock->addFunctionExpr(makeFunction(metadata)); + + emitOpcode(op_new_func_exp); + instructions().append(r0->index()); + instructions().append(scopeRegister()->index()); + instructions().append(index); + return r0; +} + +RegisterID* BytecodeGenerator::emitNewDefaultConstructor(RegisterID* dst, ConstructorKind constructorKind, const Identifier& name) +{ + UnlinkedFunctionExecutable* executable = m_vm->builtinExecutables()->createDefaultConstructor(constructorKind, name); + + unsigned index = m_codeBlock->addFunctionExpr(executable); + + emitOpcode(op_new_func_exp); + instructions().append(dst->index()); + instructions().append(scopeRegister()->index()); + instructions().append(index); + return dst; +} + +RegisterID* BytecodeGenerator::emitCall(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd) +{ + return emitCall(op_call, dst, func, expectedFunction, callArguments, divot, divotStart, divotEnd); +} + +RegisterID* BytecodeGenerator::emitCallEval(RegisterID* dst, RegisterID* func, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd) +{ + return emitCall(op_call_eval, dst, func, NoExpectedFunction, callArguments, divot, divotStart, divotEnd); +} + +ExpectedFunction BytecodeGenerator::expectedFunctionForIdentifier(const Identifier& identifier) +{ + if (identifier == m_vm->propertyNames->Object || identifier == m_vm->propertyNames->ObjectPrivateName) + return ExpectObjectConstructor; + if (identifier == m_vm->propertyNames->Array || identifier == m_vm->propertyNames->ArrayPrivateName) + return ExpectArrayConstructor; + return NoExpectedFunction; +} + +ExpectedFunction BytecodeGenerator::emitExpectedFunctionSnippet(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, Label* done) +{ + RefPtr<Label> realCall = newLabel(); + switch (expectedFunction) { + case ExpectObjectConstructor: { + // If the number of arguments is non-zero, then we can't do anything interesting. + if (callArguments.argumentCountIncludingThis() >= 2) + return NoExpectedFunction; + + size_t begin = instructions().size(); + emitOpcode(op_jneq_ptr); + instructions().append(func->index()); + instructions().append(Special::ObjectConstructor); + instructions().append(realCall->bind(begin, instructions().size())); + + if (dst != ignoredResult()) + emitNewObject(dst); + break; + } + + case ExpectArrayConstructor: { + // If you're doing anything other than "new Array()" or "new Array(foo)" then we + // don't do inline it, for now. The only reason is that call arguments are in + // the opposite order of what op_new_array expects, so we'd either need to change + // how op_new_array works or we'd need an op_new_array_reverse. Neither of these + // things sounds like it's worth it. + if (callArguments.argumentCountIncludingThis() > 2) + return NoExpectedFunction; + + size_t begin = instructions().size(); + emitOpcode(op_jneq_ptr); + instructions().append(func->index()); + instructions().append(Special::ArrayConstructor); + instructions().append(realCall->bind(begin, instructions().size())); + + if (dst != ignoredResult()) { + if (callArguments.argumentCountIncludingThis() == 2) { + emitOpcode(op_new_array_with_size); + instructions().append(dst->index()); + instructions().append(callArguments.argumentRegister(0)->index()); + instructions().append(newArrayAllocationProfile()); + } else { + ASSERT(callArguments.argumentCountIncludingThis() == 1); + emitOpcode(op_new_array); + instructions().append(dst->index()); + instructions().append(0); + instructions().append(0); + instructions().append(newArrayAllocationProfile()); + } + } + break; + } + + default: + ASSERT(expectedFunction == NoExpectedFunction); + return NoExpectedFunction; + } + + size_t begin = instructions().size(); + emitOpcode(op_jmp); + instructions().append(done->bind(begin, instructions().size())); + emitLabel(realCall.get()); + + return expectedFunction; +} + +RegisterID* BytecodeGenerator::emitCall(OpcodeID opcodeID, RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd) +{ + ASSERT(opcodeID == op_call || opcodeID == op_call_eval); + ASSERT(func->refCount()); + + if (m_shouldEmitProfileHooks) + emitMove(callArguments.profileHookRegister(), func); + + // Generate code for arguments. + unsigned argument = 0; + if (callArguments.argumentsNode()) { + ArgumentListNode* n = callArguments.argumentsNode()->m_listNode; + if (n && n->m_expr->isSpreadExpression()) { + RELEASE_ASSERT(!n->m_next); + auto expression = static_cast<SpreadExpressionNode*>(n->m_expr)->expression(); + RefPtr<RegisterID> argumentRegister; + argumentRegister = expression->emitBytecode(*this, callArguments.argumentRegister(0)); + RefPtr<RegisterID> thisRegister = emitMove(newTemporary(), callArguments.thisRegister()); + return emitCallVarargs(dst, func, callArguments.thisRegister(), argumentRegister.get(), newTemporary(), 0, callArguments.profileHookRegister(), divot, divotStart, divotEnd); + } + for (; n; n = n->m_next) + emitNode(callArguments.argumentRegister(argument++), n); + } + + // Reserve space for call frame. + Vector<RefPtr<RegisterID>, JSStack::CallFrameHeaderSize, UnsafeVectorOverflow> callFrame; + for (int i = 0; i < JSStack::CallFrameHeaderSize; ++i) + callFrame.append(newTemporary()); + + if (m_shouldEmitProfileHooks) { + emitOpcode(op_profile_will_call); + instructions().append(callArguments.profileHookRegister()->index()); + } + + emitExpressionInfo(divot, divotStart, divotEnd); + + RefPtr<Label> done = newLabel(); + expectedFunction = emitExpectedFunctionSnippet(dst, func, expectedFunction, callArguments, done.get()); + + // Emit call. + UnlinkedArrayProfile arrayProfile = newArrayProfile(); + UnlinkedValueProfile profile = emitProfiledOpcode(opcodeID); + ASSERT(dst); + ASSERT(dst != ignoredResult()); + instructions().append(dst->index()); + instructions().append(func->index()); + instructions().append(callArguments.argumentCountIncludingThis()); + instructions().append(callArguments.stackOffset()); + instructions().append(m_codeBlock->addLLIntCallLinkInfo()); + instructions().append(0); + instructions().append(arrayProfile); + instructions().append(profile); + + if (expectedFunction != NoExpectedFunction) + emitLabel(done.get()); + + if (m_shouldEmitProfileHooks) { + emitOpcode(op_profile_did_call); + instructions().append(callArguments.profileHookRegister()->index()); + } + + return dst; +} + +RegisterID* BytecodeGenerator::emitCallVarargs(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, RegisterID* profileHookRegister, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd) +{ + return emitCallVarargs(op_call_varargs, dst, func, thisRegister, arguments, firstFreeRegister, firstVarArgOffset, profileHookRegister, divot, divotStart, divotEnd); +} + +RegisterID* BytecodeGenerator::emitConstructVarargs(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, RegisterID* profileHookRegister, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd) +{ + return emitCallVarargs(op_construct_varargs, dst, func, thisRegister, arguments, firstFreeRegister, firstVarArgOffset, profileHookRegister, divot, divotStart, divotEnd); +} + +RegisterID* BytecodeGenerator::emitCallVarargs(OpcodeID opcode, RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, RegisterID* profileHookRegister, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd) +{ + if (m_shouldEmitProfileHooks) { + emitMove(profileHookRegister, func); + emitOpcode(op_profile_will_call); + instructions().append(profileHookRegister->index()); + } + + emitExpressionInfo(divot, divotStart, divotEnd); + + // Emit call. + UnlinkedArrayProfile arrayProfile = newArrayProfile(); + UnlinkedValueProfile profile = emitProfiledOpcode(opcode); + ASSERT(dst != ignoredResult()); + instructions().append(dst->index()); + instructions().append(func->index()); + instructions().append(thisRegister ? thisRegister->index() : 0); + instructions().append(arguments->index()); + instructions().append(firstFreeRegister->index()); + instructions().append(firstVarArgOffset); + instructions().append(arrayProfile); + instructions().append(profile); + if (m_shouldEmitProfileHooks) { + emitOpcode(op_profile_did_call); + instructions().append(profileHookRegister->index()); + } + return dst; +} + +void BytecodeGenerator::emitCallDefineProperty(RegisterID* newObj, RegisterID* propertyNameRegister, + RegisterID* valueRegister, RegisterID* getterRegister, RegisterID* setterRegister, unsigned options, const JSTextPosition& position) +{ + RefPtr<RegisterID> descriptorRegister = emitNewObject(newTemporary()); + + RefPtr<RegisterID> trueRegister = emitLoad(newTemporary(), true); + if (options & PropertyConfigurable) + emitDirectPutById(descriptorRegister.get(), propertyNames().configurable, trueRegister.get(), PropertyNode::Unknown); + if (options & PropertyWritable) + emitDirectPutById(descriptorRegister.get(), propertyNames().writable, trueRegister.get(), PropertyNode::Unknown); + else if (valueRegister) { + RefPtr<RegisterID> falseRegister = emitLoad(newTemporary(), false); + emitDirectPutById(descriptorRegister.get(), propertyNames().writable, falseRegister.get(), PropertyNode::Unknown); + } + if (options & PropertyEnumerable) + emitDirectPutById(descriptorRegister.get(), propertyNames().enumerable, trueRegister.get(), PropertyNode::Unknown); + + if (valueRegister) + emitDirectPutById(descriptorRegister.get(), propertyNames().value, valueRegister, PropertyNode::Unknown); + if (getterRegister) + emitDirectPutById(descriptorRegister.get(), propertyNames().get, getterRegister, PropertyNode::Unknown); + if (setterRegister) + emitDirectPutById(descriptorRegister.get(), propertyNames().set, setterRegister, PropertyNode::Unknown); + + RefPtr<RegisterID> definePropertyRegister = emitMoveLinkTimeConstant(newTemporary(), LinkTimeConstant::DefinePropertyFunction); + + CallArguments callArguments(*this, nullptr, 3); + emitLoad(callArguments.thisRegister(), jsUndefined()); + emitMove(callArguments.argumentRegister(0), newObj); + emitMove(callArguments.argumentRegister(1), propertyNameRegister); + emitMove(callArguments.argumentRegister(2), descriptorRegister.get()); + + emitCall(newTemporary(), definePropertyRegister.get(), NoExpectedFunction, callArguments, position, position, position); +} + +RegisterID* BytecodeGenerator::emitReturn(RegisterID* src) +{ + if (isConstructor()) { + bool derived = constructorKind() == ConstructorKind::Derived; + if (derived && src->index() == m_thisRegister.index()) + emitTDZCheck(src); + + RefPtr<Label> isObjectLabel = newLabel(); + emitJumpIfTrue(emitIsObject(newTemporary(), src), isObjectLabel.get()); + + if (derived) { + RefPtr<Label> isUndefinedLabel = newLabel(); + emitJumpIfTrue(emitIsUndefined(newTemporary(), src), isUndefinedLabel.get()); + emitThrowTypeError("Cannot return a non-object type in the constructor of a derived class."); + emitLabel(isUndefinedLabel.get()); + if (constructorKind() == ConstructorKind::Derived) + emitTDZCheck(&m_thisRegister); + } + + emitUnaryNoDstOp(op_ret, &m_thisRegister); + + emitLabel(isObjectLabel.get()); + } + + return emitUnaryNoDstOp(op_ret, src); +} + +RegisterID* BytecodeGenerator::emitUnaryNoDstOp(OpcodeID opcodeID, RegisterID* src) +{ + emitOpcode(opcodeID); + instructions().append(src->index()); + return src; +} + +RegisterID* BytecodeGenerator::emitConstruct(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd) +{ + ASSERT(func->refCount()); + + if (m_shouldEmitProfileHooks) + emitMove(callArguments.profileHookRegister(), func); + + // Generate code for arguments. + unsigned argument = 0; + if (ArgumentsNode* argumentsNode = callArguments.argumentsNode()) { + + ArgumentListNode* n = callArguments.argumentsNode()->m_listNode; + if (n && n->m_expr->isSpreadExpression()) { + RELEASE_ASSERT(!n->m_next); + auto expression = static_cast<SpreadExpressionNode*>(n->m_expr)->expression(); + RefPtr<RegisterID> argumentRegister; + argumentRegister = expression->emitBytecode(*this, callArguments.argumentRegister(0)); + return emitConstructVarargs(dst, func, callArguments.thisRegister(), argumentRegister.get(), newTemporary(), 0, callArguments.profileHookRegister(), divot, divotStart, divotEnd); + } + + for (ArgumentListNode* n = argumentsNode->m_listNode; n; n = n->m_next) + emitNode(callArguments.argumentRegister(argument++), n); + } + + if (m_shouldEmitProfileHooks) { + emitOpcode(op_profile_will_call); + instructions().append(callArguments.profileHookRegister()->index()); + } + + // Reserve space for call frame. + Vector<RefPtr<RegisterID>, JSStack::CallFrameHeaderSize, UnsafeVectorOverflow> callFrame; + for (int i = 0; i < JSStack::CallFrameHeaderSize; ++i) + callFrame.append(newTemporary()); + + emitExpressionInfo(divot, divotStart, divotEnd); + + RefPtr<Label> done = newLabel(); + expectedFunction = emitExpectedFunctionSnippet(dst, func, expectedFunction, callArguments, done.get()); + + UnlinkedValueProfile profile = emitProfiledOpcode(op_construct); + ASSERT(dst != ignoredResult()); + instructions().append(dst->index()); + instructions().append(func->index()); + instructions().append(callArguments.argumentCountIncludingThis()); + instructions().append(callArguments.stackOffset()); + instructions().append(m_codeBlock->addLLIntCallLinkInfo()); + instructions().append(0); + instructions().append(0); + instructions().append(profile); + + if (expectedFunction != NoExpectedFunction) + emitLabel(done.get()); + + if (m_shouldEmitProfileHooks) { + emitOpcode(op_profile_did_call); + instructions().append(callArguments.profileHookRegister()->index()); + } + + return dst; +} + +RegisterID* BytecodeGenerator::emitStrcat(RegisterID* dst, RegisterID* src, int count) +{ + emitOpcode(op_strcat); + instructions().append(dst->index()); + instructions().append(src->index()); + instructions().append(count); + + return dst; +} + +void BytecodeGenerator::emitToPrimitive(RegisterID* dst, RegisterID* src) +{ + emitOpcode(op_to_primitive); + instructions().append(dst->index()); + instructions().append(src->index()); +} + +void BytecodeGenerator::emitGetScope() +{ + emitOpcode(op_get_scope); + instructions().append(scopeRegister()->index()); +} + +RegisterID* BytecodeGenerator::emitPushWithScope(RegisterID* objectScope) +{ + pushScopedControlFlowContext(); + RegisterID* newScope = newBlockScopeVariable(); + newScope->ref(); + + emitOpcode(op_push_with_scope); + instructions().append(newScope->index()); + instructions().append(objectScope->index()); + instructions().append(scopeRegister()->index()); + + emitMove(scopeRegister(), newScope); + m_symbolTableStack.append(SymbolTableStackEntry{ Strong<SymbolTable>(), newScope, true, 0 }); + + return newScope; +} + +RegisterID* BytecodeGenerator::emitGetParentScope(RegisterID* dst, RegisterID* scope) +{ + emitOpcode(op_get_parent_scope); + instructions().append(dst->index()); + instructions().append(scope->index()); + return dst; +} + +void BytecodeGenerator::emitPopScope(RegisterID* dst, RegisterID* scope) +{ + RefPtr<RegisterID> parentScope = emitGetParentScope(newTemporary(), scope); + emitMove(dst, parentScope.get()); +} + +void BytecodeGenerator::emitPopWithScope() +{ + emitPopScope(scopeRegister(), scopeRegister()); + popScopedControlFlowContext(); + SymbolTableStackEntry stackEntry = m_symbolTableStack.takeLast(); + stackEntry.m_scope->deref(); + RELEASE_ASSERT(stackEntry.m_isWithScope); +} + +void BytecodeGenerator::emitDebugHook(DebugHookID debugHookID, unsigned line, unsigned charOffset, unsigned lineStart) +{ +#if ENABLE(DEBUG_WITH_BREAKPOINT) + if (debugHookID != DidReachBreakpoint) + return; +#else + if (!m_shouldEmitDebugHooks) + return; +#endif + JSTextPosition divot(line, charOffset, lineStart); + emitExpressionInfo(divot, divot, divot); + emitOpcode(op_debug); + instructions().append(debugHookID); + instructions().append(false); +} + +void BytecodeGenerator::pushFinallyContext(StatementNode* finallyBlock) +{ + // Reclaim free label scopes. + while (m_labelScopes.size() && !m_labelScopes.last().refCount()) + m_labelScopes.removeLast(); + + ControlFlowContext scope; + scope.isFinallyBlock = true; + FinallyContext context = { + finallyBlock, + nullptr, + nullptr, + static_cast<unsigned>(m_scopeContextStack.size()), + static_cast<unsigned>(m_switchContextStack.size()), + static_cast<unsigned>(m_forInContextStack.size()), + static_cast<unsigned>(m_tryContextStack.size()), + static_cast<unsigned>(m_labelScopes.size()), + static_cast<unsigned>(m_symbolTableStack.size()), + m_finallyDepth, + m_localScopeDepth + }; + scope.finallyContext = context; + m_scopeContextStack.append(scope); + m_finallyDepth++; +} + +void BytecodeGenerator::pushIteratorCloseContext(RegisterID* iterator, ThrowableExpressionData* node) +{ + // Reclaim free label scopes. + while (m_labelScopes.size() && !m_labelScopes.last().refCount()) + m_labelScopes.removeLast(); + + ControlFlowContext scope; + scope.isFinallyBlock = true; + FinallyContext context = { + nullptr, + iterator, + node, + static_cast<unsigned>(m_scopeContextStack.size()), + static_cast<unsigned>(m_switchContextStack.size()), + static_cast<unsigned>(m_forInContextStack.size()), + static_cast<unsigned>(m_tryContextStack.size()), + static_cast<unsigned>(m_labelScopes.size()), + static_cast<unsigned>(m_symbolTableStack.size()), + m_finallyDepth, + m_localScopeDepth + }; + scope.finallyContext = context; + m_scopeContextStack.append(scope); + m_finallyDepth++; +} + +void BytecodeGenerator::popFinallyContext() +{ + ASSERT(m_scopeContextStack.size()); + ASSERT(m_scopeContextStack.last().isFinallyBlock); + ASSERT(m_scopeContextStack.last().finallyContext.finallyBlock); + ASSERT(!m_scopeContextStack.last().finallyContext.iterator); + ASSERT(!m_scopeContextStack.last().finallyContext.enumerationNode); + ASSERT(m_finallyDepth > 0); + m_scopeContextStack.removeLast(); + m_finallyDepth--; +} + +void BytecodeGenerator::popIteratorCloseContext() +{ + ASSERT(m_scopeContextStack.size()); + ASSERT(m_scopeContextStack.last().isFinallyBlock); + ASSERT(!m_scopeContextStack.last().finallyContext.finallyBlock); + ASSERT(m_scopeContextStack.last().finallyContext.iterator); + ASSERT(m_scopeContextStack.last().finallyContext.enumerationNode); + ASSERT(m_finallyDepth > 0); + m_scopeContextStack.removeLast(); + m_finallyDepth--; +} + +LabelScopePtr BytecodeGenerator::breakTarget(const Identifier& name) +{ + // Reclaim free label scopes. + // + // The condition was previously coded as 'm_labelScopes.size() && !m_labelScopes.last().refCount()', + // however sometimes this appears to lead to GCC going a little haywire and entering the loop with + // size 0, leading to segfaulty badness. We are yet to identify a valid cause within our code to + // cause the GCC codegen to misbehave in this fashion, and as such the following refactoring of the + // loop condition is a workaround. + while (m_labelScopes.size()) { + if (m_labelScopes.last().refCount()) + break; + m_labelScopes.removeLast(); + } + + if (!m_labelScopes.size()) + return LabelScopePtr::null(); + + // We special-case the following, which is a syntax error in Firefox: + // label: + // break; + if (name.isEmpty()) { + for (int i = m_labelScopes.size() - 1; i >= 0; --i) { + LabelScope* scope = &m_labelScopes[i]; + if (scope->type() != LabelScope::NamedLabel) { + ASSERT(scope->breakTarget()); + return LabelScopePtr(m_labelScopes, i); + } + } + return LabelScopePtr::null(); + } + + for (int i = m_labelScopes.size() - 1; i >= 0; --i) { + LabelScope* scope = &m_labelScopes[i]; + if (scope->name() && *scope->name() == name) { + ASSERT(scope->breakTarget()); + return LabelScopePtr(m_labelScopes, i); + } + } + return LabelScopePtr::null(); +} + +LabelScopePtr BytecodeGenerator::continueTarget(const Identifier& name) +{ + // Reclaim free label scopes. + while (m_labelScopes.size() && !m_labelScopes.last().refCount()) + m_labelScopes.removeLast(); + + if (!m_labelScopes.size()) + return LabelScopePtr::null(); + + if (name.isEmpty()) { + for (int i = m_labelScopes.size() - 1; i >= 0; --i) { + LabelScope* scope = &m_labelScopes[i]; + if (scope->type() == LabelScope::Loop) { + ASSERT(scope->continueTarget()); + return LabelScopePtr(m_labelScopes, i); + } + } + return LabelScopePtr::null(); + } + + // Continue to the loop nested nearest to the label scope that matches + // 'name'. + LabelScopePtr result = LabelScopePtr::null(); + for (int i = m_labelScopes.size() - 1; i >= 0; --i) { + LabelScope* scope = &m_labelScopes[i]; + if (scope->type() == LabelScope::Loop) { + ASSERT(scope->continueTarget()); + result = LabelScopePtr(m_labelScopes, i); + } + if (scope->name() && *scope->name() == name) + return result; // may be null. + } + return LabelScopePtr::null(); +} + +void BytecodeGenerator::allocateAndEmitScope() +{ + m_scopeRegister = addVar(); + m_scopeRegister->ref(); + m_codeBlock->setScopeRegister(scopeRegister()->virtualRegister()); + emitGetScope(); + m_topMostScope = addVar(); + emitMove(m_topMostScope, scopeRegister()); +} + +void BytecodeGenerator::emitComplexPopScopes(RegisterID* scope, ControlFlowContext* topScope, ControlFlowContext* bottomScope) +{ + while (topScope > bottomScope) { + // First we count the number of dynamic scopes we need to remove to get + // to a finally block. + int nNormalScopes = 0; + while (topScope > bottomScope) { + if (topScope->isFinallyBlock) + break; + ++nNormalScopes; + --topScope; + } + + if (nNormalScopes) { + // We need to remove a number of dynamic scopes to get to the next + // finally block + RefPtr<RegisterID> parentScope = newTemporary(); + while (nNormalScopes--) { + parentScope = emitGetParentScope(parentScope.get(), scope); + emitMove(scope, parentScope.get()); + } + + // If topScope == bottomScope then there isn't a finally block left to emit. + if (topScope == bottomScope) + return; + } + + Vector<ControlFlowContext> savedScopeContextStack; + Vector<SwitchInfo> savedSwitchContextStack; + Vector<std::unique_ptr<ForInContext>> savedForInContextStack; + Vector<TryContext> poppedTryContexts; + Vector<SymbolTableStackEntry> savedSymbolTableStack; + LabelScopeStore savedLabelScopes; + while (topScope > bottomScope && topScope->isFinallyBlock) { + RefPtr<Label> beforeFinally = emitLabel(newLabel().get()); + + // Save the current state of the world while instating the state of the world + // for the finally block. + FinallyContext finallyContext = topScope->finallyContext; + bool flipScopes = finallyContext.scopeContextStackSize != m_scopeContextStack.size(); + bool flipSwitches = finallyContext.switchContextStackSize != m_switchContextStack.size(); + bool flipForIns = finallyContext.forInContextStackSize != m_forInContextStack.size(); + bool flipTries = finallyContext.tryContextStackSize != m_tryContextStack.size(); + bool flipLabelScopes = finallyContext.labelScopesSize != m_labelScopes.size(); + bool flipSymbolTableStack = finallyContext.symbolTableStackSize != m_symbolTableStack.size(); + int topScopeIndex = -1; + int bottomScopeIndex = -1; + if (flipScopes) { + topScopeIndex = topScope - m_scopeContextStack.begin(); + bottomScopeIndex = bottomScope - m_scopeContextStack.begin(); + savedScopeContextStack = m_scopeContextStack; + m_scopeContextStack.shrink(finallyContext.scopeContextStackSize); + } + if (flipSwitches) { + savedSwitchContextStack = m_switchContextStack; + m_switchContextStack.shrink(finallyContext.switchContextStackSize); + } + if (flipForIns) { + savedForInContextStack.swap(m_forInContextStack); + m_forInContextStack.shrink(finallyContext.forInContextStackSize); + } + if (flipTries) { + while (m_tryContextStack.size() != finallyContext.tryContextStackSize) { + ASSERT(m_tryContextStack.size() > finallyContext.tryContextStackSize); + TryContext context = m_tryContextStack.last(); + m_tryContextStack.removeLast(); + TryRange range; + range.start = context.start; + range.end = beforeFinally; + range.tryData = context.tryData; + m_tryRanges.append(range); + poppedTryContexts.append(context); + } + } + if (flipLabelScopes) { + savedLabelScopes = m_labelScopes; + while (m_labelScopes.size() > finallyContext.labelScopesSize) + m_labelScopes.removeLast(); + } + if (flipSymbolTableStack) { + savedSymbolTableStack = m_symbolTableStack; + m_symbolTableStack.shrink(finallyContext.symbolTableStackSize); + } + int savedFinallyDepth = m_finallyDepth; + m_finallyDepth = finallyContext.finallyDepth; + int savedDynamicScopeDepth = m_localScopeDepth; + m_localScopeDepth = finallyContext.dynamicScopeDepth; + + if (finallyContext.finallyBlock) { + // Emit the finally block. + emitNode(finallyContext.finallyBlock); + } else { + // Emit the IteratorClose block. + ASSERT(finallyContext.iterator); + emitIteratorClose(finallyContext.iterator, finallyContext.enumerationNode); + } + + RefPtr<Label> afterFinally = emitLabel(newLabel().get()); + + // Restore the state of the world. + if (flipScopes) { + m_scopeContextStack = savedScopeContextStack; + topScope = &m_scopeContextStack[topScopeIndex]; // assert it's within bounds + bottomScope = m_scopeContextStack.begin() + bottomScopeIndex; // don't assert, since it the index might be -1. + } + if (flipSwitches) + m_switchContextStack = savedSwitchContextStack; + if (flipForIns) + m_forInContextStack.swap(savedForInContextStack); + if (flipTries) { + ASSERT(m_tryContextStack.size() == finallyContext.tryContextStackSize); + for (unsigned i = poppedTryContexts.size(); i--;) { + TryContext context = poppedTryContexts[i]; + context.start = afterFinally; + m_tryContextStack.append(context); + } + poppedTryContexts.clear(); + } + if (flipLabelScopes) + m_labelScopes = savedLabelScopes; + if (flipSymbolTableStack) + m_symbolTableStack = savedSymbolTableStack; + m_finallyDepth = savedFinallyDepth; + m_localScopeDepth = savedDynamicScopeDepth; + + --topScope; + } + } +} + +void BytecodeGenerator::emitPopScopes(RegisterID* scope, int targetScopeDepth) +{ + ASSERT(labelScopeDepth() - targetScopeDepth >= 0); + + size_t scopeDelta = labelScopeDepth() - targetScopeDepth; + ASSERT(scopeDelta <= m_scopeContextStack.size()); + if (!scopeDelta) + return; + + if (!m_finallyDepth) { + RefPtr<RegisterID> parentScope = newTemporary(); + while (scopeDelta--) { + parentScope = emitGetParentScope(parentScope.get(), scope); + emitMove(scope, parentScope.get()); + } + return; + } + + emitComplexPopScopes(scope, &m_scopeContextStack.last(), &m_scopeContextStack.last() - scopeDelta); +} + +TryData* BytecodeGenerator::pushTry(Label* start) +{ + TryData tryData; + tryData.target = newLabel(); + tryData.handlerType = HandlerType::Illegal; + m_tryData.append(tryData); + TryData* result = &m_tryData.last(); + + TryContext tryContext; + tryContext.start = start; + tryContext.tryData = result; + + m_tryContextStack.append(tryContext); + + return result; +} + +void BytecodeGenerator::popTryAndEmitCatch(TryData* tryData, RegisterID* exceptionRegister, RegisterID* thrownValueRegister, Label* end, HandlerType handlerType) +{ + m_usesExceptions = true; + + ASSERT_UNUSED(tryData, m_tryContextStack.last().tryData == tryData); + + TryRange tryRange; + tryRange.start = m_tryContextStack.last().start; + tryRange.end = end; + tryRange.tryData = m_tryContextStack.last().tryData; + m_tryRanges.append(tryRange); + m_tryContextStack.removeLast(); + + emitLabel(tryRange.tryData->target.get()); + tryRange.tryData->handlerType = handlerType; + + emitOpcode(op_catch); + instructions().append(exceptionRegister->index()); + instructions().append(thrownValueRegister->index()); + + bool foundLocalScope = false; + for (unsigned i = m_symbolTableStack.size(); i--; ) { + // Note that if we don't find a local scope in the current function/program, + // we must grab the outer-most scope of this bytecode generation. + if (m_symbolTableStack[i].m_scope) { + foundLocalScope = true; + emitMove(scopeRegister(), m_symbolTableStack[i].m_scope); + break; + } + } + if (!foundLocalScope) + emitMove(scopeRegister(), m_topMostScope); +} + +int BytecodeGenerator::localScopeDepth() const +{ + return m_localScopeDepth; +} + +int BytecodeGenerator::labelScopeDepth() const +{ + return localScopeDepth() + m_finallyDepth; +} + +void BytecodeGenerator::emitThrowReferenceError(const String& message) +{ + emitOpcode(op_throw_static_error); + instructions().append(addConstantValue(addStringConstant(Identifier::fromString(m_vm, message)))->index()); + instructions().append(true); +} + +void BytecodeGenerator::emitThrowTypeError(const String& message) +{ + emitOpcode(op_throw_static_error); + instructions().append(addConstantValue(addStringConstant(Identifier::fromString(m_vm, message)))->index()); + instructions().append(false); +} + +void BytecodeGenerator::emitPushFunctionNameScope(const Identifier& property, RegisterID* callee) +{ + // There is some nuance here: + // If we're in strict mode code, the function name scope variable acts exactly like a "const" variable. + // If we're not in strict mode code, we want to allow bogus assignments to the name scoped variable. + // This means any assignment to the variable won't throw, but it won't actually assign a new value to it. + // To accomplish this, we don't report that this scope is a lexical scope. This will prevent + // any throws when trying to assign to the variable (while still ensuring it keeps its original + // value). There is some ugliness and exploitation of a leaky abstraction here, but it's better than + // having a completely new op code and a class to handle name scopes which are so close in functionality + // to lexical environments. + VariableEnvironment nameScopeEnvironment; + auto addResult = nameScopeEnvironment.add(property); + addResult.iterator->value.setIsCaptured(); + addResult.iterator->value.setIsConst(); // The function name scope name acts like a const variable. + unsigned numVars = m_codeBlock->m_numVars; + pushLexicalScopeInternal(nameScopeEnvironment, true, nullptr, TDZRequirement::NotUnderTDZ, ScopeType::FunctionNameScope, ScopeRegisterType::Var); + ASSERT_UNUSED(numVars, m_codeBlock->m_numVars == static_cast<int>(numVars + 1)); // Should have only created one new "var" for the function name scope. + bool shouldTreatAsLexicalVariable = isStrictMode(); + Variable functionVar = variableForLocalEntry(property, m_symbolTableStack.last().m_symbolTable->get(property.impl()), m_symbolTableStack.last().m_symbolTableConstantIndex, shouldTreatAsLexicalVariable); + emitPutToScope(m_symbolTableStack.last().m_scope, functionVar, callee, ThrowIfNotFound); +} + +void BytecodeGenerator::pushScopedControlFlowContext() +{ + ControlFlowContext context; + context.isFinallyBlock = false; + m_scopeContextStack.append(context); + m_localScopeDepth++; +} + +void BytecodeGenerator::popScopedControlFlowContext() +{ + ASSERT(m_scopeContextStack.size()); + ASSERT(!m_scopeContextStack.last().isFinallyBlock); + m_scopeContextStack.removeLast(); + m_localScopeDepth--; +} + +void BytecodeGenerator::emitPushCatchScope(const Identifier& property, RegisterID* exceptionValue, VariableEnvironment& environment) +{ + RELEASE_ASSERT(environment.contains(property.impl())); + pushLexicalScopeInternal(environment, true, nullptr, TDZRequirement::NotUnderTDZ, ScopeType::CatchScope, ScopeRegisterType::Block); + Variable exceptionVar = variable(property); + RELEASE_ASSERT(exceptionVar.isResolved()); + RefPtr<RegisterID> scope = emitResolveScope(nullptr, exceptionVar); + emitPutToScope(scope.get(), exceptionVar, exceptionValue, ThrowIfNotFound); +} + +void BytecodeGenerator::emitPopCatchScope(VariableEnvironment& environment) +{ + popLexicalScopeInternal(environment, TDZRequirement::NotUnderTDZ); +} + +void BytecodeGenerator::beginSwitch(RegisterID* scrutineeRegister, SwitchInfo::SwitchType type) +{ + SwitchInfo info = { static_cast<uint32_t>(instructions().size()), type }; + switch (type) { + case SwitchInfo::SwitchImmediate: + emitOpcode(op_switch_imm); + break; + case SwitchInfo::SwitchCharacter: + emitOpcode(op_switch_char); + break; + case SwitchInfo::SwitchString: + emitOpcode(op_switch_string); + break; + default: + RELEASE_ASSERT_NOT_REACHED(); + } + + instructions().append(0); // place holder for table index + instructions().append(0); // place holder for default target + instructions().append(scrutineeRegister->index()); + m_switchContextStack.append(info); +} + +static int32_t keyForImmediateSwitch(ExpressionNode* node, int32_t min, int32_t max) +{ + UNUSED_PARAM(max); + ASSERT(node->isNumber()); + double value = static_cast<NumberNode*>(node)->value(); + int32_t key = static_cast<int32_t>(value); + ASSERT(key == value); + ASSERT(key >= min); + ASSERT(key <= max); + return key - min; +} + +static int32_t keyForCharacterSwitch(ExpressionNode* node, int32_t min, int32_t max) +{ + UNUSED_PARAM(max); + ASSERT(node->isString()); + StringImpl* clause = static_cast<StringNode*>(node)->value().impl(); + ASSERT(clause->length() == 1); + + int32_t key = (*clause)[0]; + ASSERT(key >= min); + ASSERT(key <= max); + return key - min; +} + +static void prepareJumpTableForSwitch( + UnlinkedSimpleJumpTable& jumpTable, int32_t switchAddress, uint32_t clauseCount, + RefPtr<Label>* labels, ExpressionNode** nodes, int32_t min, int32_t max, + int32_t (*keyGetter)(ExpressionNode*, int32_t min, int32_t max)) +{ + jumpTable.min = min; + jumpTable.branchOffsets.resize(max - min + 1); + jumpTable.branchOffsets.fill(0); + for (uint32_t i = 0; i < clauseCount; ++i) { + // We're emitting this after the clause labels should have been fixed, so + // the labels should not be "forward" references + ASSERT(!labels[i]->isForward()); + jumpTable.add(keyGetter(nodes[i], min, max), labels[i]->bind(switchAddress, switchAddress + 3)); + } +} + +static void prepareJumpTableForStringSwitch(UnlinkedStringJumpTable& jumpTable, int32_t switchAddress, uint32_t clauseCount, RefPtr<Label>* labels, ExpressionNode** nodes) +{ + for (uint32_t i = 0; i < clauseCount; ++i) { + // We're emitting this after the clause labels should have been fixed, so + // the labels should not be "forward" references + ASSERT(!labels[i]->isForward()); + + ASSERT(nodes[i]->isString()); + StringImpl* clause = static_cast<StringNode*>(nodes[i])->value().impl(); + jumpTable.offsetTable.add(clause, labels[i]->bind(switchAddress, switchAddress + 3)); + } +} + +void BytecodeGenerator::endSwitch(uint32_t clauseCount, RefPtr<Label>* labels, ExpressionNode** nodes, Label* defaultLabel, int32_t min, int32_t max) +{ + SwitchInfo switchInfo = m_switchContextStack.last(); + m_switchContextStack.removeLast(); + + switch (switchInfo.switchType) { + case SwitchInfo::SwitchImmediate: + case SwitchInfo::SwitchCharacter: { + instructions()[switchInfo.bytecodeOffset + 1] = m_codeBlock->numberOfSwitchJumpTables(); + instructions()[switchInfo.bytecodeOffset + 2] = defaultLabel->bind(switchInfo.bytecodeOffset, switchInfo.bytecodeOffset + 3); + + UnlinkedSimpleJumpTable& jumpTable = m_codeBlock->addSwitchJumpTable(); + prepareJumpTableForSwitch( + jumpTable, switchInfo.bytecodeOffset, clauseCount, labels, nodes, min, max, + switchInfo.switchType == SwitchInfo::SwitchImmediate + ? keyForImmediateSwitch + : keyForCharacterSwitch); + break; + } + + case SwitchInfo::SwitchString: { + instructions()[switchInfo.bytecodeOffset + 1] = m_codeBlock->numberOfStringSwitchJumpTables(); + instructions()[switchInfo.bytecodeOffset + 2] = defaultLabel->bind(switchInfo.bytecodeOffset, switchInfo.bytecodeOffset + 3); + + UnlinkedStringJumpTable& jumpTable = m_codeBlock->addStringSwitchJumpTable(); + prepareJumpTableForStringSwitch(jumpTable, switchInfo.bytecodeOffset, clauseCount, labels, nodes); + break; + } + + default: + RELEASE_ASSERT_NOT_REACHED(); + break; + } +} + +RegisterID* BytecodeGenerator::emitThrowExpressionTooDeepException() +{ + // It would be nice to do an even better job of identifying exactly where the expression is. + // And we could make the caller pass the node pointer in, if there was some way of getting + // that from an arbitrary node. However, calling emitExpressionInfo without any useful data + // is still good enough to get us an accurate line number. + m_expressionTooDeep = true; + return newTemporary(); +} + +bool BytecodeGenerator::isArgumentNumber(const Identifier& ident, int argumentNumber) +{ + RegisterID* registerID = variable(ident).local(); + if (!registerID) + return false; + return registerID->index() == CallFrame::argumentOffset(argumentNumber); +} + +bool BytecodeGenerator::emitReadOnlyExceptionIfNeeded(const Variable& variable) +{ + if (isStrictMode() || variable.isConst()) { + emitOpcode(op_throw_static_error); + instructions().append(addConstantValue(addStringConstant(Identifier::fromString(m_vm, StrictModeReadonlyPropertyWriteError)))->index()); + instructions().append(false); + return true; + } + return false; +} + +void BytecodeGenerator::emitEnumeration(ThrowableExpressionData* node, ExpressionNode* subjectNode, const std::function<void(BytecodeGenerator&, RegisterID*)>& callBack, VariableEnvironmentNode* forLoopNode, RegisterID* forLoopSymbolTable) +{ + RefPtr<RegisterID> subject = newTemporary(); + emitNode(subject.get(), subjectNode); + RefPtr<RegisterID> iterator = emitGetById(newTemporary(), subject.get(), propertyNames().iteratorSymbol); + { + CallArguments args(*this, nullptr); + emitMove(args.thisRegister(), subject.get()); + emitCall(iterator.get(), iterator.get(), NoExpectedFunction, args, node->divot(), node->divotStart(), node->divotEnd()); + } + + RefPtr<Label> loopDone = newLabel(); + // RefPtr<Register> iterator's lifetime must be longer than IteratorCloseContext. + pushIteratorCloseContext(iterator.get(), node); + { + LabelScopePtr scope = newLabelScope(LabelScope::Loop); + RefPtr<RegisterID> value = newTemporary(); + emitLoad(value.get(), jsUndefined()); + + emitJump(scope->continueTarget()); + + RefPtr<Label> loopStart = newLabel(); + emitLabel(loopStart.get()); + emitLoopHint(); + + RefPtr<Label> tryStartLabel = newLabel(); + emitLabel(tryStartLabel.get()); + TryData* tryData = pushTry(tryStartLabel.get()); + callBack(*this, value.get()); + emitJump(scope->continueTarget()); + + // IteratorClose sequence for throw-ed control flow. + { + RefPtr<Label> catchHere = emitLabel(newLabel().get()); + RefPtr<RegisterID> exceptionRegister = newTemporary(); + RefPtr<RegisterID> thrownValueRegister = newTemporary(); + popTryAndEmitCatch(tryData, exceptionRegister.get(), + thrownValueRegister.get(), catchHere.get(), HandlerType::SynthesizedFinally); + + RefPtr<Label> catchDone = newLabel(); + + RefPtr<RegisterID> returnMethod = emitGetById(newTemporary(), iterator.get(), propertyNames().returnKeyword); + emitJumpIfTrue(emitIsUndefined(newTemporary(), returnMethod.get()), catchDone.get()); + + RefPtr<Label> returnCallTryStart = newLabel(); + emitLabel(returnCallTryStart.get()); + TryData* returnCallTryData = pushTry(returnCallTryStart.get()); + + CallArguments returnArguments(*this, nullptr); + emitMove(returnArguments.thisRegister(), iterator.get()); + emitCall(value.get(), returnMethod.get(), NoExpectedFunction, returnArguments, node->divot(), node->divotStart(), node->divotEnd()); + + emitLabel(catchDone.get()); + emitThrow(exceptionRegister.get()); + + // Absorb exception. + popTryAndEmitCatch(returnCallTryData, newTemporary(), + newTemporary(), catchDone.get(), HandlerType::SynthesizedFinally); + emitThrow(exceptionRegister.get()); + } + + emitLabel(scope->continueTarget()); + if (forLoopNode) + prepareLexicalScopeForNextForLoopIteration(forLoopNode, forLoopSymbolTable); + + { + emitIteratorNext(value.get(), iterator.get(), node); + emitJumpIfTrue(emitGetById(newTemporary(), value.get(), propertyNames().done), loopDone.get()); + emitGetById(value.get(), value.get(), propertyNames().value); + emitJump(loopStart.get()); + } + + emitLabel(scope->breakTarget()); + } + + // IteratorClose sequence for break-ed control flow. + popIteratorCloseContext(); + emitIteratorClose(iterator.get(), node); + emitLabel(loopDone.get()); +} + +#if ENABLE(ES6_TEMPLATE_LITERAL_SYNTAX) +RegisterID* BytecodeGenerator::emitGetTemplateObject(RegisterID* dst, TaggedTemplateNode* taggedTemplate) +{ + TemplateRegistryKey::StringVector rawStrings; + TemplateRegistryKey::StringVector cookedStrings; + + TemplateStringListNode* templateString = taggedTemplate->templateLiteral()->templateStrings(); + for (; templateString; templateString = templateString->next()) { + rawStrings.append(templateString->value()->raw().impl()); + cookedStrings.append(templateString->value()->cooked().impl()); + } + + RefPtr<RegisterID> getTemplateObject = nullptr; + Variable var = variable(propertyNames().getTemplateObjectPrivateName); + if (RegisterID* local = var.local()) + getTemplateObject = emitMove(newTemporary(), local); + else { + getTemplateObject = newTemporary(); + RefPtr<RegisterID> scope = newTemporary(); + moveToDestinationIfNeeded(scope.get(), emitResolveScope(scope.get(), var)); + emitGetFromScope(getTemplateObject.get(), scope.get(), var, ThrowIfNotFound); + } + + CallArguments arguments(*this, nullptr); + emitLoad(arguments.thisRegister(), JSValue(addTemplateRegistryKeyConstant(TemplateRegistryKey(rawStrings, cookedStrings)))); + return emitCall(dst, getTemplateObject.get(), NoExpectedFunction, arguments, taggedTemplate->divot(), taggedTemplate->divotStart(), taggedTemplate->divotEnd()); +} +#endif + +RegisterID* BytecodeGenerator::emitGetEnumerableLength(RegisterID* dst, RegisterID* base) +{ + emitOpcode(op_get_enumerable_length); + instructions().append(dst->index()); + instructions().append(base->index()); + return dst; +} + +RegisterID* BytecodeGenerator::emitHasGenericProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName) +{ + emitOpcode(op_has_generic_property); + instructions().append(dst->index()); + instructions().append(base->index()); + instructions().append(propertyName->index()); + return dst; +} + +RegisterID* BytecodeGenerator::emitHasIndexedProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName) +{ + UnlinkedArrayProfile arrayProfile = newArrayProfile(); + emitOpcode(op_has_indexed_property); + instructions().append(dst->index()); + instructions().append(base->index()); + instructions().append(propertyName->index()); + instructions().append(arrayProfile); + return dst; +} + +RegisterID* BytecodeGenerator::emitHasStructureProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName, RegisterID* enumerator) +{ + emitOpcode(op_has_structure_property); + instructions().append(dst->index()); + instructions().append(base->index()); + instructions().append(propertyName->index()); + instructions().append(enumerator->index()); + return dst; +} + +RegisterID* BytecodeGenerator::emitGetPropertyEnumerator(RegisterID* dst, RegisterID* base) +{ + emitOpcode(op_get_property_enumerator); + instructions().append(dst->index()); + instructions().append(base->index()); + return dst; +} + +RegisterID* BytecodeGenerator::emitEnumeratorStructurePropertyName(RegisterID* dst, RegisterID* enumerator, RegisterID* index) +{ + emitOpcode(op_enumerator_structure_pname); + instructions().append(dst->index()); + instructions().append(enumerator->index()); + instructions().append(index->index()); + return dst; +} + +RegisterID* BytecodeGenerator::emitEnumeratorGenericPropertyName(RegisterID* dst, RegisterID* enumerator, RegisterID* index) +{ + emitOpcode(op_enumerator_generic_pname); + instructions().append(dst->index()); + instructions().append(enumerator->index()); + instructions().append(index->index()); + return dst; +} + +RegisterID* BytecodeGenerator::emitToIndexString(RegisterID* dst, RegisterID* index) +{ + emitOpcode(op_to_index_string); + instructions().append(dst->index()); + instructions().append(index->index()); + return dst; +} + + +RegisterID* BytecodeGenerator::emitIsObject(RegisterID* dst, RegisterID* src) +{ + emitOpcode(op_is_object); + instructions().append(dst->index()); + instructions().append(src->index()); + return dst; +} + +RegisterID* BytecodeGenerator::emitIsUndefined(RegisterID* dst, RegisterID* src) +{ + emitOpcode(op_is_undefined); + instructions().append(dst->index()); + instructions().append(src->index()); + return dst; +} + +RegisterID* BytecodeGenerator::emitIteratorNext(RegisterID* dst, RegisterID* iterator, const ThrowableExpressionData* node) +{ + { + RefPtr<RegisterID> next = emitGetById(newTemporary(), iterator, propertyNames().next); + CallArguments nextArguments(*this, nullptr); + emitMove(nextArguments.thisRegister(), iterator); + emitCall(dst, next.get(), NoExpectedFunction, nextArguments, node->divot(), node->divotStart(), node->divotEnd()); + } + { + RefPtr<Label> typeIsObject = newLabel(); + emitJumpIfTrue(emitIsObject(newTemporary(), dst), typeIsObject.get()); + emitThrowTypeError(ASCIILiteral("Iterator result interface is not an object.")); + emitLabel(typeIsObject.get()); + } + return dst; +} + +void BytecodeGenerator::emitIteratorClose(RegisterID* iterator, const ThrowableExpressionData* node) +{ + RefPtr<Label> done = newLabel(); + RefPtr<RegisterID> returnMethod = emitGetById(newTemporary(), iterator, propertyNames().returnKeyword); + emitJumpIfTrue(emitIsUndefined(newTemporary(), returnMethod.get()), done.get()); + + RefPtr<RegisterID> value = newTemporary(); + CallArguments returnArguments(*this, nullptr); + emitMove(returnArguments.thisRegister(), iterator); + emitCall(value.get(), returnMethod.get(), NoExpectedFunction, returnArguments, node->divot(), node->divotStart(), node->divotEnd()); + emitJumpIfTrue(emitIsObject(newTemporary(), value.get()), done.get()); + emitThrowTypeError(ASCIILiteral("Iterator result interface is not an object.")); + emitLabel(done.get()); +} + +void BytecodeGenerator::pushIndexedForInScope(RegisterID* localRegister, RegisterID* indexRegister) +{ + if (!localRegister) + return; + m_forInContextStack.append(std::make_unique<IndexedForInContext>(localRegister, indexRegister)); +} + +void BytecodeGenerator::popIndexedForInScope(RegisterID* localRegister) +{ + if (!localRegister) + return; + m_forInContextStack.removeLast(); +} + +void BytecodeGenerator::pushStructureForInScope(RegisterID* localRegister, RegisterID* indexRegister, RegisterID* propertyRegister, RegisterID* enumeratorRegister) +{ + if (!localRegister) + return; + m_forInContextStack.append(std::make_unique<StructureForInContext>(localRegister, indexRegister, propertyRegister, enumeratorRegister)); +} + +void BytecodeGenerator::popStructureForInScope(RegisterID* localRegister) +{ + if (!localRegister) + return; + m_forInContextStack.removeLast(); +} + +void BytecodeGenerator::invalidateForInContextForLocal(RegisterID* localRegister) +{ + // Lexically invalidating ForInContexts is kind of weak sauce, but it only occurs if + // either of the following conditions is true: + // + // (1) The loop iteration variable is re-assigned within the body of the loop. + // (2) The loop iteration variable is captured in the lexical scope of the function. + // + // These two situations occur sufficiently rarely that it's okay to use this style of + // "analysis" to make iteration faster. If we didn't want to do this, we would either have + // to perform some flow-sensitive analysis to see if/when the loop iteration variable was + // reassigned, or we'd have to resort to runtime checks to see if the variable had been + // reassigned from its original value. + for (size_t i = m_forInContextStack.size(); i > 0; i--) { + ForInContext* context = m_forInContextStack[i - 1].get(); + if (context->local() != localRegister) + continue; + context->invalidate(); + break; + } +} + +} // namespace JSC diff --git a/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.h b/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.h new file mode 100644 index 000000000..33a15c1ff --- /dev/null +++ b/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.h @@ -0,0 +1,831 @@ +/* + * Copyright (C) 2008, 2009, 2012-2015 Apple Inc. All rights reserved. + * Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca> + * Copyright (C) 2012 Igalia, S.L. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef BytecodeGenerator_h +#define BytecodeGenerator_h + +#include "CodeBlock.h" +#include <wtf/HashTraits.h> +#include "Instruction.h" +#include "Label.h" +#include "LabelScope.h" +#include "Interpreter.h" +#include "ParserError.h" +#include "RegisterID.h" +#include "SymbolTable.h" +#include "Debugger.h" +#include "Nodes.h" +#include "StaticPropertyAnalyzer.h" +#include "TemplateRegistryKey.h" +#include "UnlinkedCodeBlock.h" + +#include <functional> + +#include <wtf/PassRefPtr.h> +#include <wtf/SegmentedVector.h> +#include <wtf/Vector.h> + + +namespace JSC { + + class Identifier; + class JSTemplateRegistryKey; + + enum ExpectedFunction { + NoExpectedFunction, + ExpectObjectConstructor, + ExpectArrayConstructor + }; + + class CallArguments { + public: + CallArguments(BytecodeGenerator&, ArgumentsNode*, unsigned additionalArguments = 0); + + RegisterID* thisRegister() { return m_argv[0].get(); } + RegisterID* argumentRegister(unsigned i) { return m_argv[i + 1].get(); } + unsigned stackOffset() { return -m_argv[0]->index() + JSStack::CallFrameHeaderSize; } + unsigned argumentCountIncludingThis() { return m_argv.size() - m_padding; } + RegisterID* profileHookRegister() { return m_profileHookRegister.get(); } + ArgumentsNode* argumentsNode() { return m_argumentsNode; } + + private: + RefPtr<RegisterID> m_profileHookRegister; + ArgumentsNode* m_argumentsNode; + Vector<RefPtr<RegisterID>, 8, UnsafeVectorOverflow> m_argv; + unsigned m_padding; + }; + + struct FinallyContext { + StatementNode* finallyBlock; + RegisterID* iterator; + ThrowableExpressionData* enumerationNode; + unsigned scopeContextStackSize; + unsigned switchContextStackSize; + unsigned forInContextStackSize; + unsigned tryContextStackSize; + unsigned labelScopesSize; + unsigned symbolTableStackSize; + int finallyDepth; + int dynamicScopeDepth; + }; + + struct ControlFlowContext { + bool isFinallyBlock; + FinallyContext finallyContext; + }; + + class ForInContext { + WTF_MAKE_FAST_ALLOCATED; + public: + ForInContext(RegisterID* localRegister) + : m_localRegister(localRegister) + , m_isValid(true) + { + } + + virtual ~ForInContext() + { + } + + bool isValid() const { return m_isValid; } + void invalidate() { m_isValid = false; } + + enum ForInContextType { + StructureForInContextType, + IndexedForInContextType + }; + virtual ForInContextType type() const = 0; + + RegisterID* local() const { return m_localRegister.get(); } + + private: + RefPtr<RegisterID> m_localRegister; + bool m_isValid; + }; + + class StructureForInContext : public ForInContext { + public: + StructureForInContext(RegisterID* localRegister, RegisterID* indexRegister, RegisterID* propertyRegister, RegisterID* enumeratorRegister) + : ForInContext(localRegister) + , m_indexRegister(indexRegister) + , m_propertyRegister(propertyRegister) + , m_enumeratorRegister(enumeratorRegister) + { + } + + virtual ForInContextType type() const + { + return StructureForInContextType; + } + + RegisterID* index() const { return m_indexRegister.get(); } + RegisterID* property() const { return m_propertyRegister.get(); } + RegisterID* enumerator() const { return m_enumeratorRegister.get(); } + + private: + RefPtr<RegisterID> m_indexRegister; + RefPtr<RegisterID> m_propertyRegister; + RefPtr<RegisterID> m_enumeratorRegister; + }; + + class IndexedForInContext : public ForInContext { + public: + IndexedForInContext(RegisterID* localRegister, RegisterID* indexRegister) + : ForInContext(localRegister) + , m_indexRegister(indexRegister) + { + } + + virtual ForInContextType type() const + { + return IndexedForInContextType; + } + + RegisterID* index() const { return m_indexRegister.get(); } + + private: + RefPtr<RegisterID> m_indexRegister; + }; + + struct TryData { + RefPtr<Label> target; + HandlerType handlerType; + }; + + struct TryContext { + RefPtr<Label> start; + TryData* tryData; + }; + + class Variable { + public: + enum VariableKind { NormalVariable, SpecialVariable }; + + Variable() + : m_offset() + , m_local(nullptr) + , m_attributes(0) + , m_kind(NormalVariable) + , m_symbolTableConstantIndex(0) // This is meaningless here for this kind of Variable. + , m_isLexicallyScoped(false) + { + } + + Variable(const Identifier& ident) + : m_ident(ident) + , m_local(nullptr) + , m_attributes(0) + , m_kind(NormalVariable) // This is somewhat meaningless here for this kind of Variable. + , m_symbolTableConstantIndex(0) // This is meaningless here for this kind of Variable. + , m_isLexicallyScoped(false) + { + } + + Variable(const Identifier& ident, VarOffset offset, RegisterID* local, unsigned attributes, VariableKind kind, int symbolTableConstantIndex, bool isLexicallyScoped) + : m_ident(ident) + , m_offset(offset) + , m_local(local) + , m_attributes(attributes) + , m_kind(kind) + , m_symbolTableConstantIndex(symbolTableConstantIndex) + , m_isLexicallyScoped(isLexicallyScoped) + { + } + + // If it's unset, then it is a non-locally-scoped variable. If it is set, then it could be + // a stack variable, a scoped variable in a local scope, or a variable captured in the + // direct arguments object. + bool isResolved() const { return !!m_offset; } + int symbolTableConstantIndex() const { ASSERT(isResolved() && !isSpecial()); return m_symbolTableConstantIndex; } + + const Identifier& ident() const { return m_ident; } + + VarOffset offset() const { return m_offset; } + bool isLocal() const { return m_offset.isStack(); } + RegisterID* local() const { return m_local; } + + bool isReadOnly() const { return m_attributes & ReadOnly; } + bool isSpecial() const { return m_kind != NormalVariable; } + bool isConst() const { return isReadOnly() && m_isLexicallyScoped; } + + private: + Identifier m_ident; + VarOffset m_offset; + RegisterID* m_local; + unsigned m_attributes; + VariableKind m_kind; + int m_symbolTableConstantIndex; + bool m_isLexicallyScoped; + }; + + struct TryRange { + RefPtr<Label> start; + RefPtr<Label> end; + TryData* tryData; + }; + + enum ProfileTypeBytecodeFlag { + ProfileTypeBytecodeClosureVar, + ProfileTypeBytecodeLocallyResolved, + ProfileTypeBytecodeDoesNotHaveGlobalID, + ProfileTypeBytecodeFunctionArgument, + ProfileTypeBytecodeFunctionReturnStatement + }; + + class BytecodeGenerator { + WTF_MAKE_FAST_ALLOCATED; + WTF_MAKE_NONCOPYABLE(BytecodeGenerator); + public: + typedef DeclarationStacks::FunctionStack FunctionStack; + + BytecodeGenerator(VM&, ProgramNode*, UnlinkedProgramCodeBlock*, DebuggerMode, ProfilerMode, const VariableEnvironment*); + BytecodeGenerator(VM&, FunctionNode*, UnlinkedFunctionCodeBlock*, DebuggerMode, ProfilerMode, const VariableEnvironment*); + BytecodeGenerator(VM&, EvalNode*, UnlinkedEvalCodeBlock*, DebuggerMode, ProfilerMode, const VariableEnvironment*); + + ~BytecodeGenerator(); + + VM* vm() const { return m_vm; } + ParserArena& parserArena() const { return m_scopeNode->parserArena(); } + const CommonIdentifiers& propertyNames() const { return *m_vm->propertyNames; } + + bool isConstructor() const { return m_codeBlock->isConstructor(); } +#if ENABLE(ES6_CLASS_SYNTAX) + ConstructorKind constructorKind() const { return m_codeBlock->constructorKind(); } +#else + ConstructorKind constructorKind() const { return ConstructorKind::None; } +#endif + + ParserError generate(); + + bool isArgumentNumber(const Identifier&, int); + + Variable variable(const Identifier&); + + enum ExistingVariableMode { VerifyExisting, IgnoreExisting }; + void createVariable(const Identifier&, VarKind, SymbolTable*, ExistingVariableMode = VerifyExisting); // Creates the variable, or asserts that the already-created variable is sufficiently compatible. + + // Returns the register storing "this" + RegisterID* thisRegister() { return &m_thisRegister; } + RegisterID* argumentsRegister() { return m_argumentsRegister; } + RegisterID* newTarget() { return m_newTargetRegister; } + + RegisterID* scopeRegister() { return m_scopeRegister; } + + // Returns the next available temporary register. Registers returned by + // newTemporary require a modified form of reference counting: any + // register with a refcount of 0 is considered "available", meaning that + // the next instruction may overwrite it. + RegisterID* newTemporary(); + + // The same as newTemporary(), but this function returns "suggestion" if + // "suggestion" is a temporary. This function is helpful in situations + // where you've put "suggestion" in a RefPtr, but you'd like to allow + // the next instruction to overwrite it anyway. + RegisterID* newTemporaryOr(RegisterID* suggestion) { return suggestion->isTemporary() ? suggestion : newTemporary(); } + + // Functions for handling of dst register + + RegisterID* ignoredResult() { return &m_ignoredResultRegister; } + + // This will be allocated in the temporary region of registers, but it will + // not be marked as a temporary. This will ensure that finalDestination() does + // not overwrite a block scope variable that it mistakes as a temporary. These + // registers can be (and are) reclaimed when the lexical scope they belong to + // is no longer on the symbol table stack. + RegisterID* newBlockScopeVariable(); + + // Returns a place to write intermediate values of an operation + // which reuses dst if it is safe to do so. + RegisterID* tempDestination(RegisterID* dst) + { + return (dst && dst != ignoredResult() && dst->isTemporary()) ? dst : newTemporary(); + } + + // Returns the place to write the final output of an operation. + RegisterID* finalDestination(RegisterID* originalDst, RegisterID* tempDst = 0) + { + if (originalDst && originalDst != ignoredResult()) + return originalDst; + ASSERT(tempDst != ignoredResult()); + if (tempDst && tempDst->isTemporary()) + return tempDst; + return newTemporary(); + } + + RegisterID* destinationForAssignResult(RegisterID* dst) + { + if (dst && dst != ignoredResult() && m_codeBlock->needsFullScopeChain()) + return dst->isTemporary() ? dst : newTemporary(); + return 0; + } + + // Moves src to dst if dst is not null and is different from src, otherwise just returns src. + RegisterID* moveToDestinationIfNeeded(RegisterID* dst, RegisterID* src) + { + return dst == ignoredResult() ? 0 : (dst && dst != src) ? emitMove(dst, src) : src; + } + + LabelScopePtr newLabelScope(LabelScope::Type, const Identifier* = 0); + PassRefPtr<Label> newLabel(); + + void emitNode(RegisterID* dst, StatementNode* n) + { + // Node::emitCode assumes that dst, if provided, is either a local or a referenced temporary. + ASSERT(!dst || dst == ignoredResult() || !dst->isTemporary() || dst->refCount()); + if (!m_vm->isSafeToRecurse()) { + emitThrowExpressionTooDeepException(); + return; + } + n->emitBytecode(*this, dst); + } + + void emitNode(StatementNode* n) + { + emitNode(0, n); + } + + RegisterID* emitNode(RegisterID* dst, ExpressionNode* n) + { + // Node::emitCode assumes that dst, if provided, is either a local or a referenced temporary. + ASSERT(!dst || dst == ignoredResult() || !dst->isTemporary() || dst->refCount()); + if (!m_vm->isSafeToRecurse()) + return emitThrowExpressionTooDeepException(); + return n->emitBytecode(*this, dst); + } + + RegisterID* emitNode(ExpressionNode* n) + { + return emitNode(0, n); + } + + void emitNodeInConditionContext(ExpressionNode* n, Label* trueTarget, Label* falseTarget, FallThroughMode fallThroughMode) + { + if (!m_vm->isSafeToRecurse()) { + emitThrowExpressionTooDeepException(); + return; + } + + n->emitBytecodeInConditionContext(*this, trueTarget, falseTarget, fallThroughMode); + } + + void emitExpressionInfo(const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd) + { + ASSERT(divot.offset >= divotStart.offset); + ASSERT(divotEnd.offset >= divot.offset); + + int sourceOffset = m_scopeNode->source().startOffset(); + unsigned firstLine = m_scopeNode->source().firstLine(); + + int divotOffset = divot.offset - sourceOffset; + int startOffset = divot.offset - divotStart.offset; + int endOffset = divotEnd.offset - divot.offset; + + unsigned line = divot.line; + ASSERT(line >= firstLine); + line -= firstLine; + + int lineStart = divot.lineStartOffset; + if (lineStart > sourceOffset) + lineStart -= sourceOffset; + else + lineStart = 0; + + if (divotOffset < lineStart) + return; + + unsigned column = divotOffset - lineStart; + + unsigned instructionOffset = instructions().size(); + if (!m_isBuiltinFunction) + m_codeBlock->addExpressionInfo(instructionOffset, divotOffset, startOffset, endOffset, line, column); + } + + + ALWAYS_INLINE bool leftHandSideNeedsCopy(bool rightHasAssignments, bool rightIsPure) + { + return (m_codeType != FunctionCode || m_codeBlock->needsFullScopeChain() || rightHasAssignments) && !rightIsPure; + } + + ALWAYS_INLINE PassRefPtr<RegisterID> emitNodeForLeftHandSide(ExpressionNode* n, bool rightHasAssignments, bool rightIsPure) + { + if (leftHandSideNeedsCopy(rightHasAssignments, rightIsPure)) { + PassRefPtr<RegisterID> dst = newTemporary(); + emitNode(dst.get(), n); + return dst; + } + + return emitNode(n); + } + + private: + void emitTypeProfilerExpressionInfo(const JSTextPosition& startDivot, const JSTextPosition& endDivot); + public: + + // This doesn't emit expression info. If using this, make sure you shouldn't be emitting text offset. + void emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag); + // These variables are associated with variables in a program. They could be Locals, LocalClosureVar, or ClosureVar. + void emitProfileType(RegisterID* registerToProfile, const Variable&, const JSTextPosition& startDivot, const JSTextPosition& endDivot); + + void emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag, const JSTextPosition& startDivot, const JSTextPosition& endDivot); + // These are not associated with variables and don't have a global id. + void emitProfileType(RegisterID* registerToProfile, const JSTextPosition& startDivot, const JSTextPosition& endDivot); + + void emitProfileControlFlow(int); + + RegisterID* emitLoad(RegisterID* dst, bool); + RegisterID* emitLoad(RegisterID* dst, const Identifier&); + RegisterID* emitLoad(RegisterID* dst, JSValue, SourceCodeRepresentation = SourceCodeRepresentation::Other); + RegisterID* emitLoadGlobalObject(RegisterID* dst); + + RegisterID* emitUnaryOp(OpcodeID, RegisterID* dst, RegisterID* src); + RegisterID* emitBinaryOp(OpcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2, OperandTypes); + RegisterID* emitEqualityOp(OpcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2); + RegisterID* emitUnaryNoDstOp(OpcodeID, RegisterID* src); + + RegisterID* emitCreateThis(RegisterID* dst); + void emitTDZCheck(RegisterID* target); + bool needsTDZCheck(const Variable&); + void emitTDZCheckIfNecessary(const Variable&, RegisterID* target, RegisterID* scope); + void liftTDZCheckIfPossible(const Variable&); + RegisterID* emitNewObject(RegisterID* dst); + RegisterID* emitNewArray(RegisterID* dst, ElementNode*, unsigned length); // stops at first elision + + RegisterID* emitNewFunction(RegisterID* dst, FunctionMetadataNode*); + RegisterID* emitNewFunctionInternal(RegisterID* dst, unsigned index); + RegisterID* emitNewFunctionExpression(RegisterID* dst, FuncExprNode* func); + RegisterID* emitNewDefaultConstructor(RegisterID* dst, ConstructorKind, const Identifier& name); + RegisterID* emitNewRegExp(RegisterID* dst, RegExp*); + + RegisterID* emitMoveLinkTimeConstant(RegisterID* dst, LinkTimeConstant); + RegisterID* emitMoveEmptyValue(RegisterID* dst); + RegisterID* emitMove(RegisterID* dst, RegisterID* src); + + RegisterID* emitToNumber(RegisterID* dst, RegisterID* src) { return emitUnaryOp(op_to_number, dst, src); } + RegisterID* emitToString(RegisterID* dst, RegisterID* src) { return emitUnaryOp(op_to_string, dst, src); } + RegisterID* emitInc(RegisterID* srcDst); + RegisterID* emitDec(RegisterID* srcDst); + + void emitCheckHasInstance(RegisterID* dst, RegisterID* value, RegisterID* base, Label* target); + RegisterID* emitInstanceOf(RegisterID* dst, RegisterID* value, RegisterID* basePrototype); + RegisterID* emitTypeOf(RegisterID* dst, RegisterID* src) { return emitUnaryOp(op_typeof, dst, src); } + RegisterID* emitIn(RegisterID* dst, RegisterID* property, RegisterID* base) { return emitBinaryOp(op_in, dst, property, base, OperandTypes()); } + + RegisterID* emitGetById(RegisterID* dst, RegisterID* base, const Identifier& property); + RegisterID* emitPutById(RegisterID* base, const Identifier& property, RegisterID* value); + RegisterID* emitDirectPutById(RegisterID* base, const Identifier& property, RegisterID* value, PropertyNode::PutType); + RegisterID* emitDeleteById(RegisterID* dst, RegisterID* base, const Identifier&); + RegisterID* emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* property); + RegisterID* emitGetArgumentByVal(RegisterID* dst, RegisterID* base, RegisterID* property); + RegisterID* emitPutByVal(RegisterID* base, RegisterID* property, RegisterID* value); + RegisterID* emitDirectPutByVal(RegisterID* base, RegisterID* property, RegisterID* value); + RegisterID* emitDeleteByVal(RegisterID* dst, RegisterID* base, RegisterID* property); + RegisterID* emitPutByIndex(RegisterID* base, unsigned index, RegisterID* value); + + void emitPutGetterById(RegisterID* base, const Identifier& property, RegisterID* getter); + void emitPutSetterById(RegisterID* base, const Identifier& property, RegisterID* setter); + void emitPutGetterSetter(RegisterID* base, const Identifier& property, RegisterID* getter, RegisterID* setter); + + ExpectedFunction expectedFunctionForIdentifier(const Identifier&); + RegisterID* emitCall(RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd); + RegisterID* emitCallEval(RegisterID* dst, RegisterID* func, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd); + RegisterID* emitCallVarargs(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, RegisterID* profileHookRegister, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd); + + enum PropertyDescriptorOption { + PropertyConfigurable = 1, + PropertyWritable = 1 << 1, + PropertyEnumerable = 1 << 2, + }; + void emitCallDefineProperty(RegisterID* newObj, RegisterID* propertyNameRegister, + RegisterID* valueRegister, RegisterID* getterRegister, RegisterID* setterRegister, unsigned options, const JSTextPosition&); + + void emitEnumeration(ThrowableExpressionData* enumerationNode, ExpressionNode* subjectNode, const std::function<void(BytecodeGenerator&, RegisterID*)>& callBack, VariableEnvironmentNode* = nullptr, RegisterID* forLoopSymbolTable = nullptr); + +#if ENABLE(ES6_TEMPLATE_LITERAL_SYNTAX) + RegisterID* emitGetTemplateObject(RegisterID* dst, TaggedTemplateNode*); +#endif + + RegisterID* emitReturn(RegisterID* src); + RegisterID* emitEnd(RegisterID* src) { return emitUnaryNoDstOp(op_end, src); } + + RegisterID* emitConstruct(RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd); + RegisterID* emitStrcat(RegisterID* dst, RegisterID* src, int count); + void emitToPrimitive(RegisterID* dst, RegisterID* src); + + ResolveType resolveType(); + RegisterID* emitResolveConstantLocal(RegisterID* dst, const Variable&); + RegisterID* emitResolveScope(RegisterID* dst, const Variable&); + RegisterID* emitGetFromScope(RegisterID* dst, RegisterID* scope, const Variable&, ResolveMode); + RegisterID* emitPutToScope(RegisterID* scope, const Variable&, RegisterID* value, ResolveMode); + RegisterID* initializeVariable(const Variable&, RegisterID* value); + + PassRefPtr<Label> emitLabel(Label*); + void emitLoopHint(); + PassRefPtr<Label> emitJump(Label* target); + PassRefPtr<Label> emitJumpIfTrue(RegisterID* cond, Label* target); + PassRefPtr<Label> emitJumpIfFalse(RegisterID* cond, Label* target); + PassRefPtr<Label> emitJumpIfNotFunctionCall(RegisterID* cond, Label* target); + PassRefPtr<Label> emitJumpIfNotFunctionApply(RegisterID* cond, Label* target); + void emitPopScopes(RegisterID* srcDst, int targetScopeDepth); + + RegisterID* emitHasIndexedProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName); + RegisterID* emitHasStructureProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName, RegisterID* enumerator); + RegisterID* emitHasGenericProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName); + RegisterID* emitGetPropertyEnumerator(RegisterID* dst, RegisterID* base); + RegisterID* emitGetEnumerableLength(RegisterID* dst, RegisterID* base); + RegisterID* emitGetStructurePropertyEnumerator(RegisterID* dst, RegisterID* base, RegisterID* length); + RegisterID* emitGetGenericPropertyEnumerator(RegisterID* dst, RegisterID* base, RegisterID* length, RegisterID* structureEnumerator); + RegisterID* emitEnumeratorStructurePropertyName(RegisterID* dst, RegisterID* enumerator, RegisterID* index); + RegisterID* emitEnumeratorGenericPropertyName(RegisterID* dst, RegisterID* enumerator, RegisterID* index); + RegisterID* emitToIndexString(RegisterID* dst, RegisterID* index); + + RegisterID* emitIsObject(RegisterID* dst, RegisterID* src); + RegisterID* emitIsUndefined(RegisterID* dst, RegisterID* src); + + RegisterID* emitIteratorNext(RegisterID* dst, RegisterID* iterator, const ThrowableExpressionData* node); + void emitIteratorClose(RegisterID* iterator, const ThrowableExpressionData* node); + + bool emitReadOnlyExceptionIfNeeded(const Variable&); + + // Start a try block. 'start' must have been emitted. + TryData* pushTry(Label* start); + // End a try block. 'end' must have been emitted. + void popTryAndEmitCatch(TryData*, RegisterID* exceptionRegister, RegisterID* thrownValueRegister, Label* end, HandlerType); + + void emitThrow(RegisterID* exc) + { + m_usesExceptions = true; + emitUnaryNoDstOp(op_throw, exc); + } + + void emitThrowReferenceError(const String& message); + void emitThrowTypeError(const String& message); + + void emitPushFunctionNameScope(const Identifier& property, RegisterID* value); + void emitPushCatchScope(const Identifier& property, RegisterID* exceptionValue, VariableEnvironment&); + void emitPopCatchScope(VariableEnvironment&); + + void emitGetScope(); + RegisterID* emitPushWithScope(RegisterID* objectScope); + void emitPopWithScope(); + + void emitDebugHook(DebugHookID, unsigned line, unsigned charOffset, unsigned lineStart); + + bool isInFinallyBlock() { return m_finallyDepth > 0; } + + void pushFinallyContext(StatementNode* finallyBlock); + void popFinallyContext(); + void pushIteratorCloseContext(RegisterID* iterator, ThrowableExpressionData* enumerationNode); + void popIteratorCloseContext(); + + void pushIndexedForInScope(RegisterID* local, RegisterID* index); + void popIndexedForInScope(RegisterID* local); + void pushStructureForInScope(RegisterID* local, RegisterID* index, RegisterID* property, RegisterID* enumerator); + void popStructureForInScope(RegisterID* local); + void invalidateForInContextForLocal(RegisterID* local); + + LabelScopePtr breakTarget(const Identifier&); + LabelScopePtr continueTarget(const Identifier&); + + void beginSwitch(RegisterID*, SwitchInfo::SwitchType); + void endSwitch(uint32_t clauseCount, RefPtr<Label>*, ExpressionNode**, Label* defaultLabel, int32_t min, int32_t range); + + CodeType codeType() const { return m_codeType; } + + bool shouldEmitProfileHooks() { return m_shouldEmitProfileHooks; } + bool shouldEmitDebugHooks() { return m_shouldEmitDebugHooks; } + + bool isStrictMode() const { return m_codeBlock->isStrictMode(); } + + bool isBuiltinFunction() const { return m_isBuiltinFunction; } + + OpcodeID lastOpcodeID() const { return m_lastOpcodeID; } + + private: + enum class TDZRequirement { UnderTDZ, NotUnderTDZ }; + enum class ScopeType { CatchScope, LetConstScope, FunctionNameScope }; + enum class ScopeRegisterType { Var, Block }; + void pushLexicalScopeInternal(VariableEnvironment&, bool canOptimizeTDZChecks, RegisterID** constantSymbolTableResult, TDZRequirement, ScopeType, ScopeRegisterType); + void popLexicalScopeInternal(VariableEnvironment&, TDZRequirement); + void emitPopScope(RegisterID* dst, RegisterID* scope); + RegisterID* emitGetParentScope(RegisterID* dst, RegisterID* scope); + public: + void pushLexicalScope(VariableEnvironmentNode*, bool canOptimizeTDZChecks, RegisterID** constantSymbolTableResult = nullptr); + void popLexicalScope(VariableEnvironmentNode*); + void prepareLexicalScopeForNextForLoopIteration(VariableEnvironmentNode*, RegisterID* loopSymbolTable); + int labelScopeDepth() const; + + private: + void reclaimFreeRegisters(); + Variable variableForLocalEntry(const Identifier&, const SymbolTableEntry&, int symbolTableConstantIndex, bool isLexicallyScoped); + + void emitOpcode(OpcodeID); + UnlinkedArrayAllocationProfile newArrayAllocationProfile(); + UnlinkedObjectAllocationProfile newObjectAllocationProfile(); + UnlinkedArrayProfile newArrayProfile(); + UnlinkedValueProfile emitProfiledOpcode(OpcodeID); + int kill(RegisterID* dst) + { + int index = dst->index(); + m_staticPropertyAnalyzer.kill(index); + return index; + } + + void retrieveLastBinaryOp(int& dstIndex, int& src1Index, int& src2Index); + void retrieveLastUnaryOp(int& dstIndex, int& srcIndex); + ALWAYS_INLINE void rewindBinaryOp(); + ALWAYS_INLINE void rewindUnaryOp(); + + void allocateAndEmitScope(); + void emitComplexPopScopes(RegisterID*, ControlFlowContext* topScope, ControlFlowContext* bottomScope); + + typedef HashMap<double, JSValue> NumberMap; + typedef HashMap<UniquedStringImpl*, JSString*, IdentifierRepHash> IdentifierStringMap; + typedef HashMap<TemplateRegistryKey, JSTemplateRegistryKey*> TemplateRegistryKeyMap; + + // Helper for emitCall() and emitConstruct(). This works because the set of + // expected functions have identical behavior for both call and construct + // (i.e. "Object()" is identical to "new Object()"). + ExpectedFunction emitExpectedFunctionSnippet(RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, Label* done); + + RegisterID* emitCall(OpcodeID, RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd); + + RegisterID* newRegister(); + + // Adds an anonymous local var slot. To give this slot a name, add it to symbolTable(). + RegisterID* addVar() + { + ++m_codeBlock->m_numVars; + RegisterID* result = newRegister(); + ASSERT(VirtualRegister(result->index()).toLocal() == m_codeBlock->m_numVars - 1); + result->ref(); // We should never free this slot. + return result; + } + + // Initializes the stack form the parameter; does nothing for the symbol table. + RegisterID* initializeNextParameter(); + UniquedStringImpl* visibleNameForParameter(DestructuringPatternNode*); + + RegisterID& registerFor(VirtualRegister reg) + { + if (reg.isLocal()) + return m_calleeRegisters[reg.toLocal()]; + + if (reg.offset() == JSStack::Callee) + return m_calleeRegister; + + ASSERT(m_parameters.size()); + return m_parameters[reg.toArgument()]; + } + + bool hasConstant(const Identifier&) const; + unsigned addConstant(const Identifier&); + RegisterID* addConstantValue(JSValue, SourceCodeRepresentation = SourceCodeRepresentation::Other); + RegisterID* addConstantEmptyValue(); + unsigned addRegExp(RegExp*); + + unsigned addConstantBuffer(unsigned length); + + UnlinkedFunctionExecutable* makeFunction(FunctionMetadataNode* metadata) + { + VariableEnvironment variablesUnderTDZ; + getVariablesUnderTDZ(variablesUnderTDZ); + + SourceParseMode parseMode = metadata->parseMode(); + ConstructAbility constructAbility = ConstructAbility::CanConstruct; + if (parseMode == SourceParseMode::GetterMode || parseMode == SourceParseMode::SetterMode || parseMode == SourceParseMode::ArrowFunctionMode || (parseMode == SourceParseMode::MethodMode && metadata->constructorKind() == ConstructorKind::None)) + constructAbility = ConstructAbility::CannotConstruct; + + return UnlinkedFunctionExecutable::create(m_vm, m_scopeNode->source(), metadata, isBuiltinFunction() ? UnlinkedBuiltinFunction : UnlinkedNormalFunction, constructAbility, variablesUnderTDZ); + } + + void getVariablesUnderTDZ(VariableEnvironment&); + + RegisterID* emitConstructVarargs(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, RegisterID* profileHookRegister, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd); + RegisterID* emitCallVarargs(OpcodeID, RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, RegisterID* profileHookRegister, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd); + + void initializeVarLexicalEnvironment(int symbolTableConstantIndex); + void initializeDefaultParameterValuesAndSetupFunctionScopeStack(FunctionParameters&, FunctionNode*, SymbolTable*, int symbolTableConstantIndex, const std::function<bool (UniquedStringImpl*)>& captures); + + public: + JSString* addStringConstant(const Identifier&); + JSTemplateRegistryKey* addTemplateRegistryKeyConstant(const TemplateRegistryKey&); + + Vector<UnlinkedInstruction, 0, UnsafeVectorOverflow>& instructions() { return m_instructions; } + + RegisterID* emitThrowExpressionTooDeepException(); + + private: + Vector<UnlinkedInstruction, 0, UnsafeVectorOverflow> m_instructions; + + bool m_shouldEmitDebugHooks; + bool m_shouldEmitProfileHooks; + + struct SymbolTableStackEntry { + Strong<SymbolTable> m_symbolTable; + RegisterID* m_scope; + bool m_isWithScope; + int m_symbolTableConstantIndex; + }; + Vector<SymbolTableStackEntry> m_symbolTableStack; + Vector<std::pair<VariableEnvironment, bool>> m_TDZStack; + + ScopeNode* const m_scopeNode; + Strong<UnlinkedCodeBlock> m_codeBlock; + + // Some of these objects keep pointers to one another. They are arranged + // to ensure a sane destruction order that avoids references to freed memory. + HashSet<RefPtr<UniquedStringImpl>, IdentifierRepHash> m_functions; + RegisterID m_ignoredResultRegister; + RegisterID m_thisRegister; + RegisterID m_calleeRegister; + RegisterID* m_scopeRegister { nullptr }; + RegisterID* m_topMostScope { nullptr }; + RegisterID* m_argumentsRegister { nullptr }; + RegisterID* m_lexicalEnvironmentRegister { nullptr }; + RegisterID* m_emptyValueRegister { nullptr }; + RegisterID* m_globalObjectRegister { nullptr }; + RegisterID* m_newTargetRegister { nullptr }; + RegisterID* m_linkTimeConstantRegisters[LinkTimeConstantCount]; + + SegmentedVector<RegisterID, 32> m_constantPoolRegisters; + SegmentedVector<RegisterID, 32> m_calleeRegisters; + SegmentedVector<RegisterID, 32> m_parameters; + SegmentedVector<Label, 32> m_labels; + LabelScopeStore m_labelScopes; + int m_finallyDepth { 0 }; + int m_localScopeDepth { 0 }; + const CodeType m_codeType; + + int localScopeDepth() const; + void pushScopedControlFlowContext(); + void popScopedControlFlowContext(); + + Vector<ControlFlowContext, 0, UnsafeVectorOverflow> m_scopeContextStack; + Vector<SwitchInfo> m_switchContextStack; + Vector<std::unique_ptr<ForInContext>> m_forInContextStack; + Vector<TryContext> m_tryContextStack; + enum FunctionVariableType : uint8_t { NormalFunctionVariable, GlobalFunctionVariable }; + Vector<std::pair<FunctionMetadataNode*, FunctionVariableType>> m_functionsToInitialize; + bool m_needToInitializeArguments { false }; + + Vector<TryRange> m_tryRanges; + SegmentedVector<TryData, 8> m_tryData; + + int m_nextConstantOffset { 0 }; + + typedef HashMap<FunctionMetadataNode*, unsigned> FunctionOffsetMap; + FunctionOffsetMap m_functionOffsets; + + // Constant pool + IdentifierMap m_identifierMap; + + typedef HashMap<EncodedJSValueWithRepresentation, unsigned, EncodedJSValueWithRepresentationHash, EncodedJSValueWithRepresentationHashTraits> JSValueMap; + JSValueMap m_jsValueMap; + IdentifierStringMap m_stringMap; + TemplateRegistryKeyMap m_templateRegistryKeyMap; + + StaticPropertyAnalyzer m_staticPropertyAnalyzer { &m_instructions }; + + VM* m_vm; + + OpcodeID m_lastOpcodeID = op_end; +#ifndef NDEBUG + size_t m_lastOpcodePosition { 0 }; +#endif + + bool m_usesExceptions { false }; + bool m_expressionTooDeep { false }; + bool m_isBuiltinFunction { false }; + bool m_usesNonStrictEval { false }; + }; + +} + +#endif // BytecodeGenerator_h diff --git a/Source/JavaScriptCore/bytecompiler/Label.h b/Source/JavaScriptCore/bytecompiler/Label.h new file mode 100644 index 000000000..b76c648bf --- /dev/null +++ b/Source/JavaScriptCore/bytecompiler/Label.h @@ -0,0 +1,91 @@ +/* + * Copyright (C) 2008 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef Label_h +#define Label_h + +#include "CodeBlock.h" +#include "Instruction.h" +#include <wtf/Assertions.h> +#include <wtf/Vector.h> +#include <limits.h> + +namespace JSC { + + class BytecodeGenerator; + + class Label { + public: + explicit Label(BytecodeGenerator& generator) + : m_refCount(0) + , m_location(invalidLocation) + , m_generator(generator) + { + } + + void setLocation(unsigned); + + int bind(int opcode, int offset) const + { + if (m_location == invalidLocation) { + m_unresolvedJumps.append(std::make_pair(opcode, offset)); + return 0; + } + return m_location - opcode; + } + + void ref() { ++m_refCount; } + void deref() + { + --m_refCount; + ASSERT(m_refCount >= 0); + } + int refCount() const { return m_refCount; } + + bool isForward() const { return m_location == invalidLocation; } + + int bind() + { + ASSERT(!isForward()); + return bind(0, 0); + } + + private: + typedef Vector<std::pair<int, int>, 8> JumpVector; + + static const unsigned invalidLocation = UINT_MAX; + + int m_refCount; + unsigned m_location; + BytecodeGenerator& m_generator; + mutable JumpVector m_unresolvedJumps; + }; + +} // namespace JSC + +#endif // Label_h diff --git a/Source/JavaScriptCore/bytecompiler/LabelScope.h b/Source/JavaScriptCore/bytecompiler/LabelScope.h new file mode 100644 index 000000000..9b84cb3f9 --- /dev/null +++ b/Source/JavaScriptCore/bytecompiler/LabelScope.h @@ -0,0 +1,136 @@ +/* + * Copyright (C) 2008 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef LabelScope_h +#define LabelScope_h + +#include <wtf/PassRefPtr.h> +#include "Label.h" + +namespace JSC { + + class Identifier; + + class LabelScope { + public: + enum Type { Loop, Switch, NamedLabel }; + + LabelScope(Type type, const Identifier* name, int scopeDepth, PassRefPtr<Label> breakTarget, PassRefPtr<Label> continueTarget) + : m_refCount(0) + , m_type(type) + , m_name(name) + , m_scopeDepth(scopeDepth) + , m_breakTarget(breakTarget) + , m_continueTarget(continueTarget) + { + } + int refCount() const { return m_refCount; } + + Label* breakTarget() const { return m_breakTarget.get(); } + Label* continueTarget() const { return m_continueTarget.get(); } + + Type type() const { return m_type; } + const Identifier* name() const { return m_name; } + int scopeDepth() const { return m_scopeDepth; } + + private: + friend class LabelScopePtr; + + void ref() { ++m_refCount; } + void deref() + { + --m_refCount; + ASSERT(m_refCount >= 0); + } + + int m_refCount; + Type m_type; + const Identifier* m_name; + int m_scopeDepth; + RefPtr<Label> m_breakTarget; + RefPtr<Label> m_continueTarget; + }; + + typedef Vector<LabelScope, 8> LabelScopeStore; + + class LabelScopePtr { + public: + LabelScopePtr() + : m_owner(0) + , m_index(0) + { + } + LabelScopePtr(LabelScopeStore& owner, size_t index) + : m_owner(&owner) + , m_index(index) + { + m_owner->at(index).ref(); + } + + LabelScopePtr(const LabelScopePtr& other) + : m_owner(other.m_owner) + , m_index(other.m_index) + { + if (m_owner) + m_owner->at(m_index).ref(); + } + + const LabelScopePtr& operator=(const LabelScopePtr& other) + { + if (other.m_owner) + other.m_owner->at(other.m_index).ref(); + if (m_owner) + m_owner->at(m_index).deref(); + m_owner = other.m_owner; + m_index = other.m_index; + return *this; + } + + ~LabelScopePtr() + { + if (m_owner) + m_owner->at(m_index).deref(); + } + + bool operator!() const { return !m_owner; } + + LabelScope& operator*() { ASSERT(m_owner); return m_owner->at(m_index); } + LabelScope* operator->() { ASSERT(m_owner); return &m_owner->at(m_index); } + const LabelScope& operator*() const { ASSERT(m_owner); return m_owner->at(m_index); } + const LabelScope* operator->() const { ASSERT(m_owner); return &m_owner->at(m_index); } + + static LabelScopePtr null() { return LabelScopePtr(); } + + private: + LabelScopeStore* m_owner; + size_t m_index; + }; + +} // namespace JSC + +#endif // LabelScope_h diff --git a/Source/JavaScriptCore/bytecompiler/NodesCodegen.cpp b/Source/JavaScriptCore/bytecompiler/NodesCodegen.cpp new file mode 100644 index 000000000..477fa5c73 --- /dev/null +++ b/Source/JavaScriptCore/bytecompiler/NodesCodegen.cpp @@ -0,0 +1,3331 @@ +/* +* Copyright (C) 1999-2002 Harri Porten (porten@kde.org) +* Copyright (C) 2001 Peter Kelly (pmk@post.com) +* Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2012, 2013, 2015 Apple Inc. All rights reserved. +* Copyright (C) 2007 Cameron Zwarich (cwzwarich@uwaterloo.ca) +* Copyright (C) 2007 Maks Orlovich +* Copyright (C) 2007 Eric Seidel <eric@webkit.org> + * Copyright (C) 2012 Igalia, S.L. +* +* This library is free software; you can redistribute it and/or +* modify it under the terms of the GNU Library General Public +* License as published by the Free Software Foundation; either +* version 2 of the License, or (at your option) any later version. +* +* This library is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* Library General Public License for more details. +* +* You should have received a copy of the GNU Library General Public License +* along with this library; see the file COPYING.LIB. If not, write to +* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, +* Boston, MA 02110-1301, USA. +* +*/ + +#include "config.h" +#include "Nodes.h" +#include "NodeConstructors.h" + +#include "BuiltinNames.h" +#include "BytecodeGenerator.h" +#include "CallFrame.h" +#include "Debugger.h" +#include "JIT.h" +#include "JSFunction.h" +#include "JSGlobalObject.h" +#include "JSONObject.h" +#include "LabelScope.h" +#include "Lexer.h" +#include "JSCInlines.h" +#include "JSTemplateRegistryKey.h" +#include "Parser.h" +#include "PropertyNameArray.h" +#include "RegExpCache.h" +#include "RegExpObject.h" +#include "SamplingTool.h" +#include "StackAlignment.h" +#include "TemplateRegistryKey.h" +#include <wtf/Assertions.h> +#include <wtf/RefCountedLeakCounter.h> +#include <wtf/Threading.h> + +using namespace WTF; + +namespace JSC { + +/* + Details of the emitBytecode function. + + Return value: The register holding the production's value. + dst: An optional parameter specifying the most efficient destination at + which to store the production's value. The callee must honor dst. + + The dst argument provides for a crude form of copy propagation. For example, + + x = 1 + + becomes + + load r[x], 1 + + instead of + + load r0, 1 + mov r[x], r0 + + because the assignment node, "x =", passes r[x] as dst to the number node, "1". +*/ + +void ExpressionNode::emitBytecodeInConditionContext(BytecodeGenerator& generator, Label* trueTarget, Label* falseTarget, FallThroughMode fallThroughMode) +{ + RegisterID* result = generator.emitNode(this); + if (fallThroughMode == FallThroughMeansTrue) + generator.emitJumpIfFalse(result, falseTarget); + else + generator.emitJumpIfTrue(result, trueTarget); +} + +// ------------------------------ ThrowableExpressionData -------------------------------- + +RegisterID* ThrowableExpressionData::emitThrowReferenceError(BytecodeGenerator& generator, const String& message) +{ + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + generator.emitThrowReferenceError(message); + return generator.newTemporary(); +} + +// ------------------------------ ConstantNode ---------------------------------- + +void ConstantNode::emitBytecodeInConditionContext(BytecodeGenerator& generator, Label* trueTarget, Label* falseTarget, FallThroughMode fallThroughMode) +{ + TriState value = jsValue(generator).pureToBoolean(); + if (value == MixedTriState) + ExpressionNode::emitBytecodeInConditionContext(generator, trueTarget, falseTarget, fallThroughMode); + else if (value == TrueTriState && fallThroughMode == FallThroughMeansFalse) + generator.emitJump(trueTarget); + else if (value == FalseTriState && fallThroughMode == FallThroughMeansTrue) + generator.emitJump(falseTarget); + + // All other cases are unconditional fall-throughs, like "if (true)". +} + +RegisterID* ConstantNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + if (dst == generator.ignoredResult()) + return 0; + return generator.emitLoad(dst, jsValue(generator)); +} + +JSValue StringNode::jsValue(BytecodeGenerator& generator) const +{ + return generator.addStringConstant(m_value); +} + +// ------------------------------ NumberNode ---------------------------------- + +RegisterID* NumberNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + if (dst == generator.ignoredResult()) + return nullptr; + return generator.emitLoad(dst, jsValue(generator), isIntegerNode() ? SourceCodeRepresentation::Integer : SourceCodeRepresentation::Double); +} + +// ------------------------------ RegExpNode ----------------------------------- + +RegisterID* RegExpNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + if (dst == generator.ignoredResult()) + return 0; + return generator.emitNewRegExp(generator.finalDestination(dst), RegExp::create(*generator.vm(), m_pattern.string(), regExpFlags(m_flags.string()))); +} + +// ------------------------------ ThisNode ------------------------------------- + +RegisterID* ThisNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + if (m_shouldAlwaysEmitTDZCheck || generator.constructorKind() == ConstructorKind::Derived) + generator.emitTDZCheck(generator.thisRegister()); + + if (dst == generator.ignoredResult()) + return 0; + + RegisterID* result = generator.moveToDestinationIfNeeded(dst, generator.thisRegister()); + static const unsigned thisLength = 4; + generator.emitProfileType(generator.thisRegister(), position(), JSTextPosition(-1, position().offset + thisLength, -1)); + return result; +} + +// ------------------------------ SuperNode ------------------------------------- + +RegisterID* SuperNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + if (dst == generator.ignoredResult()) + return 0; + + RegisterID callee; + callee.setIndex(JSStack::Callee); + + RefPtr<RegisterID> homeObject = generator.emitGetById(generator.newTemporary(), &callee, generator.propertyNames().homeObjectPrivateName); + RefPtr<RegisterID> protoParent = generator.emitGetById(generator.newTemporary(), homeObject.get(), generator.propertyNames().underscoreProto); + return generator.emitGetById(generator.finalDestination(dst), protoParent.get(), generator.propertyNames().constructor); +} + +static RegisterID* emitSuperBaseForCallee(BytecodeGenerator& generator) +{ + RegisterID callee; + callee.setIndex(JSStack::Callee); + + RefPtr<RegisterID> homeObject = generator.emitGetById(generator.newTemporary(), &callee, generator.propertyNames().homeObjectPrivateName); + return generator.emitGetById(generator.newTemporary(), homeObject.get(), generator.propertyNames().underscoreProto); +} + +// ------------------------------ NewTargetNode ---------------------------------- + +RegisterID* NewTargetNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + if (dst == generator.ignoredResult()) + return nullptr; + + return generator.moveToDestinationIfNeeded(dst, generator.newTarget()); +} + +// ------------------------------ ResolveNode ---------------------------------- + +bool ResolveNode::isPure(BytecodeGenerator& generator) const +{ + return generator.variable(m_ident).offset().isStack(); +} + +RegisterID* ResolveNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + Variable var = generator.variable(m_ident); + if (RegisterID* local = var.local()) { + generator.emitTDZCheckIfNecessary(var, local, nullptr); + if (dst == generator.ignoredResult()) + return nullptr; + + generator.emitProfileType(local, var, m_position, JSTextPosition(-1, m_position.offset + m_ident.length(), -1)); + return generator.moveToDestinationIfNeeded(dst, local); + } + + JSTextPosition divot = m_start + m_ident.length(); + generator.emitExpressionInfo(divot, m_start, divot); + RefPtr<RegisterID> scope = generator.emitResolveScope(dst, var); + RegisterID* finalDest = generator.finalDestination(dst); + RegisterID* result = generator.emitGetFromScope(finalDest, scope.get(), var, ThrowIfNotFound); + generator.emitTDZCheckIfNecessary(var, finalDest, nullptr); + generator.emitProfileType(finalDest, var, m_position, JSTextPosition(-1, m_position.offset + m_ident.length(), -1)); + return result; +} + +#if ENABLE(ES6_TEMPLATE_LITERAL_SYNTAX) +// ------------------------------ TemplateStringNode ----------------------------------- + +RegisterID* TemplateStringNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + if (dst == generator.ignoredResult()) + return nullptr; + return generator.emitLoad(dst, JSValue(generator.addStringConstant(cooked()))); +} + +// ------------------------------ TemplateLiteralNode ----------------------------------- + +RegisterID* TemplateLiteralNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + if (!m_templateExpressions) { + TemplateStringNode* templateString = m_templateStrings->value(); + ASSERT_WITH_MESSAGE(!m_templateStrings->next(), "Only one template element exists because there's no expression in a given template literal."); + return generator.emitNode(dst, templateString); + } + + Vector<RefPtr<RegisterID>, 16> temporaryRegisters; + + TemplateStringListNode* templateString = m_templateStrings; + TemplateExpressionListNode* templateExpression = m_templateExpressions; + for (; templateExpression; templateExpression = templateExpression->next(), templateString = templateString->next()) { + // Evaluate TemplateString. + if (!templateString->value()->cooked().isEmpty()) { + temporaryRegisters.append(generator.newTemporary()); + generator.emitNode(temporaryRegisters.last().get(), templateString->value()); + } + + // Evaluate Expression. + temporaryRegisters.append(generator.newTemporary()); + generator.emitNode(temporaryRegisters.last().get(), templateExpression->value()); + generator.emitToString(temporaryRegisters.last().get(), temporaryRegisters.last().get()); + } + + // Evaluate tail TemplateString. + if (!templateString->value()->cooked().isEmpty()) { + temporaryRegisters.append(generator.newTemporary()); + generator.emitNode(temporaryRegisters.last().get(), templateString->value()); + } + + return generator.emitStrcat(generator.finalDestination(dst, temporaryRegisters[0].get()), temporaryRegisters[0].get(), temporaryRegisters.size()); +} + +// ------------------------------ TaggedTemplateNode ----------------------------------- + +RegisterID* TaggedTemplateNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + ExpectedFunction expectedFunction = NoExpectedFunction; + RefPtr<RegisterID> tag = nullptr; + RefPtr<RegisterID> base = nullptr; + if (!m_tag->isLocation()) { + tag = generator.newTemporary(); + tag = generator.emitNode(tag.get(), m_tag); + } else if (m_tag->isResolveNode()) { + ResolveNode* resolve = static_cast<ResolveNode*>(m_tag); + const Identifier& identifier = resolve->identifier(); + expectedFunction = generator.expectedFunctionForIdentifier(identifier); + + Variable var = generator.variable(identifier); + if (RegisterID* local = var.local()) + tag = generator.emitMove(generator.newTemporary(), local); + else { + tag = generator.newTemporary(); + base = generator.newTemporary(); + + JSTextPosition newDivot = divotStart() + identifier.length(); + generator.emitExpressionInfo(newDivot, divotStart(), newDivot); + generator.moveToDestinationIfNeeded(base.get(), generator.emitResolveScope(base.get(), var)); + generator.emitGetFromScope(tag.get(), base.get(), var, ThrowIfNotFound); + } + } else if (m_tag->isBracketAccessorNode()) { + BracketAccessorNode* bracket = static_cast<BracketAccessorNode*>(m_tag); + base = generator.newTemporary(); + base = generator.emitNode(base.get(), bracket->base()); + RefPtr<RegisterID> property = generator.emitNode(bracket->subscript()); + tag = generator.emitGetByVal(generator.newTemporary(), base.get(), property.get()); + } else { + ASSERT(m_tag->isDotAccessorNode()); + DotAccessorNode* dot = static_cast<DotAccessorNode*>(m_tag); + base = generator.newTemporary(); + base = generator.emitNode(base.get(), dot->base()); + tag = generator.emitGetById(generator.newTemporary(), base.get(), dot->identifier()); + } + + RefPtr<RegisterID> templateObject = generator.emitGetTemplateObject(generator.newTemporary(), this); + + unsigned expressionsCount = 0; + for (TemplateExpressionListNode* templateExpression = m_templateLiteral->templateExpressions(); templateExpression; templateExpression = templateExpression->next()) + ++expressionsCount; + + CallArguments callArguments(generator, nullptr, 1 + expressionsCount); + if (base) + generator.emitMove(callArguments.thisRegister(), base.get()); + else + generator.emitLoad(callArguments.thisRegister(), jsUndefined()); + + unsigned argumentIndex = 0; + generator.emitMove(callArguments.argumentRegister(argumentIndex++), templateObject.get()); + for (TemplateExpressionListNode* templateExpression = m_templateLiteral->templateExpressions(); templateExpression; templateExpression = templateExpression->next()) + generator.emitNode(callArguments.argumentRegister(argumentIndex++), templateExpression->value()); + + return generator.emitCall(generator.finalDestination(dst, tag.get()), tag.get(), expectedFunction, callArguments, divot(), divotStart(), divotEnd()); +} +#endif + +// ------------------------------ ArrayNode ------------------------------------ + +RegisterID* ArrayNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + // FIXME: Should we put all of this code into emitNewArray? + + unsigned length = 0; + ElementNode* firstPutElement; + for (firstPutElement = m_element; firstPutElement; firstPutElement = firstPutElement->next()) { + if (firstPutElement->elision() || firstPutElement->value()->isSpreadExpression()) + break; + ++length; + } + + if (!firstPutElement && !m_elision) + return generator.emitNewArray(generator.finalDestination(dst), m_element, length); + + RefPtr<RegisterID> array = generator.emitNewArray(generator.tempDestination(dst), m_element, length); + ElementNode* n = firstPutElement; + for (; n; n = n->next()) { + if (n->value()->isSpreadExpression()) + goto handleSpread; + RegisterID* value = generator.emitNode(n->value()); + length += n->elision(); + generator.emitPutByIndex(array.get(), length++, value); + } + + if (m_elision) { + RegisterID* value = generator.emitLoad(0, jsNumber(m_elision + length)); + generator.emitPutById(array.get(), generator.propertyNames().length, value); + } + + return generator.moveToDestinationIfNeeded(dst, array.get()); + +handleSpread: + RefPtr<RegisterID> index = generator.emitLoad(generator.newTemporary(), jsNumber(length)); + auto spreader = [this, array, index](BytecodeGenerator& generator, RegisterID* value) + { + generator.emitDirectPutByVal(array.get(), index.get(), value); + generator.emitInc(index.get()); + }; + for (; n; n = n->next()) { + if (n->elision()) + generator.emitBinaryOp(op_add, index.get(), index.get(), generator.emitLoad(0, jsNumber(n->elision())), OperandTypes(ResultType::numberTypeIsInt32(), ResultType::numberTypeIsInt32())); + if (n->value()->isSpreadExpression()) { + SpreadExpressionNode* spread = static_cast<SpreadExpressionNode*>(n->value()); + generator.emitEnumeration(spread, spread->expression(), spreader); + } else { + generator.emitDirectPutByVal(array.get(), index.get(), generator.emitNode(n->value())); + generator.emitInc(index.get()); + } + } + + if (m_elision) { + generator.emitBinaryOp(op_add, index.get(), index.get(), generator.emitLoad(0, jsNumber(m_elision)), OperandTypes(ResultType::numberTypeIsInt32(), ResultType::numberTypeIsInt32())); + generator.emitPutById(array.get(), generator.propertyNames().length, index.get()); + } + return generator.moveToDestinationIfNeeded(dst, array.get()); +} + +bool ArrayNode::isSimpleArray() const +{ + if (m_elision || m_optional) + return false; + for (ElementNode* ptr = m_element; ptr; ptr = ptr->next()) { + if (ptr->elision()) + return false; + } + return true; +} + +ArgumentListNode* ArrayNode::toArgumentList(ParserArena& parserArena, int lineNumber, int startPosition) const +{ + ASSERT(!m_elision && !m_optional); + ElementNode* ptr = m_element; + if (!ptr) + return 0; + JSTokenLocation location; + location.line = lineNumber; + location.startOffset = startPosition; + ArgumentListNode* head = new (parserArena) ArgumentListNode(location, ptr->value()); + ArgumentListNode* tail = head; + ptr = ptr->next(); + for (; ptr; ptr = ptr->next()) { + ASSERT(!ptr->elision()); + tail = new (parserArena) ArgumentListNode(location, tail, ptr->value()); + } + return head; +} + +// ------------------------------ ObjectLiteralNode ---------------------------- + +RegisterID* ObjectLiteralNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + if (!m_list) { + if (dst == generator.ignoredResult()) + return 0; + return generator.emitNewObject(generator.finalDestination(dst)); + } + RefPtr<RegisterID> newObj = generator.emitNewObject(generator.tempDestination(dst)); + generator.emitNode(newObj.get(), m_list); + return generator.moveToDestinationIfNeeded(dst, newObj.get()); +} + +// ------------------------------ PropertyListNode ----------------------------- + +static inline void emitPutHomeObject(BytecodeGenerator& generator, RegisterID* function, RegisterID* homeObject) +{ + generator.emitPutById(function, generator.propertyNames().homeObjectPrivateName, homeObject); +} + +RegisterID* PropertyListNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + // Fast case: this loop just handles regular value properties. + PropertyListNode* p = this; + for (; p && (p->m_node->m_type & PropertyNode::Constant); p = p->m_next) + emitPutConstantProperty(generator, dst, *p->m_node); + + // Were there any get/set properties? + if (p) { + // Build a list of getter/setter pairs to try to put them at the same time. If we encounter + // a computed property, just emit everything as that may override previous values. + bool hasComputedProperty = false; + + typedef std::pair<PropertyNode*, PropertyNode*> GetterSetterPair; + typedef HashMap<UniquedStringImpl*, GetterSetterPair, IdentifierRepHash> GetterSetterMap; + GetterSetterMap map; + + // Build a map, pairing get/set values together. + for (PropertyListNode* q = p; q; q = q->m_next) { + PropertyNode* node = q->m_node; + if (node->m_type & PropertyNode::Computed) { + hasComputedProperty = true; + break; + } + if (node->m_type & PropertyNode::Constant) + continue; + + // Duplicates are possible. + GetterSetterPair pair(node, static_cast<PropertyNode*>(nullptr)); + GetterSetterMap::AddResult result = map.add(node->name()->impl(), pair); + if (!result.isNewEntry) { + if (result.iterator->value.first->m_type == node->m_type) + result.iterator->value.first = node; + else + result.iterator->value.second = node; + } + } + + // Iterate over the remaining properties in the list. + for (; p; p = p->m_next) { + PropertyNode* node = p->m_node; + + // Handle regular values. + if (node->m_type & PropertyNode::Constant) { + emitPutConstantProperty(generator, dst, *node); + continue; + } + + RegisterID* value = generator.emitNode(node->m_assign); + bool isClassProperty = node->needsSuperBinding(); + if (isClassProperty) + emitPutHomeObject(generator, value, dst); + + ASSERT(node->m_type & (PropertyNode::Getter | PropertyNode::Setter)); + + // This is a get/set property which may be overridden by a computed property later. + if (hasComputedProperty) { + if (node->m_type & PropertyNode::Getter) + generator.emitPutGetterById(dst, *node->name(), value); + else + generator.emitPutSetterById(dst, *node->name(), value); + continue; + } + + // This is a get/set property pair. + GetterSetterMap::iterator it = map.find(node->name()->impl()); + ASSERT(it != map.end()); + GetterSetterPair& pair = it->value; + + // Was this already generated as a part of its partner? + if (pair.second == node) + continue; + + // Generate the paired node now. + RefPtr<RegisterID> getterReg; + RefPtr<RegisterID> setterReg; + RegisterID* secondReg = nullptr; + + if (node->m_type & PropertyNode::Getter) { + getterReg = value; + if (pair.second) { + ASSERT(pair.second->m_type & PropertyNode::Setter); + setterReg = generator.emitNode(pair.second->m_assign); + secondReg = setterReg.get(); + } else { + setterReg = generator.newTemporary(); + generator.emitLoad(setterReg.get(), jsUndefined()); + } + } else { + ASSERT(node->m_type & PropertyNode::Setter); + setterReg = value; + if (pair.second) { + ASSERT(pair.second->m_type & PropertyNode::Getter); + getterReg = generator.emitNode(pair.second->m_assign); + secondReg = getterReg.get(); + } else { + getterReg = generator.newTemporary(); + generator.emitLoad(getterReg.get(), jsUndefined()); + } + } + + ASSERT(!pair.second || isClassProperty == pair.second->needsSuperBinding()); + if (isClassProperty && pair.second) + emitPutHomeObject(generator, secondReg, dst); + + if (isClassProperty) { + RefPtr<RegisterID> propertyNameRegister = generator.emitLoad(generator.newTemporary(), *node->name()); + generator.emitCallDefineProperty(dst, propertyNameRegister.get(), + nullptr, getterReg.get(), setterReg.get(), BytecodeGenerator::PropertyConfigurable, m_position); + } else + generator.emitPutGetterSetter(dst, *node->name(), getterReg.get(), setterReg.get()); + } + } + + return dst; +} + +void PropertyListNode::emitPutConstantProperty(BytecodeGenerator& generator, RegisterID* newObj, PropertyNode& node) +{ + RefPtr<RegisterID> value = generator.emitNode(node.m_assign); + if (node.needsSuperBinding()) { + emitPutHomeObject(generator, value.get(), newObj); + + RefPtr<RegisterID> propertyNameRegister; + if (node.name()) + propertyNameRegister = generator.emitLoad(generator.newTemporary(), *node.name()); + else + propertyNameRegister = generator.emitNode(node.m_expression); + + generator.emitCallDefineProperty(newObj, propertyNameRegister.get(), + value.get(), nullptr, nullptr, BytecodeGenerator::PropertyConfigurable | BytecodeGenerator::PropertyWritable, m_position); + return; + } + if (const auto* identifier = node.name()) { + Optional<uint32_t> optionalIndex = parseIndex(*identifier); + if (!optionalIndex) { + generator.emitDirectPutById(newObj, *identifier, value.get(), node.putType()); + return; + } + + RefPtr<RegisterID> index = generator.emitLoad(generator.newTemporary(), jsNumber(optionalIndex.value())); + generator.emitDirectPutByVal(newObj, index.get(), value.get()); + return; + } + RefPtr<RegisterID> propertyName = generator.emitNode(node.m_expression); + generator.emitDirectPutByVal(newObj, propertyName.get(), value.get()); +} + +// ------------------------------ BracketAccessorNode -------------------------------- + +RegisterID* BracketAccessorNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + if (m_base->isSuperNode()) { + // FIXME: Should we generate the profiler info? + if (m_subscript->isString()) { + const Identifier& id = static_cast<StringNode*>(m_subscript)->value(); + return generator.emitGetById(generator.finalDestination(dst), emitSuperBaseForCallee(generator), id); + } + return generator.emitGetByVal(generator.finalDestination(dst), emitSuperBaseForCallee(generator), generator.emitNode(m_subscript)); + } + + RegisterID* ret; + RegisterID* finalDest = generator.finalDestination(dst); + + if (m_subscript->isString()) { + RefPtr<RegisterID> base = generator.emitNode(m_base); + ret = generator.emitGetById(finalDest, base.get(), static_cast<StringNode*>(m_subscript)->value()); + } else { + RefPtr<RegisterID> base = generator.emitNodeForLeftHandSide(m_base, m_subscriptHasAssignments, m_subscript->isPure(generator)); + RegisterID* property = generator.emitNode(m_subscript); + ret = generator.emitGetByVal(finalDest, base.get(), property); + } + + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + + generator.emitProfileType(finalDest, divotStart(), divotEnd()); + return ret; +} + +// ------------------------------ DotAccessorNode -------------------------------- + +RegisterID* DotAccessorNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + RefPtr<RegisterID> base = m_base->isSuperNode() ? emitSuperBaseForCallee(generator) : generator.emitNode(m_base); + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + RegisterID* finalDest = generator.finalDestination(dst); + RegisterID* ret = generator.emitGetById(finalDest, base.get(), m_ident); + generator.emitProfileType(finalDest, divotStart(), divotEnd()); + return ret; +} + +// ------------------------------ ArgumentListNode ----------------------------- + +RegisterID* ArgumentListNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + ASSERT(m_expr); + return generator.emitNode(dst, m_expr); +} + +// ------------------------------ NewExprNode ---------------------------------- + +RegisterID* NewExprNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + ExpectedFunction expectedFunction; + if (m_expr->isResolveNode()) + expectedFunction = generator.expectedFunctionForIdentifier(static_cast<ResolveNode*>(m_expr)->identifier()); + else + expectedFunction = NoExpectedFunction; + RefPtr<RegisterID> func = generator.emitNode(m_expr); + RefPtr<RegisterID> returnValue = generator.finalDestination(dst, func.get()); + CallArguments callArguments(generator, m_args); + generator.emitMove(callArguments.thisRegister(), func.get()); + return generator.emitConstruct(returnValue.get(), func.get(), expectedFunction, callArguments, divot(), divotStart(), divotEnd()); +} + +CallArguments::CallArguments(BytecodeGenerator& generator, ArgumentsNode* argumentsNode, unsigned additionalArguments) + : m_argumentsNode(argumentsNode) + , m_padding(0) +{ + if (generator.shouldEmitProfileHooks()) + m_profileHookRegister = generator.newTemporary(); + + size_t argumentCountIncludingThis = 1 + additionalArguments; // 'this' register. + if (argumentsNode) { + for (ArgumentListNode* node = argumentsNode->m_listNode; node; node = node->m_next) + ++argumentCountIncludingThis; + } + + m_argv.grow(argumentCountIncludingThis); + for (int i = argumentCountIncludingThis - 1; i >= 0; --i) { + m_argv[i] = generator.newTemporary(); + ASSERT(static_cast<size_t>(i) == m_argv.size() - 1 || m_argv[i]->index() == m_argv[i + 1]->index() - 1); + } + + while (stackOffset() % stackAlignmentRegisters()) { + m_argv.insert(0, generator.newTemporary()); + m_padding++; + } +} + +// ------------------------------ EvalFunctionCallNode ---------------------------------- + +RegisterID* EvalFunctionCallNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + Variable var = generator.variable(generator.propertyNames().eval); + if (RegisterID* local = var.local()) { + RefPtr<RegisterID> func = generator.emitMove(generator.tempDestination(dst), local); + CallArguments callArguments(generator, m_args); + generator.emitLoad(callArguments.thisRegister(), jsUndefined()); + return generator.emitCallEval(generator.finalDestination(dst, func.get()), func.get(), callArguments, divot(), divotStart(), divotEnd()); + } + + RefPtr<RegisterID> func = generator.newTemporary(); + CallArguments callArguments(generator, m_args); + JSTextPosition newDivot = divotStart() + 4; + generator.emitExpressionInfo(newDivot, divotStart(), newDivot); + generator.moveToDestinationIfNeeded( + callArguments.thisRegister(), + generator.emitResolveScope(callArguments.thisRegister(), var)); + generator.emitGetFromScope(func.get(), callArguments.thisRegister(), var, ThrowIfNotFound); + return generator.emitCallEval(generator.finalDestination(dst, func.get()), func.get(), callArguments, divot(), divotStart(), divotEnd()); +} + +// ------------------------------ FunctionCallValueNode ---------------------------------- + +RegisterID* FunctionCallValueNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + RefPtr<RegisterID> func = generator.emitNode(m_expr); + RefPtr<RegisterID> returnValue = generator.finalDestination(dst, func.get()); + CallArguments callArguments(generator, m_args); + if (m_expr->isSuperNode()) { + ASSERT(generator.isConstructor()); + ASSERT(generator.constructorKind() == ConstructorKind::Derived); + generator.emitMove(callArguments.thisRegister(), generator.newTarget()); + RegisterID* ret = generator.emitConstruct(returnValue.get(), func.get(), NoExpectedFunction, callArguments, divot(), divotStart(), divotEnd()); + generator.emitMove(generator.thisRegister(), ret); + return ret; + } + generator.emitLoad(callArguments.thisRegister(), jsUndefined()); + RegisterID* ret = generator.emitCall(returnValue.get(), func.get(), NoExpectedFunction, callArguments, divot(), divotStart(), divotEnd()); + generator.emitProfileType(returnValue.get(), divotStart(), divotEnd()); + return ret; +} + +// ------------------------------ FunctionCallResolveNode ---------------------------------- + +RegisterID* FunctionCallResolveNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + ExpectedFunction expectedFunction = generator.expectedFunctionForIdentifier(m_ident); + + Variable var = generator.variable(m_ident); + if (RegisterID* local = var.local()) { + generator.emitTDZCheckIfNecessary(var, local, nullptr); + RefPtr<RegisterID> func = generator.emitMove(generator.tempDestination(dst), local); + RefPtr<RegisterID> returnValue = generator.finalDestination(dst, func.get()); + CallArguments callArguments(generator, m_args); + generator.emitLoad(callArguments.thisRegister(), jsUndefined()); + // This passes NoExpectedFunction because we expect that if the function is in a + // local variable, then it's not one of our built-in constructors. + RegisterID* ret = generator.emitCall(returnValue.get(), func.get(), NoExpectedFunction, callArguments, divot(), divotStart(), divotEnd()); + generator.emitProfileType(returnValue.get(), divotStart(), divotEnd()); + return ret; + } + + RefPtr<RegisterID> func = generator.newTemporary(); + RefPtr<RegisterID> returnValue = generator.finalDestination(dst, func.get()); + CallArguments callArguments(generator, m_args); + + JSTextPosition newDivot = divotStart() + m_ident.length(); + generator.emitExpressionInfo(newDivot, divotStart(), newDivot); + generator.moveToDestinationIfNeeded( + callArguments.thisRegister(), + generator.emitResolveScope(callArguments.thisRegister(), var)); + generator.emitGetFromScope(func.get(), callArguments.thisRegister(), var, ThrowIfNotFound); + generator.emitTDZCheckIfNecessary(var, func.get(), nullptr); + RegisterID* ret = generator.emitCall(returnValue.get(), func.get(), expectedFunction, callArguments, divot(), divotStart(), divotEnd()); + generator.emitProfileType(returnValue.get(), divotStart(), divotEnd()); + return ret; +} + +// ------------------------------ BytecodeIntrinsicNode ---------------------------------- + +RegisterID* BytecodeIntrinsicNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + return (this->*m_emitter)(generator, dst); +} + +RegisterID* BytecodeIntrinsicNode::emit_intrinsic_putByValDirect(BytecodeGenerator& generator, RegisterID* dst) +{ + ArgumentListNode* node = m_args->m_listNode; + RefPtr<RegisterID> base = generator.emitNode(node); + node = node->m_next; + RefPtr<RegisterID> index = generator.emitNode(node); + node = node->m_next; + RefPtr<RegisterID> value = generator.emitNode(node); + + ASSERT(!node->m_next); + + return generator.moveToDestinationIfNeeded(dst, generator.emitDirectPutByVal(base.get(), index.get(), value.get())); +} + +RegisterID* BytecodeIntrinsicNode::emit_intrinsic_toString(BytecodeGenerator& generator, RegisterID* dst) +{ + ArgumentListNode* node = m_args->m_listNode; + RefPtr<RegisterID> src = generator.emitNode(node); + ASSERT(!node->m_next); + + return generator.moveToDestinationIfNeeded(dst, generator.emitToString(generator.tempDestination(dst), src.get())); +} + +// ------------------------------ FunctionCallBracketNode ---------------------------------- + +RegisterID* FunctionCallBracketNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + bool baseIsSuper = m_base->isSuperNode(); + bool subscriptIsString = m_subscript->isString(); + + RefPtr<RegisterID> base; + if (baseIsSuper) + base = emitSuperBaseForCallee(generator); + else { + if (subscriptIsString) + base = generator.emitNode(m_base); + else + base = generator.emitNodeForLeftHandSide(m_base, m_subscriptHasAssignments, m_subscript->isPure(generator)); + } + + RefPtr<RegisterID> function; + if (subscriptIsString) { + generator.emitExpressionInfo(subexpressionDivot(), subexpressionStart(), subexpressionEnd()); + function = generator.emitGetById(generator.tempDestination(dst), base.get(), static_cast<StringNode*>(m_subscript)->value()); + } else { + RefPtr<RegisterID> property = generator.emitNode(m_subscript); + generator.emitExpressionInfo(subexpressionDivot(), subexpressionStart(), subexpressionEnd()); + function = generator.emitGetByVal(generator.tempDestination(dst), base.get(), property.get()); + } + + RefPtr<RegisterID> returnValue = generator.finalDestination(dst, function.get()); + CallArguments callArguments(generator, m_args); + if (baseIsSuper) + generator.emitMove(callArguments.thisRegister(), generator.thisRegister()); + else + generator.emitMove(callArguments.thisRegister(), base.get()); + RegisterID* ret = generator.emitCall(returnValue.get(), function.get(), NoExpectedFunction, callArguments, divot(), divotStart(), divotEnd()); + generator.emitProfileType(returnValue.get(), divotStart(), divotEnd()); + return ret; +} + +// ------------------------------ FunctionCallDotNode ---------------------------------- + +RegisterID* FunctionCallDotNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + RefPtr<RegisterID> function = generator.tempDestination(dst); + RefPtr<RegisterID> returnValue = generator.finalDestination(dst, function.get()); + CallArguments callArguments(generator, m_args); + bool baseIsSuper = m_base->isSuperNode(); + if (baseIsSuper) + generator.emitMove(callArguments.thisRegister(), generator.thisRegister()); + else + generator.emitNode(callArguments.thisRegister(), m_base); + generator.emitExpressionInfo(subexpressionDivot(), subexpressionStart(), subexpressionEnd()); + generator.emitGetById(function.get(), baseIsSuper ? emitSuperBaseForCallee(generator) : callArguments.thisRegister(), m_ident); + RegisterID* ret = generator.emitCall(returnValue.get(), function.get(), NoExpectedFunction, callArguments, divot(), divotStart(), divotEnd()); + generator.emitProfileType(returnValue.get(), divotStart(), divotEnd()); + return ret; +} + +RegisterID* CallFunctionCallDotNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + RefPtr<Label> realCall = generator.newLabel(); + RefPtr<Label> end = generator.newLabel(); + RefPtr<RegisterID> base = generator.emitNode(m_base); + generator.emitExpressionInfo(subexpressionDivot(), subexpressionStart(), subexpressionEnd()); + RefPtr<RegisterID> function; + bool emitCallCheck = !generator.isBuiltinFunction(); + if (emitCallCheck) { + function = generator.emitGetById(generator.tempDestination(dst), base.get(), generator.propertyNames().builtinNames().callPublicName()); + generator.emitJumpIfNotFunctionCall(function.get(), realCall.get()); + } + RefPtr<RegisterID> returnValue = generator.finalDestination(dst); + { + if (m_args->m_listNode && m_args->m_listNode->m_expr && m_args->m_listNode->m_expr->isSpreadExpression()) { + RefPtr<RegisterID> profileHookRegister; + if (generator.shouldEmitProfileHooks()) + profileHookRegister = generator.newTemporary(); + SpreadExpressionNode* spread = static_cast<SpreadExpressionNode*>(m_args->m_listNode->m_expr); + ExpressionNode* subject = spread->expression(); + RefPtr<RegisterID> argumentsRegister; + argumentsRegister = generator.emitNode(subject); + generator.emitExpressionInfo(spread->divot(), spread->divotStart(), spread->divotEnd()); + RefPtr<RegisterID> thisRegister = generator.emitGetByVal(generator.newTemporary(), argumentsRegister.get(), generator.emitLoad(0, jsNumber(0))); + generator.emitCallVarargs(returnValue.get(), base.get(), thisRegister.get(), argumentsRegister.get(), generator.newTemporary(), 1, profileHookRegister.get(), divot(), divotStart(), divotEnd()); + } else if (m_args->m_listNode && m_args->m_listNode->m_expr) { + ArgumentListNode* oldList = m_args->m_listNode; + m_args->m_listNode = m_args->m_listNode->m_next; + + RefPtr<RegisterID> realFunction = generator.emitMove(generator.tempDestination(dst), base.get()); + CallArguments callArguments(generator, m_args); + generator.emitNode(callArguments.thisRegister(), oldList->m_expr); + generator.emitCall(returnValue.get(), realFunction.get(), NoExpectedFunction, callArguments, divot(), divotStart(), divotEnd()); + m_args->m_listNode = oldList; + } else { + RefPtr<RegisterID> realFunction = generator.emitMove(generator.tempDestination(dst), base.get()); + CallArguments callArguments(generator, m_args); + generator.emitLoad(callArguments.thisRegister(), jsUndefined()); + generator.emitCall(returnValue.get(), realFunction.get(), NoExpectedFunction, callArguments, divot(), divotStart(), divotEnd()); + } + } + if (emitCallCheck) { + generator.emitJump(end.get()); + generator.emitLabel(realCall.get()); + { + CallArguments callArguments(generator, m_args); + generator.emitMove(callArguments.thisRegister(), base.get()); + generator.emitCall(returnValue.get(), function.get(), NoExpectedFunction, callArguments, divot(), divotStart(), divotEnd()); + } + generator.emitLabel(end.get()); + } + generator.emitProfileType(returnValue.get(), divotStart(), divotEnd()); + return returnValue.get(); +} + +static bool areTrivialApplyArguments(ArgumentsNode* args) +{ + return !args->m_listNode || !args->m_listNode->m_expr || !args->m_listNode->m_next + || (!args->m_listNode->m_next->m_next && args->m_listNode->m_next->m_expr->isSimpleArray()); +} + +RegisterID* ApplyFunctionCallDotNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + // A few simple cases can be trivially handled as ordinary function calls. + // function.apply(), function.apply(arg) -> identical to function.call + // function.apply(thisArg, [arg0, arg1, ...]) -> can be trivially coerced into function.call(thisArg, arg0, arg1, ...) and saves object allocation + bool mayBeCall = areTrivialApplyArguments(m_args); + + RefPtr<Label> realCall = generator.newLabel(); + RefPtr<Label> end = generator.newLabel(); + RefPtr<RegisterID> base = generator.emitNode(m_base); + generator.emitExpressionInfo(subexpressionDivot(), subexpressionStart(), subexpressionEnd()); + RefPtr<RegisterID> function; + RefPtr<RegisterID> returnValue = generator.finalDestination(dst, function.get()); + bool emitCallCheck = !generator.isBuiltinFunction(); + if (emitCallCheck) { + function = generator.emitGetById(generator.tempDestination(dst), base.get(), generator.propertyNames().builtinNames().applyPublicName()); + generator.emitJumpIfNotFunctionApply(function.get(), realCall.get()); + } + if (mayBeCall) { + if (m_args->m_listNode && m_args->m_listNode->m_expr) { + ArgumentListNode* oldList = m_args->m_listNode; + if (m_args->m_listNode->m_expr->isSpreadExpression()) { + SpreadExpressionNode* spread = static_cast<SpreadExpressionNode*>(m_args->m_listNode->m_expr); + RefPtr<RegisterID> profileHookRegister; + if (generator.shouldEmitProfileHooks()) + profileHookRegister = generator.newTemporary(); + RefPtr<RegisterID> realFunction = generator.emitMove(generator.newTemporary(), base.get()); + RefPtr<RegisterID> index = generator.emitLoad(generator.newTemporary(), jsNumber(0)); + RefPtr<RegisterID> thisRegister = generator.emitLoad(generator.newTemporary(), jsUndefined()); + RefPtr<RegisterID> argumentsRegister = generator.emitLoad(generator.newTemporary(), jsUndefined()); + + auto extractor = [&thisRegister, &argumentsRegister, &index](BytecodeGenerator& generator, RegisterID* value) + { + RefPtr<Label> haveThis = generator.newLabel(); + RefPtr<Label> end = generator.newLabel(); + RefPtr<RegisterID> compareResult = generator.newTemporary(); + RefPtr<RegisterID> indexZeroCompareResult = generator.emitBinaryOp(op_eq, compareResult.get(), index.get(), generator.emitLoad(0, jsNumber(0)), OperandTypes(ResultType::numberTypeIsInt32(), ResultType::numberTypeIsInt32())); + generator.emitJumpIfFalse(indexZeroCompareResult.get(), haveThis.get()); + generator.emitMove(thisRegister.get(), value); + generator.emitLoad(index.get(), jsNumber(1)); + generator.emitJump(end.get()); + generator.emitLabel(haveThis.get()); + RefPtr<RegisterID> indexOneCompareResult = generator.emitBinaryOp(op_eq, compareResult.get(), index.get(), generator.emitLoad(0, jsNumber(1)), OperandTypes(ResultType::numberTypeIsInt32(), ResultType::numberTypeIsInt32())); + generator.emitJumpIfFalse(indexOneCompareResult.get(), end.get()); + generator.emitMove(argumentsRegister.get(), value); + generator.emitLoad(index.get(), jsNumber(2)); + generator.emitLabel(end.get()); + }; + generator.emitEnumeration(this, spread->expression(), extractor); + generator.emitCallVarargs(returnValue.get(), realFunction.get(), thisRegister.get(), argumentsRegister.get(), generator.newTemporary(), 0, profileHookRegister.get(), divot(), divotStart(), divotEnd()); + } else if (m_args->m_listNode->m_next) { + ASSERT(m_args->m_listNode->m_next->m_expr->isSimpleArray()); + ASSERT(!m_args->m_listNode->m_next->m_next); + m_args->m_listNode = static_cast<ArrayNode*>(m_args->m_listNode->m_next->m_expr)->toArgumentList(generator.parserArena(), 0, 0); + RefPtr<RegisterID> realFunction = generator.emitMove(generator.tempDestination(dst), base.get()); + CallArguments callArguments(generator, m_args); + generator.emitNode(callArguments.thisRegister(), oldList->m_expr); + generator.emitCall(returnValue.get(), realFunction.get(), NoExpectedFunction, callArguments, divot(), divotStart(), divotEnd()); + } else { + m_args->m_listNode = m_args->m_listNode->m_next; + RefPtr<RegisterID> realFunction = generator.emitMove(generator.tempDestination(dst), base.get()); + CallArguments callArguments(generator, m_args); + generator.emitNode(callArguments.thisRegister(), oldList->m_expr); + generator.emitCall(returnValue.get(), realFunction.get(), NoExpectedFunction, callArguments, divot(), divotStart(), divotEnd()); + } + m_args->m_listNode = oldList; + } else { + RefPtr<RegisterID> realFunction = generator.emitMove(generator.tempDestination(dst), base.get()); + CallArguments callArguments(generator, m_args); + generator.emitLoad(callArguments.thisRegister(), jsUndefined()); + generator.emitCall(returnValue.get(), realFunction.get(), NoExpectedFunction, callArguments, divot(), divotStart(), divotEnd()); + } + } else { + ASSERT(m_args->m_listNode && m_args->m_listNode->m_next); + RefPtr<RegisterID> profileHookRegister; + if (generator.shouldEmitProfileHooks()) + profileHookRegister = generator.newTemporary(); + RefPtr<RegisterID> realFunction = generator.emitMove(generator.tempDestination(dst), base.get()); + RefPtr<RegisterID> thisRegister = generator.emitNode(m_args->m_listNode->m_expr); + RefPtr<RegisterID> argsRegister; + ArgumentListNode* args = m_args->m_listNode->m_next; + argsRegister = generator.emitNode(args->m_expr); + + // Function.prototype.apply ignores extra arguments, but we still + // need to evaluate them for side effects. + while ((args = args->m_next)) + generator.emitNode(args->m_expr); + + generator.emitCallVarargs(returnValue.get(), realFunction.get(), thisRegister.get(), argsRegister.get(), generator.newTemporary(), 0, profileHookRegister.get(), divot(), divotStart(), divotEnd()); + } + if (emitCallCheck) { + generator.emitJump(end.get()); + generator.emitLabel(realCall.get()); + CallArguments callArguments(generator, m_args); + generator.emitMove(callArguments.thisRegister(), base.get()); + generator.emitCall(returnValue.get(), function.get(), NoExpectedFunction, callArguments, divot(), divotStart(), divotEnd()); + generator.emitLabel(end.get()); + } + generator.emitProfileType(returnValue.get(), divotStart(), divotEnd()); + return returnValue.get(); +} + +// ------------------------------ PostfixNode ---------------------------------- + +static RegisterID* emitIncOrDec(BytecodeGenerator& generator, RegisterID* srcDst, Operator oper) +{ + return (oper == OpPlusPlus) ? generator.emitInc(srcDst) : generator.emitDec(srcDst); +} + +static RegisterID* emitPostIncOrDec(BytecodeGenerator& generator, RegisterID* dst, RegisterID* srcDst, Operator oper) +{ + if (dst == srcDst) + return generator.emitToNumber(generator.finalDestination(dst), srcDst); + RefPtr<RegisterID> tmp = generator.emitToNumber(generator.tempDestination(dst), srcDst); + emitIncOrDec(generator, srcDst, oper); + return generator.moveToDestinationIfNeeded(dst, tmp.get()); +} + +RegisterID* PostfixNode::emitResolve(BytecodeGenerator& generator, RegisterID* dst) +{ + if (dst == generator.ignoredResult()) + return PrefixNode::emitResolve(generator, dst); + + ASSERT(m_expr->isResolveNode()); + ResolveNode* resolve = static_cast<ResolveNode*>(m_expr); + const Identifier& ident = resolve->identifier(); + + Variable var = generator.variable(ident); + if (RegisterID* local = var.local()) { + generator.emitTDZCheckIfNecessary(var, local, nullptr); + RefPtr<RegisterID> localReg = local; + if (var.isReadOnly()) { + generator.emitReadOnlyExceptionIfNeeded(var); + localReg = generator.emitMove(generator.tempDestination(dst), local); + } + RefPtr<RegisterID> oldValue = emitPostIncOrDec(generator, generator.finalDestination(dst), localReg.get(), m_operator); + generator.emitProfileType(localReg.get(), var, divotStart(), divotEnd()); + return oldValue.get(); + } + + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + RefPtr<RegisterID> scope = generator.emitResolveScope(nullptr, var); + RefPtr<RegisterID> value = generator.emitGetFromScope(generator.newTemporary(), scope.get(), var, ThrowIfNotFound); + generator.emitTDZCheckIfNecessary(var, value.get(), nullptr); + if (var.isReadOnly()) { + bool threwException = generator.emitReadOnlyExceptionIfNeeded(var); + if (threwException) + return value.get(); + } + RefPtr<RegisterID> oldValue = emitPostIncOrDec(generator, generator.finalDestination(dst), value.get(), m_operator); + generator.emitPutToScope(scope.get(), var, value.get(), ThrowIfNotFound); + generator.emitProfileType(value.get(), var, divotStart(), divotEnd()); + + return oldValue.get(); +} + +RegisterID* PostfixNode::emitBracket(BytecodeGenerator& generator, RegisterID* dst) +{ + if (dst == generator.ignoredResult()) + return PrefixNode::emitBracket(generator, dst); + + ASSERT(m_expr->isBracketAccessorNode()); + BracketAccessorNode* bracketAccessor = static_cast<BracketAccessorNode*>(m_expr); + ExpressionNode* baseNode = bracketAccessor->base(); + ExpressionNode* subscript = bracketAccessor->subscript(); + + RefPtr<RegisterID> base = generator.emitNodeForLeftHandSide(baseNode, bracketAccessor->subscriptHasAssignments(), subscript->isPure(generator)); + RefPtr<RegisterID> property = generator.emitNode(subscript); + + generator.emitExpressionInfo(bracketAccessor->divot(), bracketAccessor->divotStart(), bracketAccessor->divotEnd()); + RefPtr<RegisterID> value = generator.emitGetByVal(generator.newTemporary(), base.get(), property.get()); + RegisterID* oldValue = emitPostIncOrDec(generator, generator.tempDestination(dst), value.get(), m_operator); + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + generator.emitPutByVal(base.get(), property.get(), value.get()); + generator.emitProfileType(value.get(), divotStart(), divotEnd()); + return generator.moveToDestinationIfNeeded(dst, oldValue); +} + +RegisterID* PostfixNode::emitDot(BytecodeGenerator& generator, RegisterID* dst) +{ + if (dst == generator.ignoredResult()) + return PrefixNode::emitDot(generator, dst); + + ASSERT(m_expr->isDotAccessorNode()); + DotAccessorNode* dotAccessor = static_cast<DotAccessorNode*>(m_expr); + ExpressionNode* baseNode = dotAccessor->base(); + const Identifier& ident = dotAccessor->identifier(); + + RefPtr<RegisterID> base = generator.emitNode(baseNode); + + generator.emitExpressionInfo(dotAccessor->divot(), dotAccessor->divotStart(), dotAccessor->divotEnd()); + RefPtr<RegisterID> value = generator.emitGetById(generator.newTemporary(), base.get(), ident); + RegisterID* oldValue = emitPostIncOrDec(generator, generator.tempDestination(dst), value.get(), m_operator); + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + generator.emitPutById(base.get(), ident, value.get()); + generator.emitProfileType(value.get(), divotStart(), divotEnd()); + return generator.moveToDestinationIfNeeded(dst, oldValue); +} + +RegisterID* PostfixNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + if (m_expr->isResolveNode()) + return emitResolve(generator, dst); + + if (m_expr->isBracketAccessorNode()) + return emitBracket(generator, dst); + + if (m_expr->isDotAccessorNode()) + return emitDot(generator, dst); + + return emitThrowReferenceError(generator, m_operator == OpPlusPlus + ? ASCIILiteral("Postfix ++ operator applied to value that is not a reference.") + : ASCIILiteral("Postfix -- operator applied to value that is not a reference.")); +} + +// ------------------------------ DeleteResolveNode ----------------------------------- + +RegisterID* DeleteResolveNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + Variable var = generator.variable(m_ident); + if (var.local()) { + generator.emitTDZCheckIfNecessary(var, var.local(), nullptr); + return generator.emitLoad(generator.finalDestination(dst), false); + } + + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + RefPtr<RegisterID> base = generator.emitResolveScope(dst, var); + generator.emitTDZCheckIfNecessary(var, nullptr, base.get()); + return generator.emitDeleteById(generator.finalDestination(dst, base.get()), base.get(), m_ident); +} + +// ------------------------------ DeleteBracketNode ----------------------------------- + +RegisterID* DeleteBracketNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + RefPtr<RegisterID> r0 = generator.emitNode(m_base); + RefPtr<RegisterID> r1 = generator.emitNode(m_subscript); + + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + if (m_base->isSuperNode()) + return emitThrowReferenceError(generator, "Cannot delete a super property"); + return generator.emitDeleteByVal(generator.finalDestination(dst), r0.get(), r1.get()); +} + +// ------------------------------ DeleteDotNode ----------------------------------- + +RegisterID* DeleteDotNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + RefPtr<RegisterID> r0 = generator.emitNode(m_base); + + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + if (m_base->isSuperNode()) + return emitThrowReferenceError(generator, "Cannot delete a super property"); + return generator.emitDeleteById(generator.finalDestination(dst), r0.get(), m_ident); +} + +// ------------------------------ DeleteValueNode ----------------------------------- + +RegisterID* DeleteValueNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + generator.emitNode(generator.ignoredResult(), m_expr); + + // delete on a non-location expression ignores the value and returns true + return generator.emitLoad(generator.finalDestination(dst), true); +} + +// ------------------------------ VoidNode ------------------------------------- + +RegisterID* VoidNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + if (dst == generator.ignoredResult()) { + generator.emitNode(generator.ignoredResult(), m_expr); + return 0; + } + RefPtr<RegisterID> r0 = generator.emitNode(m_expr); + return generator.emitLoad(dst, jsUndefined()); +} + +// ------------------------------ TypeOfResolveNode ----------------------------------- + +RegisterID* TypeOfResolveNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + Variable var = generator.variable(m_ident); + if (RegisterID* local = var.local()) { + generator.emitTDZCheckIfNecessary(var, local, nullptr); + if (dst == generator.ignoredResult()) + return 0; + return generator.emitTypeOf(generator.finalDestination(dst), local); + } + + RefPtr<RegisterID> scope = generator.emitResolveScope(dst, var); + RefPtr<RegisterID> value = generator.emitGetFromScope(generator.newTemporary(), scope.get(), var, DoNotThrowIfNotFound); + generator.emitTDZCheckIfNecessary(var, value.get(), nullptr); + if (dst == generator.ignoredResult()) + return 0; + return generator.emitTypeOf(generator.finalDestination(dst, scope.get()), value.get()); +} + +// ------------------------------ TypeOfValueNode ----------------------------------- + +RegisterID* TypeOfValueNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + if (dst == generator.ignoredResult()) { + generator.emitNode(generator.ignoredResult(), m_expr); + return 0; + } + RefPtr<RegisterID> src = generator.emitNode(m_expr); + return generator.emitTypeOf(generator.finalDestination(dst), src.get()); +} + +// ------------------------------ PrefixNode ---------------------------------- + +RegisterID* PrefixNode::emitResolve(BytecodeGenerator& generator, RegisterID* dst) +{ + ASSERT(m_expr->isResolveNode()); + ResolveNode* resolve = static_cast<ResolveNode*>(m_expr); + const Identifier& ident = resolve->identifier(); + + Variable var = generator.variable(ident); + if (RegisterID* local = var.local()) { + generator.emitTDZCheckIfNecessary(var, local, nullptr); + RefPtr<RegisterID> localReg = local; + if (var.isReadOnly()) { + generator.emitReadOnlyExceptionIfNeeded(var); + localReg = generator.emitMove(generator.tempDestination(dst), localReg.get()); + } else if (generator.vm()->typeProfiler()) { + RefPtr<RegisterID> tempDst = generator.tempDestination(dst); + generator.emitMove(tempDst.get(), localReg.get()); + emitIncOrDec(generator, tempDst.get(), m_operator); + generator.emitMove(localReg.get(), tempDst.get()); + generator.emitProfileType(localReg.get(), var, divotStart(), divotEnd()); + return generator.moveToDestinationIfNeeded(dst, tempDst.get()); + } + emitIncOrDec(generator, localReg.get(), m_operator); + return generator.moveToDestinationIfNeeded(dst, localReg.get()); + } + + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + RefPtr<RegisterID> scope = generator.emitResolveScope(dst, var); + RefPtr<RegisterID> value = generator.emitGetFromScope(generator.newTemporary(), scope.get(), var, ThrowIfNotFound); + generator.emitTDZCheckIfNecessary(var, value.get(), nullptr); + if (var.isReadOnly()) { + bool threwException = generator.emitReadOnlyExceptionIfNeeded(var); + if (threwException) + return value.get(); + } + + emitIncOrDec(generator, value.get(), m_operator); + generator.emitPutToScope(scope.get(), var, value.get(), ThrowIfNotFound); + generator.emitProfileType(value.get(), var, divotStart(), divotEnd()); + return generator.moveToDestinationIfNeeded(dst, value.get()); +} + +RegisterID* PrefixNode::emitBracket(BytecodeGenerator& generator, RegisterID* dst) +{ + ASSERT(m_expr->isBracketAccessorNode()); + BracketAccessorNode* bracketAccessor = static_cast<BracketAccessorNode*>(m_expr); + ExpressionNode* baseNode = bracketAccessor->base(); + ExpressionNode* subscript = bracketAccessor->subscript(); + + RefPtr<RegisterID> base = generator.emitNodeForLeftHandSide(baseNode, bracketAccessor->subscriptHasAssignments(), subscript->isPure(generator)); + RefPtr<RegisterID> property = generator.emitNode(subscript); + RefPtr<RegisterID> propDst = generator.tempDestination(dst); + + generator.emitExpressionInfo(bracketAccessor->divot(), bracketAccessor->divotStart(), bracketAccessor->divotEnd()); + RegisterID* value = generator.emitGetByVal(propDst.get(), base.get(), property.get()); + emitIncOrDec(generator, value, m_operator); + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + generator.emitPutByVal(base.get(), property.get(), value); + generator.emitProfileType(value, divotStart(), divotEnd()); + return generator.moveToDestinationIfNeeded(dst, propDst.get()); +} + +RegisterID* PrefixNode::emitDot(BytecodeGenerator& generator, RegisterID* dst) +{ + ASSERT(m_expr->isDotAccessorNode()); + DotAccessorNode* dotAccessor = static_cast<DotAccessorNode*>(m_expr); + ExpressionNode* baseNode = dotAccessor->base(); + const Identifier& ident = dotAccessor->identifier(); + + RefPtr<RegisterID> base = generator.emitNode(baseNode); + RefPtr<RegisterID> propDst = generator.tempDestination(dst); + + generator.emitExpressionInfo(dotAccessor->divot(), dotAccessor->divotStart(), dotAccessor->divotEnd()); + RegisterID* value = generator.emitGetById(propDst.get(), base.get(), ident); + emitIncOrDec(generator, value, m_operator); + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + generator.emitPutById(base.get(), ident, value); + generator.emitProfileType(value, divotStart(), divotEnd()); + return generator.moveToDestinationIfNeeded(dst, propDst.get()); +} + +RegisterID* PrefixNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + if (m_expr->isResolveNode()) + return emitResolve(generator, dst); + + if (m_expr->isBracketAccessorNode()) + return emitBracket(generator, dst); + + if (m_expr->isDotAccessorNode()) + return emitDot(generator, dst); + + return emitThrowReferenceError(generator, m_operator == OpPlusPlus + ? ASCIILiteral("Prefix ++ operator applied to value that is not a reference.") + : ASCIILiteral("Prefix -- operator applied to value that is not a reference.")); +} + +// ------------------------------ Unary Operation Nodes ----------------------------------- + +RegisterID* UnaryOpNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + RefPtr<RegisterID> src = generator.emitNode(m_expr); + generator.emitExpressionInfo(position(), position(), position()); + return generator.emitUnaryOp(opcodeID(), generator.finalDestination(dst), src.get()); +} + +// ------------------------------ BitwiseNotNode ----------------------------------- + +RegisterID* BitwiseNotNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + RefPtr<RegisterID> src2 = generator.emitLoad(generator.newTemporary(), jsNumber(-1)); + RefPtr<RegisterID> src1 = generator.emitNode(m_expr); + return generator.emitBinaryOp(op_bitxor, generator.finalDestination(dst, src1.get()), src1.get(), src2.get(), OperandTypes(m_expr->resultDescriptor(), ResultType::numberTypeIsInt32())); +} + +// ------------------------------ LogicalNotNode ----------------------------------- + +void LogicalNotNode::emitBytecodeInConditionContext(BytecodeGenerator& generator, Label* trueTarget, Label* falseTarget, FallThroughMode fallThroughMode) +{ + // reverse the true and false targets + generator.emitNodeInConditionContext(expr(), falseTarget, trueTarget, invert(fallThroughMode)); +} + + +// ------------------------------ Binary Operation Nodes ----------------------------------- + +// BinaryOpNode::emitStrcat: +// +// This node generates an op_strcat operation. This opcode can handle concatenation of three or +// more values, where we can determine a set of separate op_add operations would be operating on +// string values. +// +// This function expects to be operating on a graph of AST nodes looking something like this: +// +// (a)... (b) +// \ / +// (+) (c) +// \ / +// [d] ((+)) +// \ / +// [+=] +// +// The assignment operation is optional, if it exists the register holding the value on the +// lefthand side of the assignment should be passing as the optional 'lhs' argument. +// +// The method should be called on the node at the root of the tree of regular binary add +// operations (marked in the diagram with a double set of parentheses). This node must +// be performing a string concatenation (determined by statically detecting that at least +// one child must be a string). +// +// Since the minimum number of values being concatenated together is expected to be 3, if +// a lhs to a concatenating assignment is not provided then the root add should have at +// least one left child that is also an add that can be determined to be operating on strings. +// +RegisterID* BinaryOpNode::emitStrcat(BytecodeGenerator& generator, RegisterID* dst, RegisterID* lhs, ReadModifyResolveNode* emitExpressionInfoForMe) +{ + ASSERT(isAdd()); + ASSERT(resultDescriptor().definitelyIsString()); + + // Create a list of expressions for all the adds in the tree of nodes we can convert into + // a string concatenation. The rightmost node (c) is added first. The rightmost node is + // added first, and the leftmost child is never added, so the vector produced for the + // example above will be [ c, b ]. + Vector<ExpressionNode*, 16> reverseExpressionList; + reverseExpressionList.append(m_expr2); + + // Examine the left child of the add. So long as this is a string add, add its right-child + // to the list, and keep processing along the left fork. + ExpressionNode* leftMostAddChild = m_expr1; + while (leftMostAddChild->isAdd() && leftMostAddChild->resultDescriptor().definitelyIsString()) { + reverseExpressionList.append(static_cast<AddNode*>(leftMostAddChild)->m_expr2); + leftMostAddChild = static_cast<AddNode*>(leftMostAddChild)->m_expr1; + } + + Vector<RefPtr<RegisterID>, 16> temporaryRegisters; + + // If there is an assignment, allocate a temporary to hold the lhs after conversion. + // We could possibly avoid this (the lhs is converted last anyway, we could let the + // op_strcat node handle its conversion if required). + if (lhs) + temporaryRegisters.append(generator.newTemporary()); + + // Emit code for the leftmost node ((a) in the example). + temporaryRegisters.append(generator.newTemporary()); + RegisterID* leftMostAddChildTempRegister = temporaryRegisters.last().get(); + generator.emitNode(leftMostAddChildTempRegister, leftMostAddChild); + + // Note on ordering of conversions: + // + // We maintain the same ordering of conversions as we would see if the concatenations + // was performed as a sequence of adds (otherwise this optimization could change + // behaviour should an object have been provided a valueOf or toString method). + // + // Considering the above example, the sequnce of execution is: + // * evaluate operand (a) + // * evaluate operand (b) + // * convert (a) to primitive <- (this would be triggered by the first add) + // * convert (b) to primitive <- (ditto) + // * evaluate operand (c) + // * convert (c) to primitive <- (this would be triggered by the second add) + // And optionally, if there is an assignment: + // * convert (d) to primitive <- (this would be triggered by the assigning addition) + // + // As such we do not plant an op to convert the leftmost child now. Instead, use + // 'leftMostAddChildTempRegister' as a flag to trigger generation of the conversion + // once the second node has been generated. However, if the leftmost child is an + // immediate we can trivially determine that no conversion will be required. + // If this is the case + if (leftMostAddChild->isString()) + leftMostAddChildTempRegister = 0; + + while (reverseExpressionList.size()) { + ExpressionNode* node = reverseExpressionList.last(); + reverseExpressionList.removeLast(); + + // Emit the code for the current node. + temporaryRegisters.append(generator.newTemporary()); + generator.emitNode(temporaryRegisters.last().get(), node); + + // On the first iteration of this loop, when we first reach this point we have just + // generated the second node, which means it is time to convert the leftmost operand. + if (leftMostAddChildTempRegister) { + generator.emitToPrimitive(leftMostAddChildTempRegister, leftMostAddChildTempRegister); + leftMostAddChildTempRegister = 0; // Only do this once. + } + // Plant a conversion for this node, if necessary. + if (!node->isString()) + generator.emitToPrimitive(temporaryRegisters.last().get(), temporaryRegisters.last().get()); + } + ASSERT(temporaryRegisters.size() >= 3); + + // Certain read-modify nodes require expression info to be emitted *after* m_right has been generated. + // If this is required the node is passed as 'emitExpressionInfoForMe'; do so now. + if (emitExpressionInfoForMe) + generator.emitExpressionInfo(emitExpressionInfoForMe->divot(), emitExpressionInfoForMe->divotStart(), emitExpressionInfoForMe->divotEnd()); + // If there is an assignment convert the lhs now. This will also copy lhs to + // the temporary register we allocated for it. + if (lhs) + generator.emitToPrimitive(temporaryRegisters[0].get(), lhs); + + return generator.emitStrcat(generator.finalDestination(dst, temporaryRegisters[0].get()), temporaryRegisters[0].get(), temporaryRegisters.size()); +} + +void BinaryOpNode::emitBytecodeInConditionContext(BytecodeGenerator& generator, Label* trueTarget, Label* falseTarget, FallThroughMode fallThroughMode) +{ + TriState branchCondition; + ExpressionNode* branchExpression; + tryFoldToBranch(generator, branchCondition, branchExpression); + + if (branchCondition == MixedTriState) + ExpressionNode::emitBytecodeInConditionContext(generator, trueTarget, falseTarget, fallThroughMode); + else if (branchCondition == TrueTriState) + generator.emitNodeInConditionContext(branchExpression, trueTarget, falseTarget, fallThroughMode); + else + generator.emitNodeInConditionContext(branchExpression, falseTarget, trueTarget, invert(fallThroughMode)); +} + +static inline bool canFoldToBranch(OpcodeID opcodeID, ExpressionNode* branchExpression, JSValue constant) +{ + ResultType expressionType = branchExpression->resultDescriptor(); + + if (expressionType.definitelyIsBoolean() && constant.isBoolean()) + return true; + else if (expressionType.definitelyIsBoolean() && constant.isInt32() && (constant.asInt32() == 0 || constant.asInt32() == 1)) + return opcodeID == op_eq || opcodeID == op_neq; // Strict equality is false in the case of type mismatch. + else if (expressionType.isInt32() && constant.isInt32() && constant.asInt32() == 0) + return true; + + return false; +} + +void BinaryOpNode::tryFoldToBranch(BytecodeGenerator& generator, TriState& branchCondition, ExpressionNode*& branchExpression) +{ + branchCondition = MixedTriState; + branchExpression = 0; + + ConstantNode* constant = 0; + if (m_expr1->isConstant()) { + constant = static_cast<ConstantNode*>(m_expr1); + branchExpression = m_expr2; + } else if (m_expr2->isConstant()) { + constant = static_cast<ConstantNode*>(m_expr2); + branchExpression = m_expr1; + } + + if (!constant) + return; + ASSERT(branchExpression); + + OpcodeID opcodeID = this->opcodeID(); + JSValue value = constant->jsValue(generator); + bool canFoldToBranch = JSC::canFoldToBranch(opcodeID, branchExpression, value); + if (!canFoldToBranch) + return; + + if (opcodeID == op_eq || opcodeID == op_stricteq) + branchCondition = triState(value.pureToBoolean()); + else if (opcodeID == op_neq || opcodeID == op_nstricteq) + branchCondition = triState(!value.pureToBoolean()); +} + +RegisterID* BinaryOpNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + OpcodeID opcodeID = this->opcodeID(); + + if (opcodeID == op_add && m_expr1->isAdd() && m_expr1->resultDescriptor().definitelyIsString()) { + generator.emitExpressionInfo(position(), position(), position()); + return emitStrcat(generator, dst); + } + + if (opcodeID == op_neq) { + if (m_expr1->isNull() || m_expr2->isNull()) { + RefPtr<RegisterID> src = generator.tempDestination(dst); + generator.emitNode(src.get(), m_expr1->isNull() ? m_expr2 : m_expr1); + return generator.emitUnaryOp(op_neq_null, generator.finalDestination(dst, src.get()), src.get()); + } + } + + ExpressionNode* left = m_expr1; + ExpressionNode* right = m_expr2; + if (opcodeID == op_neq || opcodeID == op_nstricteq) { + if (left->isString()) + std::swap(left, right); + } + + RefPtr<RegisterID> src1 = generator.emitNodeForLeftHandSide(left, m_rightHasAssignments, right->isPure(generator)); + bool wasTypeof = generator.lastOpcodeID() == op_typeof; + RefPtr<RegisterID> src2 = generator.emitNode(right); + generator.emitExpressionInfo(position(), position(), position()); + if (wasTypeof && (opcodeID == op_neq || opcodeID == op_nstricteq)) { + RefPtr<RegisterID> tmp = generator.tempDestination(dst); + if (opcodeID == op_neq) + generator.emitEqualityOp(op_eq, generator.finalDestination(tmp.get(), src1.get()), src1.get(), src2.get()); + else if (opcodeID == op_nstricteq) + generator.emitEqualityOp(op_stricteq, generator.finalDestination(tmp.get(), src1.get()), src1.get(), src2.get()); + else + RELEASE_ASSERT_NOT_REACHED(); + return generator.emitUnaryOp(op_not, generator.finalDestination(dst, tmp.get()), tmp.get()); + } + RegisterID* result = generator.emitBinaryOp(opcodeID, generator.finalDestination(dst, src1.get()), src1.get(), src2.get(), OperandTypes(left->resultDescriptor(), right->resultDescriptor())); + if (opcodeID == op_urshift && dst != generator.ignoredResult()) + return generator.emitUnaryOp(op_unsigned, result, result); + return result; +} + +RegisterID* EqualNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + if (m_expr1->isNull() || m_expr2->isNull()) { + RefPtr<RegisterID> src = generator.tempDestination(dst); + generator.emitNode(src.get(), m_expr1->isNull() ? m_expr2 : m_expr1); + return generator.emitUnaryOp(op_eq_null, generator.finalDestination(dst, src.get()), src.get()); + } + + ExpressionNode* left = m_expr1; + ExpressionNode* right = m_expr2; + if (left->isString()) + std::swap(left, right); + + RefPtr<RegisterID> src1 = generator.emitNodeForLeftHandSide(left, m_rightHasAssignments, m_expr2->isPure(generator)); + RefPtr<RegisterID> src2 = generator.emitNode(right); + return generator.emitEqualityOp(op_eq, generator.finalDestination(dst, src1.get()), src1.get(), src2.get()); +} + +RegisterID* StrictEqualNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + ExpressionNode* left = m_expr1; + ExpressionNode* right = m_expr2; + if (left->isString()) + std::swap(left, right); + + RefPtr<RegisterID> src1 = generator.emitNodeForLeftHandSide(left, m_rightHasAssignments, m_expr2->isPure(generator)); + RefPtr<RegisterID> src2 = generator.emitNode(right); + return generator.emitEqualityOp(op_stricteq, generator.finalDestination(dst, src1.get()), src1.get(), src2.get()); +} + +RegisterID* ThrowableBinaryOpNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + RefPtr<RegisterID> src1 = generator.emitNodeForLeftHandSide(m_expr1, m_rightHasAssignments, m_expr2->isPure(generator)); + RefPtr<RegisterID> src2 = generator.emitNode(m_expr2); + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + return generator.emitBinaryOp(opcodeID(), generator.finalDestination(dst, src1.get()), src1.get(), src2.get(), OperandTypes(m_expr1->resultDescriptor(), m_expr2->resultDescriptor())); +} + +RegisterID* InstanceOfNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + RefPtr<RegisterID> src1 = generator.emitNodeForLeftHandSide(m_expr1, m_rightHasAssignments, m_expr2->isPure(generator)); + RefPtr<RegisterID> src2 = generator.emitNode(m_expr2); + RefPtr<RegisterID> prototype = generator.newTemporary(); + RefPtr<RegisterID> dstReg = generator.finalDestination(dst, src1.get()); + RefPtr<Label> target = generator.newLabel(); + + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + generator.emitCheckHasInstance(dstReg.get(), src1.get(), src2.get(), target.get()); + + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + generator.emitGetById(prototype.get(), src2.get(), generator.vm()->propertyNames->prototype); + + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + RegisterID* result = generator.emitInstanceOf(dstReg.get(), src1.get(), prototype.get()); + generator.emitLabel(target.get()); + return result; +} + +// ------------------------------ LogicalOpNode ---------------------------- + +RegisterID* LogicalOpNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + RefPtr<RegisterID> temp = generator.tempDestination(dst); + RefPtr<Label> target = generator.newLabel(); + + generator.emitNode(temp.get(), m_expr1); + if (m_operator == OpLogicalAnd) + generator.emitJumpIfFalse(temp.get(), target.get()); + else + generator.emitJumpIfTrue(temp.get(), target.get()); + generator.emitNode(temp.get(), m_expr2); + generator.emitLabel(target.get()); + + return generator.moveToDestinationIfNeeded(dst, temp.get()); +} + +void LogicalOpNode::emitBytecodeInConditionContext(BytecodeGenerator& generator, Label* trueTarget, Label* falseTarget, FallThroughMode fallThroughMode) +{ + RefPtr<Label> afterExpr1 = generator.newLabel(); + if (m_operator == OpLogicalAnd) + generator.emitNodeInConditionContext(m_expr1, afterExpr1.get(), falseTarget, FallThroughMeansTrue); + else + generator.emitNodeInConditionContext(m_expr1, trueTarget, afterExpr1.get(), FallThroughMeansFalse); + generator.emitLabel(afterExpr1.get()); + + generator.emitNodeInConditionContext(m_expr2, trueTarget, falseTarget, fallThroughMode); +} + +// ------------------------------ ConditionalNode ------------------------------ + +RegisterID* ConditionalNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + RefPtr<RegisterID> newDst = generator.finalDestination(dst); + RefPtr<Label> beforeElse = generator.newLabel(); + RefPtr<Label> afterElse = generator.newLabel(); + + RefPtr<Label> beforeThen = generator.newLabel(); + generator.emitNodeInConditionContext(m_logical, beforeThen.get(), beforeElse.get(), FallThroughMeansTrue); + generator.emitLabel(beforeThen.get()); + + generator.emitProfileControlFlow(m_expr1->startOffset()); + generator.emitNode(newDst.get(), m_expr1); + generator.emitJump(afterElse.get()); + + generator.emitLabel(beforeElse.get()); + generator.emitProfileControlFlow(m_expr1->endOffset() + 1); + generator.emitNode(newDst.get(), m_expr2); + + generator.emitLabel(afterElse.get()); + + generator.emitProfileControlFlow(m_expr2->endOffset() + 1); + + return newDst.get(); +} + +// ------------------------------ ReadModifyResolveNode ----------------------------------- + +// FIXME: should this be moved to be a method on BytecodeGenerator? +static ALWAYS_INLINE RegisterID* emitReadModifyAssignment(BytecodeGenerator& generator, RegisterID* dst, RegisterID* src1, ExpressionNode* m_right, Operator oper, OperandTypes types, ReadModifyResolveNode* emitExpressionInfoForMe = 0) +{ + OpcodeID opcodeID; + switch (oper) { + case OpMultEq: + opcodeID = op_mul; + break; + case OpDivEq: + opcodeID = op_div; + break; + case OpPlusEq: + if (m_right->isAdd() && m_right->resultDescriptor().definitelyIsString()) + return static_cast<AddNode*>(m_right)->emitStrcat(generator, dst, src1, emitExpressionInfoForMe); + opcodeID = op_add; + break; + case OpMinusEq: + opcodeID = op_sub; + break; + case OpLShift: + opcodeID = op_lshift; + break; + case OpRShift: + opcodeID = op_rshift; + break; + case OpURShift: + opcodeID = op_urshift; + break; + case OpAndEq: + opcodeID = op_bitand; + break; + case OpXOrEq: + opcodeID = op_bitxor; + break; + case OpOrEq: + opcodeID = op_bitor; + break; + case OpModEq: + opcodeID = op_mod; + break; + default: + RELEASE_ASSERT_NOT_REACHED(); + return dst; + } + + RegisterID* src2 = generator.emitNode(m_right); + + // Certain read-modify nodes require expression info to be emitted *after* m_right has been generated. + // If this is required the node is passed as 'emitExpressionInfoForMe'; do so now. + if (emitExpressionInfoForMe) + generator.emitExpressionInfo(emitExpressionInfoForMe->divot(), emitExpressionInfoForMe->divotStart(), emitExpressionInfoForMe->divotEnd()); + RegisterID* result = generator.emitBinaryOp(opcodeID, dst, src1, src2, types); + if (oper == OpURShift) + return generator.emitUnaryOp(op_unsigned, result, result); + return result; +} + +RegisterID* ReadModifyResolveNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + JSTextPosition newDivot = divotStart() + m_ident.length(); + Variable var = generator.variable(m_ident); + if (RegisterID* local = var.local()) { + generator.emitTDZCheckIfNecessary(var, local, nullptr); + if (var.isReadOnly()) { + generator.emitReadOnlyExceptionIfNeeded(var); + RegisterID* result = emitReadModifyAssignment(generator, generator.finalDestination(dst), local, m_right, m_operator, OperandTypes(ResultType::unknownType(), m_right->resultDescriptor())); + generator.emitProfileType(result, divotStart(), divotEnd()); + return result; + } + + if (generator.leftHandSideNeedsCopy(m_rightHasAssignments, m_right->isPure(generator))) { + RefPtr<RegisterID> result = generator.newTemporary(); + generator.emitMove(result.get(), local); + emitReadModifyAssignment(generator, result.get(), result.get(), m_right, m_operator, OperandTypes(ResultType::unknownType(), m_right->resultDescriptor())); + generator.emitMove(local, result.get()); + generator.invalidateForInContextForLocal(local); + generator.emitProfileType(local, divotStart(), divotEnd()); + return generator.moveToDestinationIfNeeded(dst, result.get()); + } + + RegisterID* result = emitReadModifyAssignment(generator, local, local, m_right, m_operator, OperandTypes(ResultType::unknownType(), m_right->resultDescriptor())); + generator.invalidateForInContextForLocal(local); + generator.emitProfileType(result, divotStart(), divotEnd()); + return generator.moveToDestinationIfNeeded(dst, result); + } + + generator.emitExpressionInfo(newDivot, divotStart(), newDivot); + RefPtr<RegisterID> scope = generator.emitResolveScope(nullptr, var); + RefPtr<RegisterID> value = generator.emitGetFromScope(generator.newTemporary(), scope.get(), var, ThrowIfNotFound); + generator.emitTDZCheckIfNecessary(var, value.get(), nullptr); + if (var.isReadOnly()) { + bool threwException = generator.emitReadOnlyExceptionIfNeeded(var); + if (threwException) + return value.get(); + } + RefPtr<RegisterID> result = emitReadModifyAssignment(generator, generator.finalDestination(dst, value.get()), value.get(), m_right, m_operator, OperandTypes(ResultType::unknownType(), m_right->resultDescriptor()), this); + RegisterID* returnResult = generator.emitPutToScope(scope.get(), var, result.get(), ThrowIfNotFound); + generator.emitProfileType(result.get(), var, divotStart(), divotEnd()); + return returnResult; +} + +// ------------------------------ AssignResolveNode ----------------------------------- + +RegisterID* AssignResolveNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + Variable var = generator.variable(m_ident); + if (RegisterID* local = var.local()) { + RegisterID* result = nullptr; + if (m_assignmentContext == AssignmentContext::AssignmentExpression) + generator.emitTDZCheckIfNecessary(var, local, nullptr); + + if (var.isReadOnly() && m_assignmentContext != AssignmentContext::ConstDeclarationStatement) { + result = generator.emitNode(dst, m_right); // Execute side effects first. + generator.emitReadOnlyExceptionIfNeeded(var); + generator.emitProfileType(result, var, divotStart(), divotEnd()); + } else if (var.isSpecial()) { + RefPtr<RegisterID> tempDst = generator.tempDestination(dst); + generator.emitNode(tempDst.get(), m_right); + generator.emitMove(local, tempDst.get()); + generator.emitProfileType(local, var, divotStart(), divotEnd()); + generator.invalidateForInContextForLocal(local); + result = generator.moveToDestinationIfNeeded(dst, tempDst.get()); + } else { + RegisterID* right = generator.emitNode(local, m_right); + generator.emitProfileType(right, var, divotStart(), divotEnd()); + generator.invalidateForInContextForLocal(local); + result = generator.moveToDestinationIfNeeded(dst, right); + } + + if (m_assignmentContext == AssignmentContext::DeclarationStatement || m_assignmentContext == AssignmentContext::ConstDeclarationStatement) + generator.liftTDZCheckIfPossible(var); + return result; + } + + if (generator.isStrictMode()) + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + RefPtr<RegisterID> scope = generator.emitResolveScope(nullptr, var); + if (m_assignmentContext == AssignmentContext::AssignmentExpression) + generator.emitTDZCheckIfNecessary(var, nullptr, scope.get()); + if (dst == generator.ignoredResult()) + dst = 0; + RefPtr<RegisterID> result = generator.emitNode(dst, m_right); + if (var.isReadOnly() && m_assignmentContext != AssignmentContext::ConstDeclarationStatement) { + RegisterID* result = generator.emitNode(dst, m_right); // Execute side effects first. + bool threwException = generator.emitReadOnlyExceptionIfNeeded(var); + if (threwException) + return result; + } + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + RegisterID* returnResult = generator.emitPutToScope(scope.get(), var, result.get(), generator.isStrictMode() ? ThrowIfNotFound : DoNotThrowIfNotFound); + generator.emitProfileType(result.get(), var, divotStart(), divotEnd()); + + if (m_assignmentContext == AssignmentContext::DeclarationStatement || m_assignmentContext == AssignmentContext::ConstDeclarationStatement) + generator.liftTDZCheckIfPossible(var); + return returnResult; +} + +// ------------------------------ AssignDotNode ----------------------------------- + +RegisterID* AssignDotNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + RefPtr<RegisterID> base = generator.emitNodeForLeftHandSide(m_base, m_rightHasAssignments, m_right->isPure(generator)); + RefPtr<RegisterID> value = generator.destinationForAssignResult(dst); + RefPtr<RegisterID> result = generator.emitNode(value.get(), m_right); + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + RegisterID* forwardResult = (dst == generator.ignoredResult()) ? result.get() : generator.moveToDestinationIfNeeded(generator.tempDestination(result.get()), result.get()); + generator.emitPutById(base.get(), m_ident, forwardResult); + generator.emitProfileType(forwardResult, divotStart(), divotEnd()); + return generator.moveToDestinationIfNeeded(dst, forwardResult); +} + +// ------------------------------ ReadModifyDotNode ----------------------------------- + +RegisterID* ReadModifyDotNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + RefPtr<RegisterID> base = generator.emitNodeForLeftHandSide(m_base, m_rightHasAssignments, m_right->isPure(generator)); + + generator.emitExpressionInfo(subexpressionDivot(), subexpressionStart(), subexpressionEnd()); + RefPtr<RegisterID> value = generator.emitGetById(generator.tempDestination(dst), base.get(), m_ident); + RegisterID* updatedValue = emitReadModifyAssignment(generator, generator.finalDestination(dst, value.get()), value.get(), m_right, static_cast<JSC::Operator>(m_operator), OperandTypes(ResultType::unknownType(), m_right->resultDescriptor())); + + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + RegisterID* ret = generator.emitPutById(base.get(), m_ident, updatedValue); + generator.emitProfileType(updatedValue, divotStart(), divotEnd()); + return ret; +} + +// ------------------------------ AssignErrorNode ----------------------------------- + +RegisterID* AssignErrorNode::emitBytecode(BytecodeGenerator& generator, RegisterID*) +{ + return emitThrowReferenceError(generator, ASCIILiteral("Left side of assignment is not a reference.")); +} + +// ------------------------------ AssignBracketNode ----------------------------------- + +RegisterID* AssignBracketNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + RefPtr<RegisterID> base = generator.emitNodeForLeftHandSide(m_base, m_subscriptHasAssignments || m_rightHasAssignments, m_subscript->isPure(generator) && m_right->isPure(generator)); + RefPtr<RegisterID> property = generator.emitNodeForLeftHandSide(m_subscript, m_rightHasAssignments, m_right->isPure(generator)); + RefPtr<RegisterID> value = generator.destinationForAssignResult(dst); + RefPtr<RegisterID> result = generator.emitNode(value.get(), m_right); + + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + RegisterID* forwardResult = (dst == generator.ignoredResult()) ? result.get() : generator.moveToDestinationIfNeeded(generator.tempDestination(result.get()), result.get()); + + if (m_subscript->isString()) + generator.emitPutById(base.get(), static_cast<StringNode*>(m_subscript)->value(), forwardResult); + else + generator.emitPutByVal(base.get(), property.get(), forwardResult); + + generator.emitProfileType(forwardResult, divotStart(), divotEnd()); + return generator.moveToDestinationIfNeeded(dst, forwardResult); +} + +// ------------------------------ ReadModifyBracketNode ----------------------------------- + +RegisterID* ReadModifyBracketNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + RefPtr<RegisterID> base = generator.emitNodeForLeftHandSide(m_base, m_subscriptHasAssignments || m_rightHasAssignments, m_subscript->isPure(generator) && m_right->isPure(generator)); + RefPtr<RegisterID> property = generator.emitNodeForLeftHandSide(m_subscript, m_rightHasAssignments, m_right->isPure(generator)); + + generator.emitExpressionInfo(subexpressionDivot(), subexpressionStart(), subexpressionEnd()); + RefPtr<RegisterID> value = generator.emitGetByVal(generator.tempDestination(dst), base.get(), property.get()); + RegisterID* updatedValue = emitReadModifyAssignment(generator, generator.finalDestination(dst, value.get()), value.get(), m_right, static_cast<JSC::Operator>(m_operator), OperandTypes(ResultType::unknownType(), m_right->resultDescriptor())); + + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + generator.emitPutByVal(base.get(), property.get(), updatedValue); + generator.emitProfileType(updatedValue, divotStart(), divotEnd()); + + return updatedValue; +} + +// ------------------------------ CommaNode ------------------------------------ + +RegisterID* CommaNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + CommaNode* node = this; + for (; node && node->next(); node = node->next()) + generator.emitNode(generator.ignoredResult(), node->m_expr); + return generator.emitNode(dst, node->m_expr); +} + +// ------------------------------ SourceElements ------------------------------- + + +inline StatementNode* SourceElements::lastStatement() const +{ + return m_tail; +} + +inline void SourceElements::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + for (StatementNode* statement = m_head; statement; statement = statement->next()) + generator.emitNode(dst, statement); +} + +// ------------------------------ BlockNode ------------------------------------ + +inline StatementNode* BlockNode::lastStatement() const +{ + return m_statements ? m_statements->lastStatement() : 0; +} + +StatementNode* BlockNode::singleStatement() const +{ + return m_statements ? m_statements->singleStatement() : 0; +} + +void BlockNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + if (!m_statements) + return; + generator.pushLexicalScope(this, true); + m_statements->emitBytecode(generator, dst); + generator.popLexicalScope(this); +} + +// ------------------------------ EmptyStatementNode --------------------------- + +void EmptyStatementNode::emitBytecode(BytecodeGenerator& generator, RegisterID*) +{ + generator.emitDebugHook(WillExecuteStatement, firstLine(), startOffset(), lineStartOffset()); +} + +// ------------------------------ DebuggerStatementNode --------------------------- + +void DebuggerStatementNode::emitBytecode(BytecodeGenerator& generator, RegisterID*) +{ + generator.emitDebugHook(DidReachBreakpoint, lastLine(), startOffset(), lineStartOffset()); +} + +// ------------------------------ ExprStatementNode ---------------------------- + +void ExprStatementNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + ASSERT(m_expr); + generator.emitDebugHook(WillExecuteStatement, firstLine(), startOffset(), lineStartOffset()); + generator.emitNode(dst, m_expr); +} + +// ------------------------------ DeclarationStatement ---------------------------- + +void DeclarationStatement::emitBytecode(BytecodeGenerator& generator, RegisterID*) +{ + ASSERT(m_expr); + generator.emitDebugHook(WillExecuteStatement, firstLine(), startOffset(), lineStartOffset()); + generator.emitNode(m_expr); +} + +// ------------------------------ EmptyVarExpression ---------------------------- + +RegisterID* EmptyVarExpression::emitBytecode(BytecodeGenerator& generator, RegisterID*) +{ + // It's safe to return null here because this node will always be a child node of DeclarationStatement which ignores our return value. + if (!generator.vm()->typeProfiler()) + return nullptr; + + Variable var = generator.variable(m_ident); + if (RegisterID* local = var.local()) + generator.emitProfileType(local, var, position(), JSTextPosition(-1, position().offset + m_ident.length(), -1)); + else { + RefPtr<RegisterID> scope = generator.emitResolveScope(nullptr, var); + RefPtr<RegisterID> value = generator.emitGetFromScope(generator.newTemporary(), scope.get(), var, DoNotThrowIfNotFound); + generator.emitProfileType(value.get(), var, position(), JSTextPosition(-1, position().offset + m_ident.length(), -1)); + } + + return nullptr; +} + +// ------------------------------ EmptyLetExpression ---------------------------- + +RegisterID* EmptyLetExpression::emitBytecode(BytecodeGenerator& generator, RegisterID*) +{ + // Lexical declarations like 'let' must move undefined into their variables so we don't + // get TDZ errors for situations like this: `let x; x;` + Variable var = generator.variable(m_ident); + if (RegisterID* local = var.local()) { + generator.emitLoad(local, jsUndefined()); + generator.emitProfileType(local, var, position(), JSTextPosition(-1, position().offset + m_ident.length(), -1)); + } else { + RefPtr<RegisterID> scope = generator.emitResolveScope(nullptr, var); + RefPtr<RegisterID> value = generator.emitLoad(nullptr, jsUndefined()); + generator.emitPutToScope(scope.get(), var, value.get(), generator.isStrictMode() ? ThrowIfNotFound : DoNotThrowIfNotFound); + generator.emitProfileType(value.get(), var, position(), JSTextPosition(-1, position().offset + m_ident.length(), -1)); + } + + // It's safe to return null here because this node will always be a child node of DeclarationStatement which ignores our return value. + return nullptr; +} + +// ------------------------------ IfElseNode --------------------------------------- + +static inline StatementNode* singleStatement(StatementNode* statementNode) +{ + if (statementNode->isBlock()) + return static_cast<BlockNode*>(statementNode)->singleStatement(); + return statementNode; +} + +bool IfElseNode::tryFoldBreakAndContinue(BytecodeGenerator& generator, StatementNode* ifBlock, + Label*& trueTarget, FallThroughMode& fallThroughMode) +{ + StatementNode* singleStatement = JSC::singleStatement(ifBlock); + if (!singleStatement) + return false; + + if (singleStatement->isBreak()) { + BreakNode* breakNode = static_cast<BreakNode*>(singleStatement); + Label* target = breakNode->trivialTarget(generator); + if (!target) + return false; + trueTarget = target; + fallThroughMode = FallThroughMeansFalse; + return true; + } + + if (singleStatement->isContinue()) { + ContinueNode* continueNode = static_cast<ContinueNode*>(singleStatement); + Label* target = continueNode->trivialTarget(generator); + if (!target) + return false; + trueTarget = target; + fallThroughMode = FallThroughMeansFalse; + return true; + } + + return false; +} + +void IfElseNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + generator.emitDebugHook(WillExecuteStatement, firstLine(), startOffset(), lineStartOffset()); + + RefPtr<Label> beforeThen = generator.newLabel(); + RefPtr<Label> beforeElse = generator.newLabel(); + RefPtr<Label> afterElse = generator.newLabel(); + + Label* trueTarget = beforeThen.get(); + Label* falseTarget = beforeElse.get(); + FallThroughMode fallThroughMode = FallThroughMeansTrue; + bool didFoldIfBlock = tryFoldBreakAndContinue(generator, m_ifBlock, trueTarget, fallThroughMode); + + generator.emitNodeInConditionContext(m_condition, trueTarget, falseTarget, fallThroughMode); + generator.emitLabel(beforeThen.get()); + generator.emitProfileControlFlow(m_ifBlock->startOffset()); + + if (!didFoldIfBlock) { + generator.emitNode(dst, m_ifBlock); + if (m_elseBlock) + generator.emitJump(afterElse.get()); + } + + generator.emitLabel(beforeElse.get()); + + if (m_elseBlock) { + generator.emitProfileControlFlow(m_ifBlock->endOffset() + (m_ifBlock->isBlock() ? 1 : 0)); + generator.emitNode(dst, m_elseBlock); + } + + generator.emitLabel(afterElse.get()); + StatementNode* endingBlock = m_elseBlock ? m_elseBlock : m_ifBlock; + generator.emitProfileControlFlow(endingBlock->endOffset() + (endingBlock->isBlock() ? 1 : 0)); +} + +// ------------------------------ DoWhileNode ---------------------------------- + +void DoWhileNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + LabelScopePtr scope = generator.newLabelScope(LabelScope::Loop); + + RefPtr<Label> topOfLoop = generator.newLabel(); + generator.emitLabel(topOfLoop.get()); + generator.emitLoopHint(); + generator.emitDebugHook(WillExecuteStatement, lastLine(), startOffset(), lineStartOffset()); + + generator.emitNode(dst, m_statement); + + generator.emitLabel(scope->continueTarget()); + generator.emitDebugHook(WillExecuteStatement, lastLine(), startOffset(), lineStartOffset()); + generator.emitNodeInConditionContext(m_expr, topOfLoop.get(), scope->breakTarget(), FallThroughMeansFalse); + + generator.emitLabel(scope->breakTarget()); +} + +// ------------------------------ WhileNode ------------------------------------ + +void WhileNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + LabelScopePtr scope = generator.newLabelScope(LabelScope::Loop); + RefPtr<Label> topOfLoop = generator.newLabel(); + + generator.emitDebugHook(WillExecuteStatement, m_expr->firstLine(), m_expr->startOffset(), m_expr->lineStartOffset()); + generator.emitNodeInConditionContext(m_expr, topOfLoop.get(), scope->breakTarget(), FallThroughMeansTrue); + + generator.emitLabel(topOfLoop.get()); + generator.emitLoopHint(); + + generator.emitProfileControlFlow(m_statement->startOffset()); + generator.emitNode(dst, m_statement); + + generator.emitLabel(scope->continueTarget()); + generator.emitDebugHook(WillExecuteStatement, firstLine(), startOffset(), lineStartOffset()); + + generator.emitNodeInConditionContext(m_expr, topOfLoop.get(), scope->breakTarget(), FallThroughMeansFalse); + + generator.emitLabel(scope->breakTarget()); + + generator.emitProfileControlFlow(m_statement->endOffset() + (m_statement->isBlock() ? 1 : 0)); +} + +// ------------------------------ ForNode -------------------------------------- + +void ForNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + LabelScopePtr scope = generator.newLabelScope(LabelScope::Loop); + + RegisterID* forLoopSymbolTable = nullptr; + generator.pushLexicalScope(this, true, &forLoopSymbolTable); + + generator.emitDebugHook(WillExecuteStatement, firstLine(), startOffset(), lineStartOffset()); + + if (m_expr1) + generator.emitNode(generator.ignoredResult(), m_expr1); + + RefPtr<Label> topOfLoop = generator.newLabel(); + if (m_expr2) + generator.emitNodeInConditionContext(m_expr2, topOfLoop.get(), scope->breakTarget(), FallThroughMeansTrue); + + generator.emitLabel(topOfLoop.get()); + generator.emitLoopHint(); + generator.emitProfileControlFlow(m_statement->startOffset()); + + generator.emitNode(dst, m_statement); + + generator.emitLabel(scope->continueTarget()); + generator.emitDebugHook(WillExecuteStatement, firstLine(), startOffset(), lineStartOffset()); + generator.prepareLexicalScopeForNextForLoopIteration(this, forLoopSymbolTable); + if (m_expr3) + generator.emitNode(generator.ignoredResult(), m_expr3); + + if (m_expr2) + generator.emitNodeInConditionContext(m_expr2, topOfLoop.get(), scope->breakTarget(), FallThroughMeansFalse); + else + generator.emitJump(topOfLoop.get()); + + generator.emitLabel(scope->breakTarget()); + generator.popLexicalScope(this); + generator.emitProfileControlFlow(m_statement->endOffset() + (m_statement->isBlock() ? 1 : 0)); +} + +// ------------------------------ ForInNode ------------------------------------ + +RegisterID* ForInNode::tryGetBoundLocal(BytecodeGenerator& generator) +{ + if (m_lexpr->isResolveNode()) { + const Identifier& ident = static_cast<ResolveNode*>(m_lexpr)->identifier(); + return generator.variable(ident).local(); + } + + if (m_lexpr->isDestructuringNode()) { + DestructuringAssignmentNode* assignNode = static_cast<DestructuringAssignmentNode*>(m_lexpr); + auto binding = assignNode->bindings(); + if (!binding->isBindingNode()) + return nullptr; + + auto simpleBinding = static_cast<BindingNode*>(binding); + const Identifier& ident = simpleBinding->boundProperty(); + Variable var = generator.variable(ident); + if (var.isSpecial()) + return nullptr; + return var.local(); + } + + return nullptr; +} + +void ForInNode::emitLoopHeader(BytecodeGenerator& generator, RegisterID* propertyName) +{ + if (m_lexpr->isResolveNode()) { + const Identifier& ident = static_cast<ResolveNode*>(m_lexpr)->identifier(); + Variable var = generator.variable(ident); + if (RegisterID* local = var.local()) + generator.emitMove(local, propertyName); + else { + if (generator.isStrictMode()) + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + RegisterID* scope = generator.emitResolveScope(nullptr, var); + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + generator.emitPutToScope(scope, var, propertyName, generator.isStrictMode() ? ThrowIfNotFound : DoNotThrowIfNotFound); + } + generator.emitProfileType(propertyName, var, m_lexpr->position(), JSTextPosition(-1, m_lexpr->position().offset + ident.length(), -1)); + return; + } + if (m_lexpr->isDotAccessorNode()) { + DotAccessorNode* assignNode = static_cast<DotAccessorNode*>(m_lexpr); + const Identifier& ident = assignNode->identifier(); + RegisterID* base = generator.emitNode(assignNode->base()); + generator.emitExpressionInfo(assignNode->divot(), assignNode->divotStart(), assignNode->divotEnd()); + generator.emitPutById(base, ident, propertyName); + generator.emitProfileType(propertyName, assignNode->divotStart(), assignNode->divotEnd()); + return; + } + if (m_lexpr->isBracketAccessorNode()) { + BracketAccessorNode* assignNode = static_cast<BracketAccessorNode*>(m_lexpr); + RefPtr<RegisterID> base = generator.emitNode(assignNode->base()); + RegisterID* subscript = generator.emitNode(assignNode->subscript()); + generator.emitExpressionInfo(assignNode->divot(), assignNode->divotStart(), assignNode->divotEnd()); + generator.emitPutByVal(base.get(), subscript, propertyName); + generator.emitProfileType(propertyName, assignNode->divotStart(), assignNode->divotEnd()); + return; + } + + if (m_lexpr->isDestructuringNode()) { + DestructuringAssignmentNode* assignNode = static_cast<DestructuringAssignmentNode*>(m_lexpr); + auto binding = assignNode->bindings(); + if (!binding->isBindingNode()) { + assignNode->bindings()->bindValue(generator, propertyName); + return; + } + + auto simpleBinding = static_cast<BindingNode*>(binding); + const Identifier& ident = simpleBinding->boundProperty(); + Variable var = generator.variable(ident); + if (!var.local() || var.isSpecial()) { + assignNode->bindings()->bindValue(generator, propertyName); + return; + } + generator.emitMove(var.local(), propertyName); + generator.emitProfileType(propertyName, var, simpleBinding->divotStart(), simpleBinding->divotEnd()); + return; + } + + RELEASE_ASSERT_NOT_REACHED(); +} + +void ForInNode::emitMultiLoopBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + if (!m_lexpr->isAssignmentLocation()) { + emitThrowReferenceError(generator, ASCIILiteral("Left side of for-in statement is not a reference.")); + return; + } + + RefPtr<Label> end = generator.newLabel(); + + RegisterID* forLoopSymbolTable = nullptr; + generator.pushLexicalScope(this, true, &forLoopSymbolTable); + + generator.emitDebugHook(WillExecuteStatement, firstLine(), startOffset(), lineStartOffset()); + + RefPtr<RegisterID> base = generator.newTemporary(); + RefPtr<RegisterID> length; + RefPtr<RegisterID> enumerator; + generator.emitNode(base.get(), m_expr); + RefPtr<RegisterID> local = this->tryGetBoundLocal(generator); + RefPtr<RegisterID> enumeratorIndex; + + int profilerStartOffset = m_statement->startOffset(); + int profilerEndOffset = m_statement->endOffset() + (m_statement->isBlock() ? 1 : 0); + + enumerator = generator.emitGetPropertyEnumerator(generator.newTemporary(), base.get()); + + // Indexed property loop. + { + LabelScopePtr scope = generator.newLabelScope(LabelScope::Loop); + RefPtr<Label> loopStart = generator.newLabel(); + RefPtr<Label> loopEnd = generator.newLabel(); + + length = generator.emitGetEnumerableLength(generator.newTemporary(), enumerator.get()); + RefPtr<RegisterID> i = generator.emitLoad(generator.newTemporary(), jsNumber(0)); + RefPtr<RegisterID> propertyName = generator.newTemporary(); + + generator.emitLabel(loopStart.get()); + generator.emitLoopHint(); + + RefPtr<RegisterID> result = generator.emitEqualityOp(op_less, generator.newTemporary(), i.get(), length.get()); + generator.emitJumpIfFalse(result.get(), loopEnd.get()); + generator.emitHasIndexedProperty(result.get(), base.get(), i.get()); + generator.emitJumpIfFalse(result.get(), scope->continueTarget()); + + generator.emitToIndexString(propertyName.get(), i.get()); + this->emitLoopHeader(generator, propertyName.get()); + + generator.emitProfileControlFlow(profilerStartOffset); + + generator.pushIndexedForInScope(local.get(), i.get()); + generator.emitNode(dst, m_statement); + generator.popIndexedForInScope(local.get()); + + generator.emitProfileControlFlow(profilerEndOffset); + + generator.emitLabel(scope->continueTarget()); + generator.prepareLexicalScopeForNextForLoopIteration(this, forLoopSymbolTable); + generator.emitInc(i.get()); + generator.emitJump(loopStart.get()); + + generator.emitLabel(scope->breakTarget()); + generator.emitJump(end.get()); + generator.emitLabel(loopEnd.get()); + } + + // Structure property loop. + { + LabelScopePtr scope = generator.newLabelScope(LabelScope::Loop); + RefPtr<Label> loopStart = generator.newLabel(); + RefPtr<Label> loopEnd = generator.newLabel(); + + enumeratorIndex = generator.emitLoad(generator.newTemporary(), jsNumber(0)); + RefPtr<RegisterID> propertyName = generator.newTemporary(); + generator.emitEnumeratorStructurePropertyName(propertyName.get(), enumerator.get(), enumeratorIndex.get()); + + generator.emitLabel(loopStart.get()); + generator.emitLoopHint(); + + RefPtr<RegisterID> result = generator.emitUnaryOp(op_eq_null, generator.newTemporary(), propertyName.get()); + generator.emitJumpIfTrue(result.get(), loopEnd.get()); + generator.emitHasStructureProperty(result.get(), base.get(), propertyName.get(), enumerator.get()); + generator.emitJumpIfFalse(result.get(), scope->continueTarget()); + + this->emitLoopHeader(generator, propertyName.get()); + + generator.emitProfileControlFlow(profilerStartOffset); + + generator.pushStructureForInScope(local.get(), enumeratorIndex.get(), propertyName.get(), enumerator.get()); + generator.emitNode(dst, m_statement); + generator.popStructureForInScope(local.get()); + + generator.emitProfileControlFlow(profilerEndOffset); + + generator.emitLabel(scope->continueTarget()); + generator.prepareLexicalScopeForNextForLoopIteration(this, forLoopSymbolTable); + generator.emitInc(enumeratorIndex.get()); + generator.emitEnumeratorStructurePropertyName(propertyName.get(), enumerator.get(), enumeratorIndex.get()); + generator.emitJump(loopStart.get()); + + generator.emitLabel(scope->breakTarget()); + generator.emitJump(end.get()); + generator.emitLabel(loopEnd.get()); + } + + // Generic property loop. + { + LabelScopePtr scope = generator.newLabelScope(LabelScope::Loop); + RefPtr<Label> loopStart = generator.newLabel(); + RefPtr<Label> loopEnd = generator.newLabel(); + + RefPtr<RegisterID> propertyName = generator.newTemporary(); + + generator.emitEnumeratorGenericPropertyName(propertyName.get(), enumerator.get(), enumeratorIndex.get()); + + generator.emitLabel(loopStart.get()); + generator.emitLoopHint(); + + RefPtr<RegisterID> result = generator.emitUnaryOp(op_eq_null, generator.newTemporary(), propertyName.get()); + generator.emitJumpIfTrue(result.get(), loopEnd.get()); + + generator.emitHasGenericProperty(result.get(), base.get(), propertyName.get()); + generator.emitJumpIfFalse(result.get(), scope->continueTarget()); + + this->emitLoopHeader(generator, propertyName.get()); + + generator.emitProfileControlFlow(profilerStartOffset); + + generator.emitNode(dst, m_statement); + + generator.emitLabel(scope->continueTarget()); + generator.prepareLexicalScopeForNextForLoopIteration(this, forLoopSymbolTable); + generator.emitInc(enumeratorIndex.get()); + generator.emitEnumeratorGenericPropertyName(propertyName.get(), enumerator.get(), enumeratorIndex.get()); + generator.emitJump(loopStart.get()); + + generator.emitLabel(scope->breakTarget()); + generator.emitJump(end.get()); + generator.emitLabel(loopEnd.get()); + } + + generator.emitDebugHook(WillExecuteStatement, firstLine(), startOffset(), lineStartOffset()); + generator.emitLabel(end.get()); + generator.popLexicalScope(this); + generator.emitProfileControlFlow(profilerEndOffset); +} + +void ForInNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + this->emitMultiLoopBytecode(generator, dst); +} + +// ------------------------------ ForOfNode ------------------------------------ +void ForOfNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + if (!m_lexpr->isAssignmentLocation()) { + emitThrowReferenceError(generator, ASCIILiteral("Left side of for-of statement is not a reference.")); + return; + } + + RegisterID* forLoopSymbolTable = nullptr; + generator.pushLexicalScope(this, true, &forLoopSymbolTable); + generator.emitDebugHook(WillExecuteStatement, firstLine(), startOffset(), lineStartOffset()); + auto extractor = [this, dst](BytecodeGenerator& generator, RegisterID* value) + { + if (m_lexpr->isResolveNode()) { + const Identifier& ident = static_cast<ResolveNode*>(m_lexpr)->identifier(); + Variable var = generator.variable(ident); + if (RegisterID* local = var.local()) + generator.emitMove(local, value); + else { + if (generator.isStrictMode()) + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + RegisterID* scope = generator.emitResolveScope(nullptr, var); + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + generator.emitPutToScope(scope, var, value, generator.isStrictMode() ? ThrowIfNotFound : DoNotThrowIfNotFound); + } + generator.emitProfileType(value, var, m_lexpr->position(), JSTextPosition(-1, m_lexpr->position().offset + ident.length(), -1)); + } else if (m_lexpr->isDotAccessorNode()) { + DotAccessorNode* assignNode = static_cast<DotAccessorNode*>(m_lexpr); + const Identifier& ident = assignNode->identifier(); + RefPtr<RegisterID> base = generator.emitNode(assignNode->base()); + + generator.emitExpressionInfo(assignNode->divot(), assignNode->divotStart(), assignNode->divotEnd()); + generator.emitPutById(base.get(), ident, value); + generator.emitProfileType(value, assignNode->divotStart(), assignNode->divotEnd()); + } else if (m_lexpr->isBracketAccessorNode()) { + BracketAccessorNode* assignNode = static_cast<BracketAccessorNode*>(m_lexpr); + RefPtr<RegisterID> base = generator.emitNode(assignNode->base()); + RegisterID* subscript = generator.emitNode(assignNode->subscript()); + + generator.emitExpressionInfo(assignNode->divot(), assignNode->divotStart(), assignNode->divotEnd()); + generator.emitPutByVal(base.get(), subscript, value); + generator.emitProfileType(value, assignNode->divotStart(), assignNode->divotEnd()); + } else { + ASSERT(m_lexpr->isDestructuringNode()); + DestructuringAssignmentNode* assignNode = static_cast<DestructuringAssignmentNode*>(m_lexpr); + assignNode->bindings()->bindValue(generator, value); + } + generator.emitProfileControlFlow(m_statement->startOffset()); + generator.emitNode(dst, m_statement); + }; + generator.emitEnumeration(this, m_expr, extractor, this, forLoopSymbolTable); + generator.popLexicalScope(this); + generator.emitProfileControlFlow(m_statement->endOffset() + (m_statement->isBlock() ? 1 : 0)); +} + +// ------------------------------ ContinueNode --------------------------------- + +Label* ContinueNode::trivialTarget(BytecodeGenerator& generator) +{ + if (generator.shouldEmitDebugHooks()) + return 0; + + LabelScopePtr scope = generator.continueTarget(m_ident); + ASSERT(scope); + + if (generator.labelScopeDepth() != scope->scopeDepth()) + return 0; + + return scope->continueTarget(); +} + +void ContinueNode::emitBytecode(BytecodeGenerator& generator, RegisterID*) +{ + generator.emitDebugHook(WillExecuteStatement, firstLine(), startOffset(), lineStartOffset()); + + LabelScopePtr scope = generator.continueTarget(m_ident); + ASSERT(scope); + + generator.emitPopScopes(generator.scopeRegister(), scope->scopeDepth()); + generator.emitJump(scope->continueTarget()); + + generator.emitProfileControlFlow(endOffset()); +} + +// ------------------------------ BreakNode ------------------------------------ + +Label* BreakNode::trivialTarget(BytecodeGenerator& generator) +{ + if (generator.shouldEmitDebugHooks()) + return 0; + + LabelScopePtr scope = generator.breakTarget(m_ident); + ASSERT(scope); + + if (generator.labelScopeDepth() != scope->scopeDepth()) + return 0; + + return scope->breakTarget(); +} + +void BreakNode::emitBytecode(BytecodeGenerator& generator, RegisterID*) +{ + generator.emitDebugHook(WillExecuteStatement, firstLine(), startOffset(), lineStartOffset()); + + LabelScopePtr scope = generator.breakTarget(m_ident); + ASSERT(scope); + + generator.emitPopScopes(generator.scopeRegister(), scope->scopeDepth()); + generator.emitJump(scope->breakTarget()); + + generator.emitProfileControlFlow(endOffset()); +} + +// ------------------------------ ReturnNode ----------------------------------- + +void ReturnNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + generator.emitDebugHook(WillExecuteStatement, firstLine(), startOffset(), lineStartOffset()); + ASSERT(generator.codeType() == FunctionCode); + + if (dst == generator.ignoredResult()) + dst = 0; + + RefPtr<RegisterID> returnRegister = m_value ? generator.emitNode(dst, m_value) : generator.emitLoad(dst, jsUndefined()); + generator.emitProfileType(returnRegister.get(), ProfileTypeBytecodeFunctionReturnStatement, divotStart(), divotEnd()); + if (generator.isInFinallyBlock()) { + returnRegister = generator.emitMove(generator.newTemporary(), returnRegister.get()); + generator.emitPopScopes(generator.scopeRegister(), 0); + } + + generator.emitDebugHook(WillLeaveCallFrame, lastLine(), startOffset(), lineStartOffset()); + generator.emitReturn(returnRegister.get()); + generator.emitProfileControlFlow(endOffset()); + // Emitting an unreachable return here is needed in case this op_profile_control_flow is the + // last opcode in a CodeBlock because a CodeBlock's instructions must end with a terminal opcode. + if (generator.vm()->controlFlowProfiler()) + generator.emitReturn(generator.emitLoad(nullptr, jsUndefined())); +} + +// ------------------------------ WithNode ------------------------------------- + +void WithNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + generator.emitDebugHook(WillExecuteStatement, firstLine(), startOffset(), lineStartOffset()); + + RefPtr<RegisterID> scope = generator.emitNode(m_expr); + generator.emitExpressionInfo(m_divot, m_divot - m_expressionLength, m_divot); + generator.emitPushWithScope(scope.get()); + generator.emitNode(dst, m_statement); + generator.emitPopWithScope(); +} + +// ------------------------------ CaseClauseNode -------------------------------- + +inline void CaseClauseNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + generator.emitProfileControlFlow(m_startOffset); + if (!m_statements) + return; + m_statements->emitBytecode(generator, dst); +} + +// ------------------------------ CaseBlockNode -------------------------------- + +enum SwitchKind { + SwitchUnset = 0, + SwitchNumber = 1, + SwitchString = 2, + SwitchNeither = 3 +}; + +static void processClauseList(ClauseListNode* list, Vector<ExpressionNode*, 8>& literalVector, SwitchKind& typeForTable, bool& singleCharacterSwitch, int32_t& min_num, int32_t& max_num) +{ + for (; list; list = list->getNext()) { + ExpressionNode* clauseExpression = list->getClause()->expr(); + literalVector.append(clauseExpression); + if (clauseExpression->isNumber()) { + double value = static_cast<NumberNode*>(clauseExpression)->value(); + int32_t intVal = static_cast<int32_t>(value); + if ((typeForTable & ~SwitchNumber) || (intVal != value)) { + typeForTable = SwitchNeither; + break; + } + if (intVal < min_num) + min_num = intVal; + if (intVal > max_num) + max_num = intVal; + typeForTable = SwitchNumber; + continue; + } + if (clauseExpression->isString()) { + if (typeForTable & ~SwitchString) { + typeForTable = SwitchNeither; + break; + } + const String& value = static_cast<StringNode*>(clauseExpression)->value().string(); + if (singleCharacterSwitch &= value.length() == 1) { + int32_t intVal = value[0]; + if (intVal < min_num) + min_num = intVal; + if (intVal > max_num) + max_num = intVal; + } + typeForTable = SwitchString; + continue; + } + typeForTable = SwitchNeither; + break; + } +} + +static inline size_t length(ClauseListNode* list1, ClauseListNode* list2) +{ + size_t length = 0; + for (ClauseListNode* node = list1; node; node = node->getNext()) + ++length; + for (ClauseListNode* node = list2; node; node = node->getNext()) + ++length; + return length; +} + +SwitchInfo::SwitchType CaseBlockNode::tryTableSwitch(Vector<ExpressionNode*, 8>& literalVector, int32_t& min_num, int32_t& max_num) +{ + if (length(m_list1, m_list2) < s_tableSwitchMinimum) + return SwitchInfo::SwitchNone; + + SwitchKind typeForTable = SwitchUnset; + bool singleCharacterSwitch = true; + + processClauseList(m_list1, literalVector, typeForTable, singleCharacterSwitch, min_num, max_num); + processClauseList(m_list2, literalVector, typeForTable, singleCharacterSwitch, min_num, max_num); + + if (typeForTable == SwitchUnset || typeForTable == SwitchNeither) + return SwitchInfo::SwitchNone; + + if (typeForTable == SwitchNumber) { + int32_t range = max_num - min_num; + if (min_num <= max_num && range <= 1000 && (range / literalVector.size()) < 10) + return SwitchInfo::SwitchImmediate; + return SwitchInfo::SwitchNone; + } + + ASSERT(typeForTable == SwitchString); + + if (singleCharacterSwitch) { + int32_t range = max_num - min_num; + if (min_num <= max_num && range <= 1000 && (range / literalVector.size()) < 10) + return SwitchInfo::SwitchCharacter; + } + + return SwitchInfo::SwitchString; +} + +void CaseBlockNode::emitBytecodeForBlock(BytecodeGenerator& generator, RegisterID* switchExpression, RegisterID* dst) +{ + RefPtr<Label> defaultLabel; + Vector<RefPtr<Label>, 8> labelVector; + Vector<ExpressionNode*, 8> literalVector; + int32_t min_num = std::numeric_limits<int32_t>::max(); + int32_t max_num = std::numeric_limits<int32_t>::min(); + SwitchInfo::SwitchType switchType = tryTableSwitch(literalVector, min_num, max_num); + + if (switchType != SwitchInfo::SwitchNone) { + // Prepare the various labels + for (uint32_t i = 0; i < literalVector.size(); i++) + labelVector.append(generator.newLabel()); + defaultLabel = generator.newLabel(); + generator.beginSwitch(switchExpression, switchType); + } else { + // Setup jumps + for (ClauseListNode* list = m_list1; list; list = list->getNext()) { + RefPtr<RegisterID> clauseVal = generator.newTemporary(); + generator.emitNode(clauseVal.get(), list->getClause()->expr()); + generator.emitBinaryOp(op_stricteq, clauseVal.get(), clauseVal.get(), switchExpression, OperandTypes()); + labelVector.append(generator.newLabel()); + generator.emitJumpIfTrue(clauseVal.get(), labelVector[labelVector.size() - 1].get()); + } + + for (ClauseListNode* list = m_list2; list; list = list->getNext()) { + RefPtr<RegisterID> clauseVal = generator.newTemporary(); + generator.emitNode(clauseVal.get(), list->getClause()->expr()); + generator.emitBinaryOp(op_stricteq, clauseVal.get(), clauseVal.get(), switchExpression, OperandTypes()); + labelVector.append(generator.newLabel()); + generator.emitJumpIfTrue(clauseVal.get(), labelVector[labelVector.size() - 1].get()); + } + defaultLabel = generator.newLabel(); + generator.emitJump(defaultLabel.get()); + } + + size_t i = 0; + for (ClauseListNode* list = m_list1; list; list = list->getNext()) { + generator.emitLabel(labelVector[i++].get()); + list->getClause()->emitBytecode(generator, dst); + } + + if (m_defaultClause) { + generator.emitLabel(defaultLabel.get()); + m_defaultClause->emitBytecode(generator, dst); + } + + for (ClauseListNode* list = m_list2; list; list = list->getNext()) { + generator.emitLabel(labelVector[i++].get()); + list->getClause()->emitBytecode(generator, dst); + } + if (!m_defaultClause) + generator.emitLabel(defaultLabel.get()); + + ASSERT(i == labelVector.size()); + if (switchType != SwitchInfo::SwitchNone) { + ASSERT(labelVector.size() == literalVector.size()); + generator.endSwitch(labelVector.size(), labelVector.data(), literalVector.data(), defaultLabel.get(), min_num, max_num); + } +} + +// ------------------------------ SwitchNode ----------------------------------- + +void SwitchNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + generator.emitDebugHook(WillExecuteStatement, firstLine(), startOffset(), lineStartOffset()); + + LabelScopePtr scope = generator.newLabelScope(LabelScope::Switch); + + RefPtr<RegisterID> r0 = generator.emitNode(m_expr); + + generator.pushLexicalScope(this, false); + m_block->emitBytecodeForBlock(generator, r0.get(), dst); + generator.popLexicalScope(this); + + generator.emitLabel(scope->breakTarget()); + generator.emitProfileControlFlow(endOffset()); +} + +// ------------------------------ LabelNode ------------------------------------ + +void LabelNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + generator.emitDebugHook(WillExecuteStatement, firstLine(), startOffset(), lineStartOffset()); + + ASSERT(!generator.breakTarget(m_name)); + + LabelScopePtr scope = generator.newLabelScope(LabelScope::NamedLabel, &m_name); + generator.emitNode(dst, m_statement); + + generator.emitLabel(scope->breakTarget()); +} + +// ------------------------------ ThrowNode ------------------------------------ + +void ThrowNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + generator.emitDebugHook(WillExecuteStatement, firstLine(), startOffset(), lineStartOffset()); + + if (dst == generator.ignoredResult()) + dst = 0; + RefPtr<RegisterID> expr = generator.emitNode(m_expr); + generator.emitExpressionInfo(divot(), divotStart(), divotEnd()); + generator.emitThrow(expr.get()); + + generator.emitProfileControlFlow(endOffset()); +} + +// ------------------------------ TryNode -------------------------------------- + +void TryNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + // NOTE: The catch and finally blocks must be labeled explicitly, so the + // optimizer knows they may be jumped to from anywhere. + + generator.emitDebugHook(WillExecuteStatement, firstLine(), startOffset(), lineStartOffset()); + + ASSERT(m_catchBlock || m_finallyBlock); + + RefPtr<Label> tryStartLabel = generator.newLabel(); + generator.emitLabel(tryStartLabel.get()); + + if (m_finallyBlock) + generator.pushFinallyContext(m_finallyBlock); + TryData* tryData = generator.pushTry(tryStartLabel.get()); + + generator.emitNode(dst, m_tryBlock); + + if (m_catchBlock) { + RefPtr<Label> catchEndLabel = generator.newLabel(); + + // Normal path: jump over the catch block. + generator.emitJump(catchEndLabel.get()); + + // Uncaught exception path: the catch block. + RefPtr<Label> here = generator.emitLabel(generator.newLabel().get()); + RefPtr<RegisterID> exceptionRegister = generator.newTemporary(); + RefPtr<RegisterID> thrownValueRegister = generator.newTemporary(); + generator.popTryAndEmitCatch(tryData, exceptionRegister.get(), thrownValueRegister.get(), here.get(), HandlerType::Catch); + + if (m_finallyBlock) { + // If the catch block throws an exception and we have a finally block, then the finally + // block should "catch" that exception. + tryData = generator.pushTry(here.get()); + } + + generator.emitPushCatchScope(m_thrownValueIdent, thrownValueRegister.get(), m_catchEnvironment); + generator.emitProfileControlFlow(m_tryBlock->endOffset() + 1); + generator.emitNode(dst, m_catchBlock); + generator.emitPopCatchScope(m_catchEnvironment); + generator.emitLabel(catchEndLabel.get()); + } + + if (m_finallyBlock) { + RefPtr<Label> preFinallyLabel = generator.emitLabel(generator.newLabel().get()); + + generator.popFinallyContext(); + + RefPtr<Label> finallyEndLabel = generator.newLabel(); + + int finallyStartOffset = m_catchBlock ? m_catchBlock->endOffset() + 1 : m_tryBlock->endOffset() + 1; + + // Normal path: run the finally code, and jump to the end. + generator.emitProfileControlFlow(finallyStartOffset); + generator.emitNode(dst, m_finallyBlock); + generator.emitProfileControlFlow(m_finallyBlock->endOffset() + 1); + generator.emitJump(finallyEndLabel.get()); + + // Uncaught exception path: invoke the finally block, then re-throw the exception. + RefPtr<RegisterID> exceptionRegister = generator.newTemporary(); + RefPtr<RegisterID> thrownValueRegister = generator.newTemporary(); + generator.popTryAndEmitCatch(tryData, exceptionRegister.get(), thrownValueRegister.get(), preFinallyLabel.get(), HandlerType::Finally); + generator.emitProfileControlFlow(finallyStartOffset); + generator.emitNode(dst, m_finallyBlock); + generator.emitThrow(exceptionRegister.get()); + + generator.emitLabel(finallyEndLabel.get()); + generator.emitProfileControlFlow(m_finallyBlock->endOffset() + 1); + } else + generator.emitProfileControlFlow(m_catchBlock->endOffset() + 1); + +} + +// ------------------------------ ScopeNode ----------------------------- + +inline void ScopeNode::emitStatementsBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + if (!m_statements) + return; + m_statements->emitBytecode(generator, dst); +} + +// ------------------------------ ProgramNode ----------------------------- + +void ProgramNode::emitBytecode(BytecodeGenerator& generator, RegisterID*) +{ + generator.emitDebugHook(WillExecuteProgram, startLine(), startStartOffset(), startLineStartOffset()); + + RefPtr<RegisterID> dstRegister = generator.newTemporary(); + generator.emitLoad(dstRegister.get(), jsUndefined()); + generator.emitProfileControlFlow(startStartOffset()); + emitStatementsBytecode(generator, dstRegister.get()); + + generator.emitDebugHook(DidExecuteProgram, lastLine(), startOffset(), lineStartOffset()); + generator.emitEnd(dstRegister.get()); +} + +// ------------------------------ ModuleProgramNode -------------------- + +void ModuleProgramNode::emitBytecode(BytecodeGenerator&, RegisterID*) +{ +} + +// ------------------------------ EvalNode ----------------------------- + +void EvalNode::emitBytecode(BytecodeGenerator& generator, RegisterID*) +{ + generator.emitDebugHook(WillExecuteProgram, startLine(), startStartOffset(), startLineStartOffset()); + + RefPtr<RegisterID> dstRegister = generator.newTemporary(); + generator.emitLoad(dstRegister.get(), jsUndefined()); + emitStatementsBytecode(generator, dstRegister.get()); + + generator.emitDebugHook(DidExecuteProgram, lastLine(), startOffset(), lineStartOffset()); + generator.emitEnd(dstRegister.get()); +} + +// ------------------------------ FunctionNode ----------------------------- + +void FunctionNode::emitBytecode(BytecodeGenerator& generator, RegisterID*) +{ + if (generator.vm()->typeProfiler()) { + for (size_t i = 0; i < m_parameters->size(); i++) { + // Destructuring parameters are handled in destructuring nodes. + if (!m_parameters->at(i).first->isBindingNode()) + continue; + BindingNode* parameter = static_cast<BindingNode*>(m_parameters->at(i).first); + RegisterID reg(CallFrame::argumentOffset(i)); + generator.emitProfileType(®, ProfileTypeBytecodeFunctionArgument, parameter->divotStart(), parameter->divotEnd()); + } + } + + generator.emitProfileControlFlow(startStartOffset()); + generator.emitDebugHook(DidEnterCallFrame, startLine(), startStartOffset(), startLineStartOffset()); + emitStatementsBytecode(generator, generator.ignoredResult()); + + StatementNode* singleStatement = this->singleStatement(); + ReturnNode* returnNode = 0; + + // Check for a return statement at the end of a function composed of a single block. + if (singleStatement && singleStatement->isBlock()) { + StatementNode* lastStatementInBlock = static_cast<BlockNode*>(singleStatement)->lastStatement(); + if (lastStatementInBlock && lastStatementInBlock->isReturnNode()) + returnNode = static_cast<ReturnNode*>(lastStatementInBlock); + } + + // If there is no return we must automatically insert one. + if (!returnNode) { + RegisterID* r0 = generator.isConstructor() ? generator.thisRegister() : generator.emitLoad(0, jsUndefined()); + generator.emitProfileType(r0, ProfileTypeBytecodeFunctionReturnStatement); // Do not emit expression info for this profile because it's not in the user's source code. + ASSERT(startOffset() >= lineStartOffset()); + generator.emitDebugHook(WillLeaveCallFrame, lastLine(), startOffset(), lineStartOffset()); + generator.emitReturn(r0); + return; + } +} + +// ------------------------------ FuncDeclNode --------------------------------- + +void FuncDeclNode::emitBytecode(BytecodeGenerator&, RegisterID*) +{ +} + +// ------------------------------ FuncExprNode --------------------------------- + +RegisterID* FuncExprNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + return generator.emitNewFunctionExpression(generator.finalDestination(dst), this); +} + +#if ENABLE(ES6_CLASS_SYNTAX) +// ------------------------------ ClassDeclNode --------------------------------- + +void ClassDeclNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + generator.emitNode(dst, m_classDeclaration); +} + +// ------------------------------ ClassExprNode --------------------------------- + +RegisterID* ClassExprNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + RefPtr<RegisterID> superclass; + if (m_classHeritage) { + superclass = generator.newTemporary(); + generator.emitNode(superclass.get(), m_classHeritage); + } + + RefPtr<RegisterID> constructor; + + // FIXME: Make the prototype non-configurable & non-writable. + if (m_constructorExpression) + constructor = generator.emitNode(dst, m_constructorExpression); + else { + constructor = generator.emitNewDefaultConstructor(generator.finalDestination(dst), + m_classHeritage ? ConstructorKind::Derived : ConstructorKind::Base, m_name); + } + + const auto& propertyNames = generator.propertyNames(); + RefPtr<RegisterID> prototype = generator.emitNewObject(generator.newTemporary()); + + if (superclass) { + RefPtr<RegisterID> protoParent = generator.newTemporary(); + generator.emitLoad(protoParent.get(), jsNull()); + + RefPtr<RegisterID> tempRegister = generator.newTemporary(); + + // FIXME: Throw TypeError if it's a generator function. + RefPtr<Label> superclassIsUndefinedLabel = generator.newLabel(); + generator.emitJumpIfTrue(generator.emitIsUndefined(tempRegister.get(), superclass.get()), superclassIsUndefinedLabel.get()); + + RefPtr<Label> superclassIsNullLabel = generator.newLabel(); + generator.emitJumpIfTrue(generator.emitUnaryOp(op_eq_null, tempRegister.get(), superclass.get()), superclassIsNullLabel.get()); + + RefPtr<Label> superclassIsObjectLabel = generator.newLabel(); + generator.emitJumpIfTrue(generator.emitIsObject(tempRegister.get(), superclass.get()), superclassIsObjectLabel.get()); + generator.emitLabel(superclassIsUndefinedLabel.get()); + generator.emitThrowTypeError(ASCIILiteral("The superclass is not an object.")); + generator.emitLabel(superclassIsObjectLabel.get()); + generator.emitGetById(protoParent.get(), superclass.get(), generator.propertyNames().prototype); + + RefPtr<Label> protoParentIsObjectOrNullLabel = generator.newLabel(); + generator.emitJumpIfTrue(generator.emitUnaryOp(op_is_object_or_null, tempRegister.get(), protoParent.get()), protoParentIsObjectOrNullLabel.get()); + generator.emitThrowTypeError(ASCIILiteral("The superclass's prototype is not an object.")); + generator.emitLabel(protoParentIsObjectOrNullLabel.get()); + + generator.emitDirectPutById(constructor.get(), generator.propertyNames().underscoreProto, superclass.get(), PropertyNode::Unknown); + generator.emitLabel(superclassIsNullLabel.get()); + generator.emitDirectPutById(prototype.get(), generator.propertyNames().underscoreProto, protoParent.get(), PropertyNode::Unknown); + + emitPutHomeObject(generator, constructor.get(), prototype.get()); + } + + RefPtr<RegisterID> constructorNameRegister = generator.emitLoad(generator.newTemporary(), propertyNames.constructor); + generator.emitCallDefineProperty(prototype.get(), constructorNameRegister.get(), constructor.get(), nullptr, nullptr, + BytecodeGenerator::PropertyConfigurable | BytecodeGenerator::PropertyWritable, m_position); + + RefPtr<RegisterID> prototypeNameRegister = generator.emitLoad(generator.newTemporary(), propertyNames.prototype); + generator.emitCallDefineProperty(constructor.get(), prototypeNameRegister.get(), prototype.get(), nullptr, nullptr, 0, m_position); + + if (m_staticMethods) + generator.emitNode(constructor.get(), m_staticMethods); + + if (m_instanceMethods) + generator.emitNode(prototype.get(), m_instanceMethods); + + return generator.moveToDestinationIfNeeded(dst, constructor.get()); +} +#endif + +// ------------------------------ ImportDeclarationNode ----------------------- + +void ImportDeclarationNode::emitBytecode(BytecodeGenerator&, RegisterID*) +{ +} + +// ------------------------------ ExportAllDeclarationNode -------------------- + +void ExportAllDeclarationNode::emitBytecode(BytecodeGenerator&, RegisterID*) +{ +} + +// ------------------------------ ExportDefaultDeclarationNode ---------------- + +void ExportDefaultDeclarationNode::emitBytecode(BytecodeGenerator&, RegisterID*) +{ +} + +// ------------------------------ ExportLocalDeclarationNode ------------------ + +void ExportLocalDeclarationNode::emitBytecode(BytecodeGenerator&, RegisterID*) +{ +} + +// ------------------------------ ExportNamedDeclarationNode ------------------ + +void ExportNamedDeclarationNode::emitBytecode(BytecodeGenerator&, RegisterID*) +{ +} + +// ------------------------------ DestructuringAssignmentNode ----------------- +RegisterID* DestructuringAssignmentNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) +{ + if (RegisterID* result = m_bindings->emitDirectBinding(generator, dst, m_initializer)) + return result; + RefPtr<RegisterID> initializer = generator.tempDestination(dst); + generator.emitNode(initializer.get(), m_initializer); + m_bindings->bindValue(generator, initializer.get()); + return generator.moveToDestinationIfNeeded(dst, initializer.get()); +} + +static void assignDefaultValueIfUndefined(BytecodeGenerator& generator, RegisterID* maybeUndefined, ExpressionNode* defaultValue) +{ + ASSERT(defaultValue); + RefPtr<Label> isNotUndefined = generator.newLabel(); + generator.emitJumpIfFalse(generator.emitIsUndefined(generator.newTemporary(), maybeUndefined), isNotUndefined.get()); + generator.emitNode(maybeUndefined, defaultValue); + generator.emitLabel(isNotUndefined.get()); +} + +void ArrayPatternNode::bindValue(BytecodeGenerator& generator, RegisterID* rhs) const +{ + RefPtr<RegisterID> iterator = generator.newTemporary(); + { + generator.emitGetById(iterator.get(), rhs, generator.propertyNames().iteratorSymbol); + CallArguments args(generator, nullptr); + generator.emitMove(args.thisRegister(), rhs); + generator.emitCall(iterator.get(), iterator.get(), NoExpectedFunction, args, divot(), divotStart(), divotEnd()); + } + + if (m_targetPatterns.isEmpty()) { + generator.emitIteratorClose(iterator.get(), this); + return; + } + + RefPtr<RegisterID> done; + for (auto& target : m_targetPatterns) { + switch (target.bindingType) { + case BindingType::Elision: + case BindingType::Element: { + RefPtr<Label> iterationSkipped = generator.newLabel(); + if (!done) + done = generator.newTemporary(); + else + generator.emitJumpIfTrue(done.get(), iterationSkipped.get()); + + RefPtr<RegisterID> value = generator.newTemporary(); + generator.emitIteratorNext(value.get(), iterator.get(), this); + generator.emitGetById(done.get(), value.get(), generator.propertyNames().done); + generator.emitJumpIfTrue(done.get(), iterationSkipped.get()); + generator.emitGetById(value.get(), value.get(), generator.propertyNames().value); + + { + RefPtr<Label> valueIsSet = generator.newLabel(); + generator.emitJump(valueIsSet.get()); + generator.emitLabel(iterationSkipped.get()); + generator.emitLoad(value.get(), jsUndefined()); + generator.emitLabel(valueIsSet.get()); + } + + if (target.bindingType == BindingType::Element) { + if (target.defaultValue) + assignDefaultValueIfUndefined(generator, value.get(), target.defaultValue); + target.pattern->bindValue(generator, value.get()); + } + break; + } + + case BindingType::RestElement: { + RefPtr<RegisterID> array = generator.emitNewArray(generator.newTemporary(), 0, 0); + + RefPtr<Label> iterationDone = generator.newLabel(); + if (!done) + done = generator.newTemporary(); + else + generator.emitJumpIfTrue(done.get(), iterationDone.get()); + + RefPtr<RegisterID> index = generator.newTemporary(); + generator.emitLoad(index.get(), jsNumber(0)); + RefPtr<Label> loopStart = generator.newLabel(); + generator.emitLabel(loopStart.get()); + + RefPtr<RegisterID> value = generator.newTemporary(); + generator.emitIteratorNext(value.get(), iterator.get(), this); + generator.emitGetById(done.get(), value.get(), generator.propertyNames().done); + generator.emitJumpIfTrue(done.get(), iterationDone.get()); + generator.emitGetById(value.get(), value.get(), generator.propertyNames().value); + + generator.emitDirectPutByVal(array.get(), index.get(), value.get()); + generator.emitInc(index.get()); + generator.emitJump(loopStart.get()); + + generator.emitLabel(iterationDone.get()); + target.pattern->bindValue(generator, array.get()); + break; + } + } + } + + RefPtr<Label> iteratorClosed = generator.newLabel(); + generator.emitJumpIfTrue(done.get(), iteratorClosed.get()); + generator.emitIteratorClose(iterator.get(), this); + generator.emitLabel(iteratorClosed.get()); +} + +RegisterID* ArrayPatternNode::emitDirectBinding(BytecodeGenerator& generator, RegisterID* dst, ExpressionNode* rhs) +{ + if (!rhs->isSimpleArray()) + return 0; + + RefPtr<RegisterID> resultRegister; + if (dst && dst != generator.ignoredResult()) + resultRegister = generator.emitNewArray(generator.newTemporary(), 0, 0); + ElementNode* elementNodes = static_cast<ArrayNode*>(rhs)->elements(); + Vector<ExpressionNode*> elements; + for (; elementNodes; elementNodes = elementNodes->next()) + elements.append(elementNodes->value()); + if (m_targetPatterns.size() != elements.size()) + return 0; + Vector<RefPtr<RegisterID>> registers; + registers.reserveCapacity(m_targetPatterns.size()); + for (size_t i = 0; i < m_targetPatterns.size(); i++) { + registers.uncheckedAppend(generator.newTemporary()); + generator.emitNode(registers.last().get(), elements[i]); + if (m_targetPatterns[i].defaultValue) + assignDefaultValueIfUndefined(generator, registers.last().get(), m_targetPatterns[i].defaultValue); + if (resultRegister) + generator.emitPutByIndex(resultRegister.get(), i, registers.last().get()); + } + + for (size_t i = 0; i < m_targetPatterns.size(); i++) { + if (m_targetPatterns[i].pattern) + m_targetPatterns[i].pattern->bindValue(generator, registers[i].get()); + } + if (resultRegister) + return generator.moveToDestinationIfNeeded(dst, resultRegister.get()); + return generator.emitLoad(generator.finalDestination(dst), jsUndefined()); +} + +void ArrayPatternNode::toString(StringBuilder& builder) const +{ + builder.append('['); + for (size_t i = 0; i < m_targetPatterns.size(); i++) { + const auto& target = m_targetPatterns[i]; + + switch (target.bindingType) { + case BindingType::Elision: + builder.append(','); + break; + + case BindingType::Element: + target.pattern->toString(builder); + if (i < m_targetPatterns.size() - 1) + builder.append(','); + break; + + case BindingType::RestElement: + builder.append("..."); + target.pattern->toString(builder); + break; + } + } + builder.append(']'); +} + +void ArrayPatternNode::collectBoundIdentifiers(Vector<Identifier>& identifiers) const +{ + for (size_t i = 0; i < m_targetPatterns.size(); i++) { + if (DestructuringPatternNode* node = m_targetPatterns[i].pattern) + node->collectBoundIdentifiers(identifiers); + } +} + +void ObjectPatternNode::toString(StringBuilder& builder) const +{ + builder.append('{'); + for (size_t i = 0; i < m_targetPatterns.size(); i++) { + if (m_targetPatterns[i].wasString) + builder.appendQuotedJSONString(m_targetPatterns[i].propertyName.string()); + else + builder.append(m_targetPatterns[i].propertyName.string()); + builder.append(':'); + m_targetPatterns[i].pattern->toString(builder); + if (i < m_targetPatterns.size() - 1) + builder.append(','); + } + builder.append('}'); +} + +void ObjectPatternNode::bindValue(BytecodeGenerator& generator, RegisterID* rhs) const +{ + for (size_t i = 0; i < m_targetPatterns.size(); i++) { + auto& target = m_targetPatterns[i]; + RefPtr<RegisterID> temp = generator.newTemporary(); + generator.emitGetById(temp.get(), rhs, target.propertyName); + if (target.defaultValue) + assignDefaultValueIfUndefined(generator, temp.get(), target.defaultValue); + target.pattern->bindValue(generator, temp.get()); + } +} + +void ObjectPatternNode::collectBoundIdentifiers(Vector<Identifier>& identifiers) const +{ + for (size_t i = 0; i < m_targetPatterns.size(); i++) + m_targetPatterns[i].pattern->collectBoundIdentifiers(identifiers); +} + +void BindingNode::bindValue(BytecodeGenerator& generator, RegisterID* value) const +{ + Variable var = generator.variable(m_boundProperty); + if (RegisterID* local = var.local()) { + if (m_bindingContext == AssignmentContext::AssignmentExpression) + generator.emitTDZCheckIfNecessary(var, local, nullptr); + if (var.isReadOnly() && m_bindingContext != AssignmentContext::ConstDeclarationStatement) { + bool threwException = generator.emitReadOnlyExceptionIfNeeded(var); + if (threwException) + return; + } + generator.emitMove(local, value); + generator.emitProfileType(local, var, divotStart(), divotEnd()); + if (m_bindingContext == AssignmentContext::DeclarationStatement || m_bindingContext == AssignmentContext::ConstDeclarationStatement) + generator.liftTDZCheckIfPossible(var); + return; + } + if (generator.isStrictMode()) + generator.emitExpressionInfo(divotEnd(), divotStart(), divotEnd()); + RegisterID* scope = generator.emitResolveScope(nullptr, var); + generator.emitExpressionInfo(divotEnd(), divotStart(), divotEnd()); + if (m_bindingContext == AssignmentContext::AssignmentExpression) + generator.emitTDZCheckIfNecessary(var, nullptr, scope); + if (var.isReadOnly() && m_bindingContext != AssignmentContext::ConstDeclarationStatement) { + bool threwException = generator.emitReadOnlyExceptionIfNeeded(var); + if (threwException) + return; + } + generator.emitPutToScope(scope, var, value, generator.isStrictMode() ? ThrowIfNotFound : DoNotThrowIfNotFound); + generator.emitProfileType(value, var, divotStart(), divotEnd()); + if (m_bindingContext == AssignmentContext::DeclarationStatement || m_bindingContext == AssignmentContext::ConstDeclarationStatement) + generator.liftTDZCheckIfPossible(var); + return; +} + +void BindingNode::toString(StringBuilder& builder) const +{ + builder.append(m_boundProperty.string()); +} + +void BindingNode::collectBoundIdentifiers(Vector<Identifier>& identifiers) const +{ + identifiers.append(m_boundProperty); +} + +RegisterID* SpreadExpressionNode::emitBytecode(BytecodeGenerator&, RegisterID*) +{ + RELEASE_ASSERT_NOT_REACHED(); + return 0; +} + +} // namespace JSC diff --git a/Source/JavaScriptCore/bytecompiler/RegisterID.h b/Source/JavaScriptCore/bytecompiler/RegisterID.h new file mode 100644 index 000000000..688c8b9c8 --- /dev/null +++ b/Source/JavaScriptCore/bytecompiler/RegisterID.h @@ -0,0 +1,138 @@ +/* + * Copyright (C) 2008 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef RegisterID_h +#define RegisterID_h + +#include "VirtualRegister.h" + +#include <wtf/Assertions.h> +#include <wtf/VectorTraits.h> + +namespace JSC { + + class RegisterID { + WTF_MAKE_NONCOPYABLE(RegisterID); + public: + RegisterID() + : m_refCount(0) + , m_isTemporary(false) +#ifndef NDEBUG + , m_didSetIndex(false) +#endif + { + } + + RegisterID(VirtualRegister virtualRegister) + : m_refCount(0) + , m_virtualRegister(virtualRegister) + , m_isTemporary(false) +#ifndef NDEBUG + , m_didSetIndex(true) +#endif + { + } + + explicit RegisterID(int index) + : m_refCount(0) + , m_virtualRegister(VirtualRegister(index)) + , m_isTemporary(false) +#ifndef NDEBUG + , m_didSetIndex(true) +#endif + { + } + + void setIndex(int index) + { +#ifndef NDEBUG + m_didSetIndex = true; +#endif + m_virtualRegister = VirtualRegister(index); + } + + void setTemporary() + { + m_isTemporary = true; + } + + int index() const + { + ASSERT(m_didSetIndex); + return m_virtualRegister.offset(); + } + + VirtualRegister virtualRegister() const + { + ASSERT(m_virtualRegister.isValid()); + return m_virtualRegister; + } + + bool isTemporary() + { + return m_isTemporary; + } + + void ref() + { + ++m_refCount; + } + + void deref() + { + --m_refCount; + ASSERT(m_refCount >= 0); + } + + int refCount() const + { + return m_refCount; + } + + private: + + int m_refCount; + VirtualRegister m_virtualRegister; + bool m_isTemporary; +#ifndef NDEBUG + bool m_didSetIndex; +#endif + }; + +} // namespace JSC + +namespace WTF { + + template<> struct VectorTraits<JSC::RegisterID> : VectorTraitsBase<true, JSC::RegisterID> { + static const bool needsInitialization = true; + static const bool canInitializeWithMemset = true; // Default initialization just sets everything to 0 or false, so this is safe. + }; + +} // namespace WTF + +#endif // RegisterID_h diff --git a/Source/JavaScriptCore/bytecompiler/StaticPropertyAnalysis.h b/Source/JavaScriptCore/bytecompiler/StaticPropertyAnalysis.h new file mode 100644 index 000000000..5a9918dd1 --- /dev/null +++ b/Source/JavaScriptCore/bytecompiler/StaticPropertyAnalysis.h @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef StaticPropertyAnalysis_h +#define StaticPropertyAnalysis_h + +#include "Executable.h" +#include "JSGlobalObject.h" +#include <wtf/HashSet.h> + +namespace JSC { + +// Reference count indicates number of live registers that alias this object. +class StaticPropertyAnalysis : public RefCounted<StaticPropertyAnalysis> { +public: + static Ref<StaticPropertyAnalysis> create(Vector<UnlinkedInstruction, 0, UnsafeVectorOverflow>* instructions, unsigned target) + { + return adoptRef(*new StaticPropertyAnalysis(instructions, target)); + } + + void addPropertyIndex(unsigned propertyIndex) { m_propertyIndexes.add(propertyIndex); } + + void record() + { + (*m_instructions)[m_target] = m_propertyIndexes.size(); + } + + int propertyIndexCount() { return m_propertyIndexes.size(); } + +private: + StaticPropertyAnalysis(Vector<UnlinkedInstruction, 0, UnsafeVectorOverflow>* instructions, unsigned target) + : m_instructions(instructions) + , m_target(target) + { + } + + Vector<UnlinkedInstruction, 0, UnsafeVectorOverflow>* m_instructions; + unsigned m_target; + typedef HashSet<unsigned, WTF::IntHash<unsigned>, WTF::UnsignedWithZeroKeyHashTraits<unsigned>> PropertyIndexSet; + PropertyIndexSet m_propertyIndexes; +}; + +} // namespace JSC + +#endif // StaticPropertyAnalysis_h diff --git a/Source/JavaScriptCore/bytecompiler/StaticPropertyAnalyzer.h b/Source/JavaScriptCore/bytecompiler/StaticPropertyAnalyzer.h new file mode 100644 index 000000000..e63fef86a --- /dev/null +++ b/Source/JavaScriptCore/bytecompiler/StaticPropertyAnalyzer.h @@ -0,0 +1,170 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef StaticPropertyAnalyzer_h +#define StaticPropertyAnalyzer_h + +#include "StaticPropertyAnalysis.h" +#include <wtf/HashMap.h> + +namespace JSC { + +// Used for flow-insensitive static analysis of the number of properties assigned to an object. +// We use this analysis with other runtime data to produce an optimization guess. This analysis +// is understood to be lossy, and it's OK if it turns out to be wrong sometimes. +class StaticPropertyAnalyzer { +public: + StaticPropertyAnalyzer(Vector<UnlinkedInstruction, 0, UnsafeVectorOverflow>*); + + void createThis(int dst, unsigned offsetOfInlineCapacityOperand); + void newObject(int dst, unsigned offsetOfInlineCapacityOperand); + void putById(int dst, unsigned propertyIndex); // propertyIndex is an index into a uniqued set of strings. + void mov(int dst, int src); + + void kill(); + void kill(int dst); + +private: + void kill(StaticPropertyAnalysis*); + + Vector<UnlinkedInstruction, 0, UnsafeVectorOverflow>* m_instructions; + typedef HashMap<int, RefPtr<StaticPropertyAnalysis>, WTF::IntHash<int>, WTF::UnsignedWithZeroKeyHashTraits<int>> AnalysisMap; + AnalysisMap m_analyses; +}; + +inline StaticPropertyAnalyzer::StaticPropertyAnalyzer(Vector<UnlinkedInstruction, 0, UnsafeVectorOverflow>* instructions) + : m_instructions(instructions) +{ +} + +inline void StaticPropertyAnalyzer::createThis(int dst, unsigned offsetOfInlineCapacityOperand) +{ + AnalysisMap::AddResult addResult = m_analyses.add( + dst, StaticPropertyAnalysis::create(m_instructions, offsetOfInlineCapacityOperand)); + ASSERT_UNUSED(addResult, addResult.isNewEntry); // Can't have two 'this' in the same constructor. +} + +inline void StaticPropertyAnalyzer::newObject(int dst, unsigned offsetOfInlineCapacityOperand) +{ + RefPtr<StaticPropertyAnalysis> analysis = StaticPropertyAnalysis::create(m_instructions, offsetOfInlineCapacityOperand); + AnalysisMap::AddResult addResult = m_analyses.add(dst, analysis); + if (!addResult.isNewEntry) { + kill(addResult.iterator->value.get()); + addResult.iterator->value = analysis.release(); + } +} + +inline void StaticPropertyAnalyzer::putById(int dst, unsigned propertyIndex) +{ + StaticPropertyAnalysis* analysis = m_analyses.get(dst); + if (!analysis) + return; + analysis->addPropertyIndex(propertyIndex); +} + +inline void StaticPropertyAnalyzer::mov(int dst, int src) +{ + RefPtr<StaticPropertyAnalysis> analysis = m_analyses.get(src); + if (!analysis) { + kill(dst); + return; + } + + AnalysisMap::AddResult addResult = m_analyses.add(dst, analysis); + if (!addResult.isNewEntry) { + kill(addResult.iterator->value.get()); + addResult.iterator->value = analysis.release(); + } +} + +inline void StaticPropertyAnalyzer::kill(StaticPropertyAnalysis* analysis) +{ + if (!analysis) + return; + if (!analysis->hasOneRef()) // Aliases for this object still exist, so it might acquire more properties. + return; + analysis->record(); +} + +inline void StaticPropertyAnalyzer::kill(int dst) +{ + // We observe kills in order to avoid piling on properties to an object after + // its bytecode register has been recycled. + + // Consider these cases: + + // (1) Aliased temporary + // var o1 = { name: name }; + // var o2 = { name: name }; + + // (2) Aliased local -- no control flow + // var local; + // local = new Object; + // local.name = name; + // ... + + // local = lookup(); + // local.didLookup = true; + // ... + + // (3) Aliased local -- control flow + // var local; + // if (condition) + // local = { }; + // else { + // local = new Object; + // } + // local.name = name; + + // (Note: our default codegen for "new Object" looks like case (3).) + + // Case (1) is easy because temporaries almost never survive across control flow. + + // Cases (2) and (3) are hard. Case (2) should kill "local", while case (3) should + // not. There is no great way to solve these cases with simple static analysis. + + // Since this is a simple static analysis, we just try to catch the simplest cases, + // so we accept kills to any registers except for registers that have no inferred + // properties yet. + + AnalysisMap::iterator it = m_analyses.find(dst); + if (it == m_analyses.end()) + return; + if (!it->value->propertyIndexCount()) + return; + + kill(it->value.get()); + m_analyses.remove(it); +} + +inline void StaticPropertyAnalyzer::kill() +{ + while (m_analyses.size()) + kill(m_analyses.take(m_analyses.begin()->key).get()); +} + +} // namespace JSC + +#endif // StaticPropertyAnalyzer_h |