JavaScriptCore Deep Dive 6 - The LLInt Interpreter

Preface

Executing bytecode is one of the core parts of the JavaScriptCore engine, and it is also where most JavaScript-engine optimizations concentrate.

Interpreting and executing JS bytecode is a complex system. After OSR and multiple tiers of JIT were introduced, bytecode execution became increasingly efficient, striking a good balance between low latency and high throughput. Low-latency LLInt interprets bytecode first. When repeated calls, recursion, loops, or other trigger conditions appear, execution can switch through OSR into JIT-based execution. Different JIT tiers may be entered depending on the specific trigger conditions, which improves performance.

CLoopRegister simulates real CPU registers. It defines the following strategies:

  1. How to pack integers smaller than intptr_t into pseudo-registers.
  2. How to hide differences between big-endian and little-endian platforms.
1
2
3
4
5
6
7
8
9
10
11
struct UnlinkedInstruction 
{
UnlinkedInstruction() { u.operand = 0; }
UnlinkedInstruction(OpcodeID opcode) { u.opcode = opcode; }
UnlinkedInstruction(int operand) { u.operand = operand; }
union {
OpcodeID opcode;
int32_t operand;
unsigned index;
} u;
};
1
2
3
4
5
6
7
8
9
struct ProtoCallFrame {
Register codeBlockValue;
Register calleeValue;
Register argCountAndCodeOriginValue;
Register thisArg;
uint32_t paddedArgCount;
bool arityMissMatch;
JSValue *args;
}
1
2
3
4
5
6
JSValue execute(ProgramExecutable*, CallFrame*, JSObject* thisObj);
JSValue execute(EvalExecutable*, CallFrame*, JSValue thisValue, JSScope*);
JSValue execute(ModuleProgramExecutable*, CallFrame*, JSModuleEnvironment*);

JSValue executeCall(CallFrame*, JSObject* function, CallType, const CallData&, JSValue thisValue, const ArgList&);
JSObject* executeConstruct(CallFrame*, JSObject* function, ConstructType, const ConstructData&, const ArgList&, JSValue newTarget);
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
// Elements needed by interpreter execution: executable program, execution stack, and global object.
JSValue Interpreter::execute(ProgramExecutable* program, CallFrame* callFrame, JSObject* thisObj)
{
JSScope* scope = thisObj->globalObject()->globalScope();
VM& vm = *scope->vm();

ASSERT(!vm.exception());
ASSERT(!vm.isCollectorBusy());
RELEASE_ASSERT(vm.currentThreadIsHoldingAPILock());

// It seems execution is not allowed while the garbage collector is busy.
if (vm.isCollectorBusy())
return jsNull();

if (!vm.isSafeToRecurse())
return checkedReturn(throwStackOverflowError(callFrame));

// First check if the "program" is actually just a JSON object. If so,
// we'll handle the JSON object here. Else, we'll handle real JS code
// below at failedJSONP.

Vector<JSONPData> JSONPData;
bool parseResult;

// StringView provides a view over a string. It can observe the string in
// different ways, but it does not allow modification. Because it is read-only,
// it does not really own a copy of the string; it shares storage with it.
StringView programSource = program->source().view();
if (programSource.isNull())
return jsUndefined();

if (programSource.is8Bit()) {
LiteralParser<LChar> literalParser(callFrame, programSource.characters8(), programSource.length(), JSONP);
parseResult = literalParser.tryJSONPParse(JSONPData, scope->globalObject()->globalObjectMethodTable()->supportsRichSourceInfo(scope->globalObject()));
} else {
LiteralParser<UChar> literalParser(callFrame, programSource.characters16(), programSource.length(), JSONP);
parseResult = literalParser.tryJSONPParse(JSONPData, scope->globalObject()->globalObjectMethodTable()->supportsRichSourceInfo(scope->globalObject()));
}

// If parsing succeeds.
if (parseResult) {
// Special handling for JSON.
}
failedJSONP:
// If we get here, then we have already proven that the script is not a JSON object.

VMEntryScope entryScope(vm, scope->globalObject());

// Compile source to bytecode if necessary.

// Initialize global properties.
if (JSObject* error = program->initializeGlobalProperties(vm, callFrame, scope))
return checkedReturn(callFrame->vm().throwException(callFrame, error));

// Prepare for execution.
if (JSObject* error = program->prepareForExecution(callFrame, nullptr, scope, CodeForCall))
return checkedReturn(callFrame->vm().throwException(callFrame, error));

ProgramCodeBlock* codeBlock = program->codeBlock();

if (UNLIKELY(vm.shouldTriggerTermination(callFrame)))
return throwTerminatedExecutionException(callFrame);

if (scope->structure()->isUncacheableDictionary())
scope->flattenDictionaryObject(vm);

ASSERT(codeBlock->numParameters() == 1); // 1 parameter for 'this'.

// Prototype call frame.
ProtoCallFrame protoCallFrame;
protoCallFrame.init(codeBlock, JSCallee::create(vm, scope->globalObject(), scope), thisObj, 1);

// Execute code: generate JIT code first, then execute it.
JSValue result = program->generatedJITCode()->execute(&vm, &protoCallFrame);

return checkedReturn(result);
}

