JavaScriptCore Deep Dive 5 - Bytecode Generation, Part 3

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
2
3
4
5
RegisterID* ConstantNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst)
{
if (dst == generator.ignoredResult()) return 0;
return generator.emitLoad(dst, jsValue(generator));
}

Here emitLoad does not pass the third parameter, because the default value is SourceCodeRepresentation::Other.

1
enum class SourceCodeRepresentation {Other,Integer,Double};
1
2
3
4
5
6
RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, JSValue v, SourceCodeRepresentation sourceCodeRepresentation)
{
RegisterID* constantID = addConstantValue(v, sourceCodeRepresentation);
if (dst) return emitMove(dst, constantID);
return constantID;
}

emitLoad first calls addConstantValue to add the constant, then calls emitMove to move the return value into the destination register.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
RegisterID* BytecodeGenerator::addConstantValue(JSValue v, SourceCodeRepresentation sourceCodeRepresentation)
{
if (!v) return addConstantEmptyValue();
// Current offset.
int index = m_nextConstantOffset;
...

EncodedJSValueWithRepresentation valueMapKey { JSValue::encode(v), sourceCodeRepresentation };
JSValueMap::AddResult result = m_jsValueMap.add(valueMapKey, m_nextConstantOffset);

if (result.isNewEntry)
{
// If this is a new entry, add it to m_constantPoolRegisters.
m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
// Increase the offset.
++m_nextConstantOffset;
m_codeBlock->addConstant(v, sourceCodeRepresentation);
}
else
{
// If it already exists, return its index.
index = result.iterator->value;
}
return &m_constantPoolRegisters[index];
}

The implementation of emitMove is very straightforward: op_mov dst src.

1
2
3
4
5
6
7
RegisterID* BytecodeGenerator::emitMove(RegisterID* dst, RegisterID* src)
{
emitOpcode(op_mov);
instructions().append(dst->index());
instructions().append(src->index());
return dst;
}

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 the CallFrame pointer are entries in the call frame. See JSStack.h.
  • 0x00000000-0x3FFFFFFF: forward indices from the CallFrame pointer are local variables and temporaries in the function call frame.
  • 0x40000000-0x7FFFFFFF: positive indices from 0x40000000 specify entries in the constant pool on the CodeBlock.

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, this always points to the global object, such as window, regardless of strict mode.
  • Inside a normal function, this differs between strict and non-strict mode. In non-strict mode, it points to the global object by default. In strict mode, it is undefined.
  • Inside an object method, this points to the object that calls the method.
  • Inside a constructor, this is bound to the newly created object.
  • An arrow function does not bind this; it captures the this value from its defining context.
1
2
3
4
5
6
7
RegisterID* ThisNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst)
{
generator.ensureThis();
if (dst == generator.ignoredResult()) return 0;
RegisterID* result = generator.moveToDestinationIfNeeded(dst, generator.thisRegister());
return result;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
RegisterID* BytecodeGenerator::ensureThis()
{
// If super is used inside an arrow function, this needs to be loaded
// from the arrow-function context.
if (constructorKind() == ConstructorKind::Derived && needsToUpdateArrowFunctionContext() && isSuperCallUsedInInnerArrowFunction())
emitLoadThisFromArrowFunctionLexicalEnvironment();

// Temporal Dead Zone check.
if (constructorKind() == ConstructorKind::Derived || isDerivedConstructorContext())
emitTDZCheck(thisRegister());

return thisRegister();// m_thisRegister
}

There are two points to explain.

  • Because arrow functions do not bind this, some arrow functions need to load this and super, 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
2
3
4
5
6
7
8
9
10
11
12
var A = class A {
constructor () { this.id = 'A'; }
}

var B = class B extend A {
constructor () {
var arrow = () => super();
arrow();
eval("this.id = 'B'");
}
}

  • Temporal Dead Zone: ES6 specifies that if a block contains let or const, 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 with let is initialized, it is unavailable. This is called the temporal dead zone, or TDZ. Here, before using this, JavaScriptCore also needs to check whether the object represented by this is in a TDZ state.

moveToDestinationIfNeeded is also straightforward, so there is no need for extra explanation:

1
2
3
4
5
// 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;
}

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
2
3
4
5
6
7
8
9
10
11
RegisterID* SuperNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst)
{
RegisterID* result = emitSuperBaseForCallee(generator);
return generator.moveToDestinationIfNeeded(generator.finalDestination(dst), result);
}

