v8
V8 is Google’s open source high-performance JavaScript and WebAssembly engine, written in C++.
Loading...
Searching...
No Matches
module-compiler.h
Go to the documentation of this file.
1// Copyright 2017 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef V8_WASM_MODULE_COMPILER_H_
6#define V8_WASM_MODULE_COMPILER_H_
7
8#if !V8_ENABLE_WEBASSEMBLY
9#error This header should only be included if WebAssembly is enabled.
10#endif // !V8_ENABLE_WEBASSEMBLY
11
12#include <atomic>
13#include <functional>
14#include <memory>
15#include <optional>
16
17#include "include/v8-metrics.h"
19#include "src/common/globals.h"
25
26namespace v8 {
27
28namespace base {
29template <typename T>
30class Vector;
31} // namespace base
32
33namespace internal {
34
35class JSArrayBuffer;
36class JSPromise;
37class Counters;
38class WasmModuleObject;
39class WasmInstanceObject;
41
42namespace wasm {
43
44struct CompilationEnv;
45class CompilationResultResolver;
46class ErrorThrower;
47class ModuleCompiler;
48class NativeModule;
49class ProfileInformation;
50class StreamingDecoder;
51class WasmCode;
52struct WasmModule;
53
55std::shared_ptr<NativeModule> CompileToNativeModule(
56 Isolate* isolate, WasmEnabledFeatures enabled_features,
57 WasmDetectedFeatures detected_features, CompileTimeImports compile_imports,
58 ErrorThrower* thrower, std::shared_ptr<const WasmModule> module,
59 base::OwnedVector<const uint8_t> wire_bytes, int compilation_id,
60 v8::metrics::Recorder::ContextId context_id, ProfileInformation* pgo_info);
61
63 const WasmModule* module, base::Vector<const uint8_t> wire_bytes,
64 const CompileTimeImports& imports, WasmDetectedFeatures* detected);
65
66// Compiles the wrapper for this (kind, sig) pair and sets the corresponding
67// cache entry. Assumes the key already exists in the cache but has not been
68// compiled yet.
70WasmCode* CompileImportWrapperForTest(Isolate* isolate,
71 NativeModule* native_module,
73 const CanonicalSig* sig,
74 CanonicalTypeIndex type_index,
75 int expected_arity, Suspend suspend);
76
77// Triggered by the WasmCompileLazy builtin. The return value indicates whether
78// compilation was successful. Lazy compilation can fail only if validation is
79// also lazy.
80bool CompileLazy(Isolate*, Tagged<WasmTrustedInstanceData>, int func_index);
81
82// Throws the compilation error after failed lazy compilation.
83void ThrowLazyCompilationError(Isolate* isolate,
84 const NativeModule* native_module,
85 int func_index);
86
87// Trigger tier-up of a particular function to TurboFan. If tier-up was already
88// triggered, we instead increase the priority with exponential back-off.
90 int func_index);
91// Synchronous version of the above.
94 int func_index);
95// Same, but all functions.
98
100 NativeModule* native_module);
101
102// Publish a set of detected features in a given isolate. If this is the initial
103// compilation, also the "kWasmModuleCompilation" use counter is incremented to
104// serve as a baseline for the other detected features.
105void PublishDetectedFeatures(WasmDetectedFeatures, Isolate*,
106 bool is_initial_compilation);
107
108// Encapsulates all the state and steps of an asynchronous compilation.
109// An asynchronous compile job consists of a number of tasks that are executed
110// as foreground and background tasks. Any phase that touches the V8 heap or
111// allocates on the V8 heap (e.g. creating the module object) must be a
112// foreground task. All other tasks (e.g. decoding and validating, the majority
113// of the work of compilation) can be background tasks.
114// TODO(wasm): factor out common parts of this with the synchronous pipeline.
116 public:
117 AsyncCompileJob(Isolate* isolate, WasmEnabledFeatures enabled_features,
118 CompileTimeImports compile_imports,
120 DirectHandle<Context> context,
121 DirectHandle<NativeContext> incumbent_context,
122 const char* api_method_name,
123 std::shared_ptr<CompilationResultResolver> resolver,
124 int compilation_id);
126
127 void Start();
128
129 std::shared_ptr<StreamingDecoder> CreateStreamingDecoder();
130
131 void Abort();
133
134 Isolate* isolate() const { return isolate_; }
135
138
139 private:
140 class CompileTask;
141 class CompileStep;
142 class CompilationStateCallback;
143
144 // States of the AsyncCompileJob.
145 // Step 1 (async). Decodes the wasm module.
146 // --> Fail on decoding failure,
147 // --> PrepareAndStartCompile on success.
148 class DecodeModule;
149
150 // Step 2 (sync). Prepares runtime objects and starts background compilation.
151 // --> finish directly on native module cache hit,
152 // --> finish directly on validation error,
153 // --> trigger eager compilation, if any; FinishCompile is triggered when
154 // done.
155 class PrepareAndStartCompile;
156
157 // Step 3 (sync). Compilation finished. Finalize the module and resolve the
158 // promise.
159 class FinishCompilation;
160
161 // Step 4 (sync). Decoding, validation or compilation failed. Reject the
162 // promise.
163 class Fail;
164
166
167 // Decrements the number of outstanding finishers. The last caller of this
168 // function should finish the asynchronous compilation, see the comment on
169 // {outstanding_finishers_}.
174
175 void CreateNativeModule(std::shared_ptr<const WasmModule> module,
176 size_t code_size_estimate);
177 // Return true for cache hit, false for cache miss.
178 bool GetOrCreateNativeModule(std::shared_ptr<const WasmModule> module,
179 size_t code_size_estimate);
181
182 void FinishCompile(bool is_after_cache_hit);
183
184 void Failed();
185
187
188 void FinishSuccessfully();
189
190 void StartForegroundTask();
192
193 void StartBackgroundTask();
194
199 // Switches to the compilation step {Step} and starts a foreground task to
200 // execute it. Most of the time we know that there cannot be a running
201 // foreground task. If there might be one, then pass
202 // kUseExistingForegroundTask to avoid spawning a second one.
203 template <typename Step,
205 typename... Args>
206 void DoSync(Args&&... args);
207
208 // Switches to the compilation step {Step} and immediately executes that step.
209 template <typename Step, typename... Args>
210 void DoImmediately(Args&&... args);
211
212 // Switches to the compilation step {Step} and starts a background task to
213 // execute it.
214 template <typename Step, typename... Args>
215 void DoAsync(Args&&... args);
216
217 // Switches to the compilation step {Step} but does not start a task to
218 // execute it.
219 template <typename Step, typename... Args>
220 void NextStep(Args&&... args);
221
223 const char* const api_method_name_;
228 // Copy of the module wire bytes, moved into the {native_module_} on its
229 // creation.
231 // Reference to the wire bytes (held in {bytes_copy_} or as part of
232 // {native_module_}).
238 const std::shared_ptr<CompilationResultResolver> resolver_;
239
241 std::shared_ptr<NativeModule> native_module_;
242
243 std::unique_ptr<CompileStep> step_;
245
246 std::shared_ptr<v8::TaskRunner> foreground_task_runner_;
247
248 // For async compilation the AsyncCompileJob is the only finisher. For
249 // streaming compilation also the AsyncStreamingProcessor has to finish before
250 // compilation can be finished.
251 std::atomic<int32_t> outstanding_finishers_{1};
252
253 // A reference to a pending foreground task, or {nullptr} if none is pending.
255
256 // The AsyncCompileJob owns the StreamingDecoder because the StreamingDecoder
257 // contains data which is needed by the AsyncCompileJob for streaming
258 // compilation. The AsyncCompileJob does not actively use the
259 // StreamingDecoder.
260 std::shared_ptr<StreamingDecoder> stream_;
261
262 // The compilation id to identify trace events linked to this compilation.
264};
265
266} // namespace wasm
267} // namespace internal
268} // namespace v8
269
270#endif // V8_WASM_MODULE_COMPILER_H_
Builtins::Kind kind
Definition builtins.cc:40
V8_WARN_UNUSED_RESULT bool DecrementAndCheckFinisherCount()
const WasmEnabledFeatures enabled_features_
void FinishCompile(bool is_after_cache_hit)
CancelableTaskManager background_task_manager_
AsyncCompileJob(Isolate *isolate, WasmEnabledFeatures enabled_features, CompileTimeImports compile_imports, base::OwnedVector< const uint8_t > bytes, DirectHandle< Context > context, DirectHandle< NativeContext > incumbent_context, const char *api_method_name, std::shared_ptr< CompilationResultResolver > resolver, int compilation_id)
IndirectHandle< WasmModuleObject > module_object_
const std::shared_ptr< CompilationResultResolver > resolver_
IndirectHandle< NativeContext > incumbent_context_
std::shared_ptr< StreamingDecoder > CreateStreamingDecoder()
v8::metrics::Recorder::ContextId context_id_
std::shared_ptr< v8::TaskRunner > foreground_task_runner_
IndirectHandle< NativeContext > native_context_
DirectHandle< NativeContext > context() const
std::shared_ptr< StreamingDecoder > stream_
std::shared_ptr< NativeModule > native_module_
v8::metrics::Recorder::ContextId context_id() const
void AsyncCompileSucceeded(DirectHandle< WasmModuleObject > result)
std::atomic< int32_t > outstanding_finishers_
bool GetOrCreateNativeModule(std::shared_ptr< const WasmModule > module, size_t code_size_estimate)
v8::metrics::WasmModuleDecoded metrics_event_
void CreateNativeModule(std::shared_ptr< const WasmModule > module, size_t code_size_estimate)
base::OwnedVector< const uint8_t > bytes_copy_
std::unique_ptr< CompileStep > step_
base::Vector< const DirectHandle< Object > > args
Definition execution.cc:74
ZoneVector< RpoNumber > & result
void TierUpNowForTesting(Isolate *isolate, Tagged< WasmTrustedInstanceData > trusted_instance_data, int func_index)
void TriggerTierUp(Isolate *isolate, Tagged< WasmTrustedInstanceData > trusted_instance_data, int func_index)
void TierUpAllForTesting(Isolate *isolate, Tagged< WasmTrustedInstanceData > trusted_instance_data)
void InitializeCompilationForTesting(NativeModule *native_module)
WasmCode * CompileImportWrapperForTest(Isolate *isolate, NativeModule *native_module, ImportCallKind kind, const CanonicalSig *sig, CanonicalTypeIndex type_index, int expected_arity, Suspend suspend)
void ThrowLazyCompilationError(Isolate *isolate, const NativeModule *native_module, int func_index)
std::shared_ptr< NativeModule > CompileToNativeModule(Isolate *isolate, WasmEnabledFeatures enabled_features, WasmDetectedFeatures detected_features, CompileTimeImports compile_imports, ErrorThrower *thrower, std::shared_ptr< const WasmModule > module, base::OwnedVector< const uint8_t > wire_bytes, int compilation_id, v8::metrics::Recorder::ContextId context_id, ProfileInformation *pgo_info)
WasmError ValidateAndSetBuiltinImports(const WasmModule *module, base::Vector< const uint8_t > wire_bytes, const CompileTimeImports &imports, WasmDetectedFeatures *detected)
void PublishDetectedFeatures(WasmDetectedFeatures detected_features, Isolate *isolate, bool is_initial_compilation)
bool CompileLazy(Isolate *isolate, Tagged< WasmTrustedInstanceData > trusted_instance_data, int func_index)
kWasmInternalFunctionIndirectPointerTag WasmTrustedInstanceData
Tagged(T object) -> Tagged< T >
wasm::WasmModule WasmModule
kWasmInternalFunctionIndirectPointerTag kProtectedInstanceDataOffset sig
Definition c-api.cc:87
#define DCHECK_LT(v1, v2)
Definition logging.h:489
#define V8_EXPORT_PRIVATE
Definition macros.h:460
#define V8_WARN_UNUSED_RESULT
Definition v8config.h:671