ProgramExecutable

ProgramExecutable can be understood as the manager of the script currently being executed. Its name already tells us that it represents an executable program.

First, it initializes global properties.

The processing results are recorded in callFrame. The main work is done through the JSGlobalObject methods addFunction and addVar, which record the global properties parsed from let, const, and class declarations, as well as global variables declared with var, let, and const.

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
// Initialize global properties.
JSObject* ProgramExecutable::initializeGlobalProperties(VM& vm, CallFrame* callFrame, JSScope* scope)
{
RELEASE_ASSERT(scope);
JSGlobalObject* globalObject = scope->globalObject();
RELEASE_ASSERT(globalObject);
ASSERT(&globalObject->vm() == &vm);

JSObject* exception = 0;

// UnlinkedCodeBlock stores compiled bytecode.
UnlinkedProgramCodeBlock* unlinkedCodeBlock = globalObject->createProgramCodeBlock(callFrame, this, &exception);
if (exception)
return exception;

// Global lexical environment.
JSGlobalLexicalEnvironment* globalLexicalEnvironment = globalObject->globalLexicalEnvironment();

// Declared variables.
const VariableEnvironment& variableDeclarations = unlinkedCodeBlock->variableDeclarations();

// Lexical declarations.
const VariableEnvironment& lexicalDeclarations = unlinkedCodeBlock->lexicalDeclarations();

m_unlinkedProgramCodeBlock.set(vm, this, unlinkedCodeBlock);

BatchedTransitionOptimizer optimizer(vm, globalObject);

// Iterate through functions in the current unlinkedCodeBlock.
for (size_t i = 0, numberOfFunctions = unlinkedCodeBlock->numberOfFunctionDecls(); i < numberOfFunctions; ++i) {
UnlinkedFunctionExecutable* unlinkedFunctionExecutable = unlinkedCodeBlock->functionDecl(i);
ASSERT(!unlinkedFunctionExecutable->name().isEmpty());

// Add the function to the global object.
globalObject->addFunction(callFrame, unlinkedFunctionExecutable->name());

// If the VM collects runtime information or control flow.
if (vm.typeProfiler() || vm.controlFlowProfiler()) {
vm.functionHasExecutedCache()->insertUnexecutedRange(sourceID(),
unlinkedFunctionExecutable->typeProfilingStartOffset(),
unlinkedFunctionExecutable->typeProfilingEndOffset());
}
}

// Iterate through variables declared in the current unlinkedCodeBlock.
for (auto& entry : variableDeclarations) {
ASSERT(entry.value.isVar());
globalObject->addVar(callFrame, Identifier::fromUid(&vm, entry.key.get()));
}

// Handle lexical declarations.
{
JSGlobalLexicalEnvironment* globalLexicalEnvironment = jsCast<JSGlobalLexicalEnvironment*>(globalObject->globalScope());

// Get the global symbol table.
SymbolTable* symbolTable = globalLexicalEnvironment->symbolTable();
ConcurrentJITLocker locker(symbolTable->m_lock);
for (auto& entry : lexicalDeclarations) {
if (UNLIKELY(entry.value.isConst() && !vm.globalConstRedeclarationShouldThrow() && !isStrictMode())) {
if (symbolTable->contains(locker, entry.key.get()))
continue;
}
ScopeOffset offset = symbolTable->takeNextScopeOffset(locker);
SymbolTableEntry newEntry(VarOffset(offset), entry.value.isConst() ? ReadOnly : 0);
newEntry.prepareToWatch();
symbolTable->add(locker, entry.key.get(), newEntry);

ScopeOffset offsetForAssert = globalLexicalEnvironment->addVariables(1, jsTDZValue());
RELEASE_ASSERT(offsetForAssert == offset);
}
}
return 0;
}
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
JSObject* ScriptExecutable::prepareForExecutionImpl(
ExecState* exec, JSFunction* function, JSScope* scope, CodeSpecializationKind kind)
{
VM& vm = exec->vm();
DeferGC deferGC(vm.heap);

if (vm.getAndClearFailNextNewCodeBlock())
return createError(exec->callerFrame(), ASCIILiteral("Forced Failure"));

JSObject* exception = 0;
CodeBlock* codeBlock = newCodeBlockFor(kind, function, scope, exception);
if (!codeBlock) {
RELEASE_ASSERT(exception);
return exception;
}

if (Options::validateBytecode())
codeBlock->validate();

if (Options::useLLInt())
setupLLInt(vm, codeBlock);// Interpretive execution.
else
setupJIT(vm, codeBlock);// JIT-compiled execution.

// Install code.
installCode(*codeBlock->vm(), codeBlock, codeBlock->codeType(), codeBlock->specializationKind());
return 0;
}
-------------本文结束 感谢您的阅读-------------
If this article helped you, your support encourages me to keep writing.

Title:JavaScriptCore Deep Dive 6 - The LLInt Interpreter

Author:lingyun

Published:2018-09-20 00:35

Updated:2026-10-08 00:23

Original link:https://tsuijunxi.github.io/en/2018/09/20/javascriptcore-deep-dive-6-llint-interpreter/

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