static RegisterID* emitSuperBaseForCallee(BytecodeGenerator& generator)
{
RefPtr<RegisterID> homeObject = emitHomeObjectForCallee(generator);
return generator.emitGetById(generator.newTemporary(), homeObject.get(), generator.propertyNames().underscoreProto);
}

The key is emitHomeObjectForCallee:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
static RegisterID* emitHomeObjectForCallee(BytecodeGenerator& generator)
{
// In a derived-class context or a derived-constructor context,
// load HomeObject from the derived constructor.
// Here super is used as a function: super().
// Although super represents the constructor of parent class A, it returns
// an instance of subclass B; this inside super therefore points to B.
// So super() is equivalent to A.prototype.constructor.call(this).
if (generator.isDerivedClassContext() || generator.isDerivedConstructorContext()) {
RegisterID* derivedConstructor = generator.emitLoadDerivedConstructorFromArrowFunctionLexicalEnvironment();
return generator.emitGetById(generator.newTemporary(), derivedConstructor, generator.propertyNames().homeObjectPrivateName);
}

// Otherwise, retrieve it from the call frame. In this case super is used
// as an object, and in ordinary methods it points to the parent prototype.
// super.xxx() is equivalent to A.prototype.xxx().
RegisterID callee;
callee.setIndex(dd::Callee);
return generator.emitGetById(generator.newTemporary(), &callee, generator.propertyNames().homeObjectPrivateName);
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
class BinaryOpNode : public ExpressionNode {
public:
RegisterID* emitStrcat(BytecodeGenerator& generator, RegisterID* destination, RegisterID* lhs = 0, ReadModifyResolveNode* emitExpressionInfoForMe = 0);
private:
RegisterID* emitBytecode(BytecodeGenerator&, RegisterID* = 0) override;

protected:
ExpressionNode* m_expr1;
ExpressionNode* m_expr2;
private:
OpcodeID m_opcodeID;
protected:
bool m_rightHasAssignments;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
RegisterID* BinaryOpNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst)
{
OpcodeID opcodeID = this->opcodeID();

// If the operator is + and the left expression result is a string,
// string concatenation should clearly be used.
if (opcodeID == op_add && m_expr1->isAdd() && m_expr1->resultDescriptor().definitelyIsString()) {
generator.emitExpressionInfo(position(), position(), position());
return emitStrcat(generator, dst);
}

// If the operator is != and either expression is null, use op_neq_null
// to test whether the value is not null.
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 the operator is != or !== and the left expression is a string,
// swap the left and right expressions.
if (opcodeID == op_neq || opcodeID == op_nstricteq) {
if (left->isString()) std::swap(left, right);
}

// Generate bytecode for the left expression.
RefPtr<RegisterID> src1 = generator.emitNodeForLeftHandSide(left, m_rightHasAssignments, right->isPure(generator));

// Generate bytecode for the right expression.
RefPtr<RegisterID> src2 = generator.emitNode(right);

...
// Generate bytecode for the binary operation.
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;
}

The bytecode instruction for a binary operation is direct:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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;
}

Some bytecode instructions have a length of 5:

1
2
3
4
5
6
7
{ "name" : "op_bitand", "length" : 5 },
{ "name" : "op_bitxor", "length" : 5 },
{ "name" : "op_bitor", "length" : 5 },
{ "name" : "op_add", "length" : 5 },
{ "name" : "op_mul", "length" : 5 },
{ "name" : "op_div", "length" : 5 },
{ "name" : "op_sub", "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
2
3
4
5
6
7
static const Type TypeInt32 = 1;
static const Type TypeMaybeNumber = 0x04;
static const Type TypeMaybeString = 0x08;
static const Type TypeMaybeNull = 0x10;
static const Type TypeMaybeBool = 0x20;
static const Type TypeMaybeOther = 0x40;
...

A unary operation instruction only needs one operator and two operands:

1
2
3
4
5
6
7
RegisterID* BytecodeGenerator::emitUnaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src)
{
emitOpcode(opcodeID);
instructions().append(dst->index());
instructions().append(src->index());
return dst;
}

