Preface
I originally thought two articles would be enough to finish the analysis of bytecode generation. In the end, the length grew too much, so I split the topic into three parts: upper, middle, and lower. This is the final article in the bytecode-generation series.
Note: if some explanations feel unclear, please also read the comments in the code.
ExpressionNode
Continuing from the middle part, this article analyzes
bytecode-generation details for several ExpressionNode
subclasses. Compared with StatementNode,
ExpressionNode involves more detailed bytecode
instructions.
ConstantNode
The bytecode generation for a constant node directly calls
emitLoad and tries to load that constant.
1 | RegisterID* ConstantNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) |
Here emitLoad does not pass the third parameter, because
the default value is SourceCodeRepresentation::Other.
1 | enum class SourceCodeRepresentation {Other,Integer,Double}; |
1 | RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, JSValue v, SourceCodeRepresentation sourceCodeRepresentation) |
emitLoad first calls addConstantValue to
add the constant, then calls emitMove to move the return
value into the destination register.
1 | RegisterID* BytecodeGenerator::addConstantValue(JSValue v, SourceCodeRepresentation sourceCodeRepresentation) |
The implementation of emitMove is very straightforward:
op_mov dst src.
1 | RegisterID* BytecodeGenerator::emitMove(RegisterID* dst, RegisterID* src) |
Now let’s explain FirstConstantRegisterIndex:
1 | static const int FirstConstantRegisterIndex = 0x40000000; |
Register numbers used in bytecode operations have different meanings according to their ranges:
0x80000000-0xFFFFFFFF: negative indices from theCallFramepointer are entries in the call frame. SeeJSStack.h.0x00000000-0x3FFFFFFF: forward indices from theCallFramepointer are local variables and temporaries in the function call frame.0x40000000-0x7FFFFFFF: positive indices from0x40000000specify entries in the constant pool on theCodeBlock.
Clearly, this bytecode generation is closely related to
CodeBlock, so it uses the third range.
ThisNode
The this keyword in JavaScript is rather strange. It
means different things in different contexts. Do you still remember the
first time you were dominated by this?
- In the global environment,
thisalways points to the global object, such aswindow, regardless of strict mode.- Inside a normal function,
thisdiffers between strict and non-strict mode. In non-strict mode, it points to the global object by default. In strict mode, it isundefined.- Inside an object method,
thispoints to the object that calls the method.- Inside a constructor,
thisis bound to the newly created object.- An arrow function does not bind
this; it captures thethisvalue from its defining context.
1 | RegisterID* ThisNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) |
1 | RegisterID* BytecodeGenerator::ensureThis() |
There are two points to explain.
- Because arrow functions do not bind
this, some arrow functions need to loadthisandsuper, especially inside constructors.
In the example below, before calling eval in the
constructor, this needs to be loaded. Although
super represents the constructor of parent class
A, it returns an instance of subclass B; the
this inside super is therefore B.
So super() is equivalent to
A.prototype.constructor.call(this), and this
must be loaded in advance.
1 | var A = class A { |
Temporal Dead Zone: ES6 specifies that if a block containsletorconst, then the variables declared by those commands form a closed scope from the beginning of that block. Using those variables before declaration throws an error. In short, before a variable declared withletis initialized, it is unavailable. This is called the temporal dead zone, or TDZ. Here, before usingthis, JavaScriptCore also needs to check whether the object represented bythisis in a TDZ state.
moveToDestinationIfNeeded is also straightforward, so
there is no need for extra explanation:
1 | // Moves src to dst if dst is not null and is different from src, otherwise just returns src. |
SuperNode
Now let’s look at how bytecode is generated for the
super keyword.
super can only be used inside a class. Calling it
outside a class causes an error because JavaScript has no way to know
which parent constructor it refers to. It is essentially syntactic
sugar. JavaScript inheritance is still prototype-based, and
super is fundamentally a form of constructor borrowing.
A subclass must call super inside its
constructor; otherwise, creating an instance throws an
error. This is because the subclass does not have its own
this object at first. It inherits the parent class’s
this object and then modifies it. Without calling
super, the subclass cannot obtain this.
So SuperNode first needs to figure out what
super points to.
1 | RegisterID* SuperNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) |
The key is emitHomeObjectForCallee:
1 | static RegisterID* emitHomeObjectForCallee(BytecodeGenerator& generator) |
BinaryOpNode
First look at the definition of BinaryOpNode. A binary
operation contains a left expression, a right expression, and an
operator:
1 | m_expr1 m_opcodeID m_expr2 |
1 | class BinaryOpNode : public ExpressionNode { |
1 | RegisterID* BinaryOpNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) |
The bytecode instruction for a binary operation is direct:
1 | RegisterID* BytecodeGenerator::emitBinaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2, OperandTypes types) |
Some bytecode instructions have a length of 5:
1 | { "name" : "op_bitand", "length" : 5 }, |
These length-5 instructions need an additional
OperandTypes value. It represents operand types, such as
whether an operand is an integer, boolean, or string.
1 | static const Type TypeInt32 = 1; |
A unary operation instruction only needs one operator and two operands:
1 | RegisterID* BytecodeGenerator::emitUnaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src) |
EqualNode
EqualNode is a subclass of BinaryOpNode,
and their bytecode-generation ideas are basically the same.
1 | RegisterID* EqualNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) |
The key method is emitEqualityOp, which is responsible
for two kinds of equality checks:
- Whether the values have the same type.
- Whether the values are equal.
1 | RegisterID* BytecodeGenerator::emitEqualityOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2) |
retrieveLastUnaryOp retrieves the two operands from the
last instruction in instructions, then assigns them to
srcIndex and dstIndex.
1 | void BytecodeGenerator::retrieveLastUnaryOp(int& dstIndex, int& srcIndex) |
DotAccessorNode
In JavaScript, method and property access through dot syntax is represented by the dot operator.
1 | class DotAccessorNode : public ExpressionNode, public ThrowableExpressionData |
1 | RegisterID* DotAccessorNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) |
The bytecode detail is worth noting: it includes
op_get_by_id_with_this. Dot access is essentially loading a
property or method name. Also, when loading for the first time, that
property or method may not exist yet, so addConstant is
called to add it.
1 | RegisterID* BytecodeGenerator::emitGetById(RegisterID* dst, RegisterID* base, RegisterID* thisVal, const Identifier& property) |
BracketAccessorNode
1 | class BracketAccessorNode : public ExpressionNode, public ThrowableExpressionData { |
Bracket refers to square brackets. Here
BracketAccessorNode represents an expression in the form
A[B]: m_base is A, and
m_subscript is B.
In JavaScript, bracket notation can be used like this:
1 | var obj= {}; |
1 | RegisterID* BracketAccessorNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) |
In some cases, BracketAccessorNode is very similar to
DotAccessorNode; after all, the two forms can sometimes be
used interchangeably. The final instruction may also become
op_get_by_id_with_this to load a property or method.
But in other cases, BracketAccessorNode accesses by
index, such as with arrays:
1 | var mycars=new Array() |
In that case there is no identifier, only a value, so the final
instruction is op_get_by_val_with_this.
1 | RegisterID* BytecodeGenerator::emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* thisValue, RegisterID* property) |
ClassExprNode
Class-expression nodes in JavaScript are relatively complex.
1 | class ClassExprNode final : public ExpressionNode, public VariableEnvironmentNode |
1 | RegisterID* ClassExprNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) |
The classic ES5 inheritance approach is combination inheritance: use the prototype chain to inherit methods and constructor borrowing to inherit properties.
ES6 is also based on this idea, but it wraps the behavior in a cleaner and more elegant API. It makes JavaScript increasingly powerful, adjusts several property references, standardizes inheritance operations, and separates inheritance implementation from instance construction.
Pay attention to the two lines below:
1 | generator.emitCallDefineProperty(prototype.get(), constructorNameRegister.get(), constructor.get(), nullptr, nullptr, |
They implement JavaScript’s typical combination inheritance, where
Sub inherits from Base:
1 | Sub.prototype = new Base(); |
In ES6, subclass inheritance of parent-class properties is implemented so that when constructing an instance, the subclass obtains its properties directly, without having to look them up on the prototype. ES6 static methods and static properties, which can only be accessed on the constructor, are also implemented through direct class inheritance. Ordinary reusable methods still live on the prototype chain; the principle and implementation are the same as ES5.
1 | // Generate bytecode for static methods. Notice the first parameter is constructor. |
BaseFuncExprNode
1 | class BaseFuncExprNode : public ExpressionNode { |
BaseFuncExprNode has three subclasses:
FuncExprNode, ArrowFuncExprNode, and
MethodDefinitionNode. The emitBytecode
implementations of all three eventually call
emitNewFunctionExpressionCommon.
FuncExprNode
1 | RegisterID* FuncExprNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) |
ArrowFuncExprNode and MethodDefinitionNode
also call emitNewFunctionExpressionCommon eventually, so I
will not repeat the analysis in detail.
ArrowFuncExprNode
1 | RegisterID* ArrowFuncExprNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) |
MethodDefinitionNode
1 | RegisterID* MethodDefinitionNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst) |
The core is here:
1 | void BytecodeGenerator::emitNewFunctionExpressionCommon(RegisterID* dst, FunctionMetadataNode* function) |
The logic is simple. It mainly uses these instructions:
op_new_func_exp, op_new_generator_func_exp,
and op_new_arrow_func_exp.
Summary
The bytecode-generation series has been one of the harder series for me so far. The main difficulties are the large amount of code and the need to understand ES5, ES6, and C++ at the same time.
Because my ability is limited, some parts of the analysis may be incomplete or incorrect. Please do not hesitate to point them out so I can continue improving the series later.