EqualNode

EqualNode is a subclass of BinaryOpNode, and their bytecode-generation ideas are basically the same.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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());
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
RegisterID* BytecodeGenerator::emitEqualityOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2)
{
if (m_lastOpcodeID == op_typeof)
{
// Type comparison.
int dstIndex;
int srcIndex;

// Retrieve the two operands from the last instruction in instructions,
// and assign them to srcIndex and dstIndex.
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();
// Since this is a type comparison, specialized instructions are used.
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;
}
}
}

// Ordinary equality-comparison instruction.
emitOpcode(opcodeID);
instructions().append(dst->index());
instructions().append(src1->index());
instructions().append(src2->index());
return dst;
}

retrieveLastUnaryOp retrieves the two operands from the last instruction in instructions, then assigns them to srcIndex and dstIndex.

1
2
3
4
5
6
void BytecodeGenerator::retrieveLastUnaryOp(int& dstIndex, int& srcIndex)
{
size_t size = instructions().size();
dstIndex = instructions().at(size - 2).u.operand;
srcIndex = instructions().at(size - 1).u.operand;
}

DotAccessorNode

In JavaScript, method and property access through dot syntax is represented by the dot operator.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class DotAccessorNode : public ExpressionNode, public ThrowableExpressionData 
{
public:
DotAccessorNode(const JSTokenLocation&, ExpressionNode* base, const Identifier&);

ExpressionNode* base() const { return m_base; }

private:
RegisterID* emitBytecode(BytecodeGenerator&, RegisterID* = 0) override;

bool isLocation() const override { return true; }
bool isDotAccessorNode() const override { return true; }

ExpressionNode* m_base;
const Identifier& m_ident;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
RegisterID* DotAccessorNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst)
{
// Determine whether the dot access is calling a parent-class method.
bool baseIsSuper = m_base->isSuperNode();

// If it is a parent-class method, call emitSuperBaseForCallee to prepare super.
// Otherwise, generate bytecode for m_base.
RefPtr<RegisterID> base = baseIsSuper ? emitSuperBaseForCallee(generator) : generator.emitNode(m_base);

generator.emitExpressionInfo(divot(), divotStart(), divotEnd());

RegisterID* finalDest = generator.finalDestination(dst);
RegisterID* ret;
if (baseIsSuper)
{
// For a parent-class method, emitGetById needs four parameters,
// and this must be determined before the call. This is because
// JavaScript super is syntactic sugar and needs this prepared first.
RefPtr<RegisterID> thisValue = generator.ensureThis();
ret = generator.emitGetById(finalDest, base.get(), thisValue.get(), m_ident);
}
else
{
ret = generator.emitGetById(finalDest, base.get(), m_ident);
}

return ret;
}

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
2
3
4
5
6
7
8
9
RegisterID* BytecodeGenerator::emitGetById(RegisterID* dst, RegisterID* base, RegisterID* thisVal, const Identifier& property)
{
emitOpcode(op_get_by_id_with_this);
instructions().append(kill(dst));
instructions().append(base->index());
instructions().append(thisVal->index());
instructions().append(addConstant(property));
return dst;
}

BracketAccessorNode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class BracketAccessorNode : public ExpressionNode, public ThrowableExpressionData {
public:
BracketAccessorNode(const JSTokenLocation&, ExpressionNode* base, ExpressionNode* subscript, bool subscriptHasAssignments);

ExpressionNode* base() const { return m_base; }
ExpressionNode* subscript() const { return m_subscript; }

bool subscriptHasAssignments() const { return m_subscriptHasAssignments; }

private:
RegisterID* emitBytecode(BytecodeGenerator&, RegisterID* = 0) override;

bool isLocation() const override { return true; }
bool isBracketAccessorNode() const override { return true; }

ExpressionNode* m_base;
ExpressionNode* m_subscript;
bool m_subscriptHasAssignments;
};

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
2
3
4
5
6
var obj= {};  
// Add property name to obj. name is a valid identifier, so obj.name also works.
obj['name'] = 'jack';
// Add property 2a to obj. 2a is not a valid identifier because it starts with a number,
// so obj.2a cannot be used.
obj['2a'] = 'test';
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
RegisterID* BracketAccessorNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst)
{
// If obj happens to point to the current object's prototype, this is a superNode.
if (m_base->isSuperNode())
{
// As before, this and super both need to be prepared.
RefPtr<RegisterID> finalDest = generator.finalDestination(dst);
RefPtr<RegisterID> thisValue = generator.ensureThis();
RefPtr<RegisterID> superBase = emitSuperBaseForCallee(generator);

if (isNonIndexStringElement(*m_subscript)) {
// If subscript is a non-index string, use Identifier as the key.
const Identifier& id = static_cast<StringNode*>(m_subscript)->value();
generator.emitGetById(finalDest.get(), superBase.get(), thisValue.get(), id);
}
else
{
// Otherwise generate bytecode for m_subscript and put the result
// into a register as the key.
RefPtr<RegisterID> subscript = generator.emitNode(m_subscript);
generator.emitGetByVal(finalDest.get(), superBase.get(), thisValue.get(), subscript.get());
}

generator.emitExpressionInfo(divot(), divotStart(), divotEnd());
return finalDest.get();
}

// Similar to the above, except superBase becomes base.
RegisterID* ret;
RefPtr<RegisterID> finalDest = generator.finalDestination(dst);

if (isNonIndexStringElement(*m_subscript)) {
RefPtr<RegisterID> base = generator.emitNode(m_base);
ret = generator.emitGetById(finalDest.get(), 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.get(), base.get(), property);
}

generator.emitExpressionInfo(divot(), divotStart(), divotEnd());
return ret;
}

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
2
3
4
var mycars=new Array()
mycars[0]="Saab"
mycars[1]="Volvo"
mycars[2]="BMW"

In that case there is no identifier, only a value, so the final instruction is op_get_by_val_with_this.

1
2
3
4
5
6
7
8
9
RegisterID* BytecodeGenerator::emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* thisValue, RegisterID* property)
{
emitOpcode(op_get_by_val_with_this);
instructions().append(kill(dst));
instructions().append(base->index());
instructions().append(thisValue->index());
instructions().append(property->index());
return dst;
}

ClassExprNode

Class-expression nodes in JavaScript are relatively complex.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class ClassExprNode final : public ExpressionNode, public VariableEnvironmentNode
{
public:
ClassExprNode(const JSTokenLocation&, const Identifier&, const SourceCode& classSource,
VariableEnvironment& classEnvironment, ExpressionNode* constructorExpresssion,
ExpressionNode* parentClass, PropertyListNode* instanceMethods, PropertyListNode* staticMethods);

private:
RegisterID* emitBytecode(BytecodeGenerator&, RegisterID* = 0) override;

SourceCode m_classSource; // Source code.
const Identifier& m_name; // Class name.
const Identifier* m_ecmaName;// ECMA class name.
ExpressionNode* m_constructorExpression;// Constructor node.
ExpressionNode* m_classHeritage; // Class inheritance expression.
PropertyListNode* m_instanceMethods; // Instance method list.
PropertyListNode* m_staticMethods; // Static method list.
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
RegisterID* ClassExprNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst)
{
if (!m_name.isNull())
generator.pushLexicalScope(this, BytecodeGenerator::TDZCheckOptimization::Optimize, BytecodeGenerator::NestedScopeType::IsNested);

RefPtr<RegisterID> superclass;
if (m_classHeritage) {
// Generate bytecode for the class-inheritance expression.
superclass = generator.newTemporary();
generator.emitNode(superclass.get(), m_classHeritage);
}

RefPtr<RegisterID> constructor;

// FIXME: Make the prototype non-configurable & non-writable.
if (m_constructorExpression)
{
// Set metadata.
FunctionMetadataNode* metadata = static_cast<FuncExprNode*>(m_constructorExpression)->metadata();
metadata->setEcmaName(ecmaName());
metadata->setClassSource(m_classSource);
// Generate bytecode for the constructor.
constructor = generator.emitNode(dst, m_constructorExpression);
}
else
{
// If no constructor is provided, generate bytecode for the default constructor.
constructor = generator.emitNewDefaultConstructor(generator.finalDestination(dst),
m_classHeritage ? ConstructorKind::Derived : ConstructorKind::Base,
m_name, ecmaName(), m_classSource);
}

// Get CommonIdentifiers from the VM. These are essentially identifiers in the VM.
const auto& propertyNames = generator.propertyNames();

// Generate bytecode for creating a new object.
RefPtr<RegisterID> prototype = generator.emitNewObject(generator.newTemporary());

if (superclass)
{
// If inheriting from a parent class.
RefPtr<RegisterID> protoParent = generator.newTemporary();
generator.emitLoad(protoParent.get(), jsNull());

// If the parent class is not defined yet, generate bytecode that jumps
// to the label for an undefined parent class.
RefPtr<RegisterID> tempRegister = generator.newTemporary();
RefPtr<Label> superclassIsUndefinedLabel = generator.newLabel();
generator.emitJumpIfTrue(generator.emitIsUndefined(tempRegister.get(), superclass.get()), superclassIsUndefinedLabel.get());

// If the parent class is null, generate bytecode that jumps to the null label.
RefPtr<Label> superclassIsNullLabel = generator.newLabel();
generator.emitJumpIfTrue(generator.emitUnaryOp(op_eq_null, tempRegister.get(), superclass.get()), superclassIsNullLabel.get());

// If the parent class is an object, also generate a label jump.
RefPtr<Label> superclassIsObjectLabel = generator.newLabel();
generator.emitJumpIfTrue(generator.emitIsObject(tempRegister.get(), superclass.get()), superclassIsObjectLabel.get());

// Backfill labels.
generator.emitLabel(superclassIsUndefinedLabel.get());
generator.emitLabel(superclassIsObjectLabel.get());

// Get the parent prototype.
generator.emitGetById(protoParent.get(), superclass.get(), generator.propertyNames().prototype);

// If the parent prototype is an object or null, another label jump is generated.
RefPtr<Label> protoParentIsObjectOrNullLabel = generator.newLabel();
generator.emitJumpIfTrue(generator.emitUnaryOp(op_is_object_or_null, tempRegister.get(), protoParent.get()), protoParentIsObjectOrNullLabel.get());
generator.emitJumpIfTrue(generator.emitUnaryOp(op_is_function, tempRegister.get(), protoParent.get()), protoParentIsObjectOrNullLabel.get());

// Backfill label.
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());
}

// Generate bytecode for defining the constructor property.
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);

// Generate bytecode for defining the prototype property.
RefPtr<RegisterID> prototypeNameRegister = generator.emitLoad(generator.newTemporary(), propertyNames.prototype);
generator.emitCallDefineProperty(constructor.get(), prototypeNameRegister.get(), prototype.get(), nullptr, nullptr, 0, m_position);

// Generate bytecode for static methods.
if (m_staticMethods)
generator.emitNode(constructor.get(), m_staticMethods);

// Generate bytecode for instance methods.
if (m_instanceMethods)
generator.emitNode(prototype.get(), m_instanceMethods);

if (!m_name.isNull())
{
Variable classNameVar = generator.variable(m_name);
RefPtr<RegisterID> scope = generator.emitResolveScope(nullptr, classNameVar);
generator.emitPutToScope(scope.get(), classNameVar, constructor.get(), ThrowIfNotFound, InitializationMode::Initialization);
generator.popLexicalScope(this);
}

// Return the object generated by the constructor.
return generator.moveToDestinationIfNeeded(dst, constructor.get());
}

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
2
3
4
generator.emitCallDefineProperty(prototype.get(), constructorNameRegister.get(), constructor.get(), nullptr, nullptr,
BytecodeGenerator::PropertyConfigurable | BytecodeGenerator::PropertyWritable, m_position);

generator.emitCallDefineProperty(constructor.get(), prototypeNameRegister.get(), prototype.get(), nullptr, nullptr, 0, m_position);

They implement JavaScript’s typical combination inheritance, where Sub inherits from Base:

1
2
Sub.prototype = new Base();
Sub.prototype.constructor = Sub;

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
2
3
4
5
6
7
// Generate bytecode for static methods. Notice the first parameter is constructor.
if (m_staticMethods)
generator.emitNode(constructor.get(), m_staticMethods);

// Generate bytecode for instance methods. Notice the first parameter is prototype.
if (m_instanceMethods)
generator.emitNode(prototype.get(), m_instanceMethods);

BaseFuncExprNode

1
2
3
4
5
6
7
8
9
class BaseFuncExprNode : public ExpressionNode {
public:
FunctionMetadataNode* metadata() { return m_metadata; }

protected:
BaseFuncExprNode(const JSTokenLocation&, const Identifier&, FunctionMetadataNode*, const SourceCode&, FunctionMode);

FunctionMetadataNode* m_metadata;
};

BaseFuncExprNode has three subclasses: FuncExprNode, ArrowFuncExprNode, and MethodDefinitionNode. The emitBytecode implementations of all three eventually call emitNewFunctionExpressionCommon.

FuncExprNode

1
2
3
4
5
6
7
8
9
10
11
12
RegisterID* FuncExprNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst)
{
// finalDestination: returns the place to write the final output of an operation.
return generator.emitNewFunctionExpression(generator.finalDestination(dst), this);
}

RegisterID* BytecodeGenerator::emitNewFunctionExpression(RegisterID* dst, FuncExprNode* func)
{
emitNewFunctionExpressionCommon(dst, func->metadata());
return dst;
}

ArrowFuncExprNode and MethodDefinitionNode also call emitNewFunctionExpressionCommon eventually, so I will not repeat the analysis in detail.

ArrowFuncExprNode

1
2
3
4
5
6
7
8
9
10
11
RegisterID* ArrowFuncExprNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst)
{
return generator.emitNewArrowFunctionExpression(generator.finalDestination(dst), this);
}

RegisterID* BytecodeGenerator::emitNewArrowFunctionExpression(RegisterID* dst, ArrowFuncExprNode* func)
{
emitNewFunctionExpressionCommon(dst, func->metadata());
return dst;
}

MethodDefinitionNode

1
2
3
4
5
6
7
8
9
10
RegisterID* MethodDefinitionNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst)
{
return generator.emitNewMethodDefinition(generator.finalDestination(dst), this);
}

RegisterID* BytecodeGenerator::emitNewMethodDefinition(RegisterID* dst, MethodDefinitionNode* func)
{
emitNewFunctionExpressionCommon(dst, func->metadata());
return dst;
}

The core is here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
void BytecodeGenerator::emitNewFunctionExpressionCommon(RegisterID* dst, FunctionMetadataNode* function)
{
// Use FunctionMetadataNode to create a function, store it in the m_functionExprs
// container of m_codeBlock, and return its index.
unsigned index = m_codeBlock->addFunctionExpr(makeFunction(function));

// Default value.
OpcodeID opcodeID = op_new_func_exp;
switch (function->parseMode())
{
// Closure.
case SourceParseMode::GeneratorWrapperFunctionMode: {
opcodeID = op_new_generator_func_exp;
break;
}
// Arrow function.
case SourceParseMode::ArrowFunctionMode: {
opcodeID = op_new_arrow_func_exp;
break;
}
default: {
break;
}
}

// op_new_func_exp/op_new_generator_func_exp/op_new_arrow_func_exp have length 4.
emitOpcode(opcodeID);
instructions().append(dst->index());
instructions().append(scopeRegister()->index());
instructions().append(index);
}

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.

-------------本文结束 感谢您的阅读-------------
If this article helped you, your support encourages me to keep writing.

Title:JavaScriptCore Deep Dive 5 - Bytecode Generation, Part 3

Author:lingyun

Published:2018-09-15 00:34

Updated:2026-10-07 00:00

Original link:https://tsuijunxi.github.io/en/2018/09/15/javascriptcore-deep-dive-5-bytecode-generation-part-3/

License: Attribution-NonCommercial-NoDerivatives 4.0 International Please keep the original link and author when sharing.