Debian Codegraph @

js/src/wasm/WasmCompileArgs.h

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 *
4 * Copyright 2021 Mozilla Foundation
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 #ifndef wasm_compile_args_h
20 #define wasm_compile_args_h
21
22 #include "mozilla/RefPtr.h"
23 #include "mozilla/SHA1.h"
24 #include "mozilla/TypedEnumBits.h"
25
26 #include "js/Utility.h"
27 #include "js/WasmFeatures.h"
28 #include "wasm/WasmBinaryTypes.h"
29 #include "wasm/WasmConstants.h"
30 #include "wasm/WasmShareable.h"
31
32 namespace js {
33 namespace wasm {
34
35 enum class Shareable { False, True };
36
37 // Code can be compiled either with the Baseline compiler or the Ion compiler,
38 // and tier-variant data are tagged with the Tier value.
39 //
40 // A tier value is used to request tier-variant aspects of code, metadata, or
41 // linkdata. The tiers are normally explicit (Baseline and Ion); implicit tiers
42 // can be obtained through accessors on Code objects (eg, stableTier).
43
44 enum class Tier {
45 Baseline,
46 Debug = Baseline,
47 Optimized,
48 Serialized = Optimized
49 };
50
51 static constexpr const char* ToString(Tier tier) {
52 switch (tier) {
53 case wasm::Tier::Baseline:
54 return "baseline";
55 case wasm::Tier::Optimized:
56 return "optimized";
57 default:
58 return "unknown";
59 }
60 }
61
62 // Iterator over tiers present in a tiered data structure.
63
64 class Tiers {
65 Tier t_[2];
66 uint32_t n_;
67
68 public:
69 explicit Tiers() { n_ = 0; }
70 explicit Tiers(Tier t) {
71 t_[0] = t;
72 n_ = 1;
73 }
74 explicit Tiers(Tier t, Tier u) {
75 MOZ_ASSERT(t != u);
76 t_[0] = t;
77 t_[1] = u;
78 n_ = 2;
79 }
80
81 Tier* begin() { return t_; }
82 Tier* end() { return t_ + n_; }
83 };
84
85 struct BuiltinModuleIds {
86 BuiltinModuleIds() = default;
87
88 bool selfTest = false;
89 bool intGemm = false;
90 bool jsString = false;
91 bool jsStringConstants = false;
92 SharedChars jsStringConstantsNamespace;
93
94 bool hasNone() const {
95 return !selfTest && !intGemm && !jsString && !jsStringConstants;
96 }
97 };
98
99 // Describes per-compilation settings that are controlled by an options bag
100 // passed to compilation and validation functions. (Nonstandard extension
101 // available under prefs.)
102
103 struct FeatureOptions {
104 FeatureOptions()
105 : disableOptimizingCompiler(false),
106 isBuiltinModule(false),
107 jsStringBuiltins(false),
108 jsStringConstants(false),
109 requireExnref(false) {}
110
111 // Whether we should try to disable our optimizing compiler. Only available
112 // with `IsSimdPrivilegedContext`.
113 bool disableOptimizingCompiler;
114
115 // Enables builtin module opcodes, only set in WasmBuiltinModule.cpp.
116 bool isBuiltinModule;
117
118 // Enable JS String builtins for this module, only available if the feature
119 // is also enabled.
120 bool jsStringBuiltins;
121 // Enable imported string constants for this module, only available if the
122 // feature is also enabled.
123 bool jsStringConstants;
124 SharedChars jsStringConstantsNamespace;
125
126 // Enable exnref support.
127 bool requireExnref;
128
129 // Parse the compile options bag.
130 [[nodiscard]] bool init(JSContext* cx, HandleValue val);
131 };
132
133 // Describes the features that control wasm compilation.
134
135 struct FeatureArgs {
136 FeatureArgs()
137 :
138 #define WASM_FEATURE(NAME, LOWER_NAME, ...) LOWER_NAME(false),
139 JS_FOR_WASM_FEATURES(WASM_FEATURE)
140 #undef WASM_FEATURE
141 sharedMemory(Shareable::False),
142 simd(false),
143 isBuiltinModule(false),
144 builtinModules() {
145 }
146 FeatureArgs(const FeatureArgs&) = default;
147 FeatureArgs& operator=(const FeatureArgs&) = default;
148 FeatureArgs(FeatureArgs&&) = default;
149 FeatureArgs& operator=(FeatureArgs&&) = default;
150
151 static FeatureArgs build(JSContext* cx, const FeatureOptions& options);
152 static FeatureArgs allEnabled() {
153 FeatureArgs args;
154 #define WASM_FEATURE(NAME, LOWER_NAME, ...) args.LOWER_NAME = true;
155 JS_FOR_WASM_FEATURES(WASM_FEATURE)
156 #undef WASM_FEATURE
157 args.sharedMemory = Shareable::True;
158 args.simd = true;
159 return args;
160 }
161
162 #define WASM_FEATURE(NAME, LOWER_NAME, ...) bool LOWER_NAME;
163 JS_FOR_WASM_FEATURES(WASM_FEATURE)
164 #undef WASM_FEATURE
165
166 Shareable sharedMemory;
167 bool simd;
168 // Whether this module is a wasm builtin module (see WasmBuiltinModule.h) and
169 // can contain special opcodes in function bodies.
170 bool isBuiltinModule;
171 // The set of builtin modules that are imported by this module.
172 BuiltinModuleIds builtinModules;
173 };
174
175 // Observed feature usage for a compiled module. Intended to be used for use
176 // counters.
177 enum class FeatureUsage : uint8_t {
178 None = 0x0,
179 LegacyExceptions = 0x1,
180 ReturnCall = 0x2,
181 };
182
183 using FeatureUsageVector = Vector<FeatureUsage, 0, SystemAllocPolicy>;
184
185 void SetUseCountersForFeatureUsage(JSContext* cx, JSObject* object,
186 FeatureUsage usage);
187
188 MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(FeatureUsage);
189
190 // Describes the JS scripted caller of a request to compile a wasm module.
191
192 struct ScriptedCaller {
193 UniqueChars filename; // UTF-8 encoded
194 bool filenameIsURL;
195 uint32_t line;
196
197 ScriptedCaller() : filenameIsURL(false), line(0) {}
198 };
199
200 // Describes the reasons we cannot compute compile args
201
202 enum class CompileArgsError {
203 OutOfMemory,
204 NoCompiler,
205 };
206
207 // Describes all the parameters that control wasm compilation.
208
209 struct CompileArgs;
210 using MutableCompileArgs = RefPtr<CompileArgs>;
211 using SharedCompileArgs = RefPtr<const CompileArgs>;
212
213 struct CompileArgs : ShareableBase<CompileArgs> {
214 ScriptedCaller scriptedCaller;
215 UniqueChars sourceMapURL;
216
217 bool baselineEnabled;
218 bool ionEnabled;
219 bool debugEnabled;
220 bool forceTiering;
221
222 FeatureArgs features;
223
224 // CompileArgs has several constructors:
225 //
226 // - two through factory functions `build`/`buildAndReport`, which checks
227 // that flags are consistent with each other, and optionally reports any
228 // errors.
229 // - the 'buildForAsmJS' one, which uses the appropriate configuration for
230 // legacy asm.js code.
231 // - the 'buildForValidation' one, which takes just the features to enable
232 // and sets the compilers to a null state.
233 // - one that gives complete access to underlying fields.
234 //
235 // You should use the factory functions in general, unless you have a very
236 // good reason (i.e. no JSContext around and you know which flags have been
237 // used).
238
239 static SharedCompileArgs build(JSContext* cx, ScriptedCaller&& scriptedCaller,
240 const FeatureOptions& options,
241 CompileArgsError* error);
242 static SharedCompileArgs buildForAsmJS(ScriptedCaller&& scriptedCaller);
243 static SharedCompileArgs buildAndReport(JSContext* cx,
244 ScriptedCaller&& scriptedCaller,
245 const FeatureOptions& options,
246 bool reportOOM = false);
247 static SharedCompileArgs buildForValidation(const FeatureArgs& args);
248
249 explicit CompileArgs()
250 : scriptedCaller(),
251 baselineEnabled(false),
252 ionEnabled(false),
253 debugEnabled(false),
254 forceTiering(false) {}
255 };
256
257 // CompilerEnvironment holds any values that will be needed to compute
258 // compilation parameters once the module's feature opt-in sections have been
259 // parsed.
260 //
261 // Subsequent to construction a computeParameters() call will compute the final
262 // compilation parameters, and the object can then be queried for their values.
263
264 struct CompileArgs;
265 class Decoder;
266
267 struct CompilerEnvironment {
268 // The object starts in one of two "initial" states; computeParameters moves
269 // it into the "computed" state.
270 enum State { InitialWithArgs, InitialWithModeTierDebug, Computed };
271
272 State state_;
273 union {
274 // Value if the state_ == InitialWithArgs.
275 const CompileArgs* args_;
276
277 // Value in the other two states.
278 struct {
279 CompileMode mode_;
280 Tier tier_;
281 DebugEnabled debug_;
282 };
283 };
284
285 public:
286 // Retain a reference to the CompileArgs. A subsequent computeParameters()
287 // will compute all parameters from the CompileArgs and additional values.
288 explicit CompilerEnvironment(const CompileArgs& args);
289
290 // Save the provided values for mode, tier, and debug, and the initial value
291 // for gc/refTypes. A subsequent computeParameters() will compute the
292 // final value of gc/refTypes.
293 CompilerEnvironment(CompileMode mode, Tier tier, DebugEnabled debugEnabled);
294
295 // Compute any remaining compilation parameters.
296 void computeParameters(const ModuleMetadata& moduleMeta);
297
298 // Compute any remaining compilation parameters. Only use this method if
299 // the CompilerEnvironment was created with values for mode, tier, and
300 // debug.
301 void computeParameters();
302
303 bool isComputed() const { return state_ == Computed; }
304 CompileMode mode() const {
305 MOZ_ASSERT(isComputed());
306 return mode_;
307 }
308 CompileState initialState() const {
309 switch (mode()) {
310 case CompileMode::Once:
311 return CompileState::Once;
312 case CompileMode::EagerTiering:
313 return CompileState::EagerTier1;
314 case CompileMode::LazyTiering:
315 return CompileState::LazyTier1;
316 default:
317 MOZ_CRASH();
318 }
319 }
320 Tier tier() const {
321 MOZ_ASSERT(isComputed());
322 return tier_;
323 }
324 DebugEnabled debug() const {
325 MOZ_ASSERT(isComputed());
326 return debug_;
327 }
328 bool debugEnabled() const { return debug() == DebugEnabled::True; }
329 };
330
331 // A bytecode source is a wrapper around wasm bytecode that is to be compiled
332 // or validated. It has been pre-parsed into three regions:
333 // 1. 'env' - everything before the code section
334 // 2. 'code' - the code section
335 // 3. 'tail' - everything after the code section.
336 //
337 // The naming here matches the corresponding validation functions we have. This
338 // design comes from the requirements of streaming compilation which assembles
339 // separate buffers for each of these regions, and never constructs a single
340 // contiguous buffer. We use it for compiling contiguous buffers as well so that
341 // we have a single code path.
342 //
343 // If a module does not contain a code section (or is invalid and cannot be
344 // split into these regions), the bytecode source will only have an 'env'
345 // region.
346 //
347 // This class does not own any of the underlying buffers and only points to
348 // them. See BytecodeBuffer for that.
349 class BytecodeSource {
350 BytecodeSpan env_;
351 BytecodeSpan code_;
352 BytecodeSpan tail_;
353
354 size_t envOffset() const { return 0; }
355 size_t codeOffset() const { return envOffset() + envLength(); }
356 size_t tailOffset() const { return codeOffset() + codeLength(); }
357
358 size_t envLength() const { return env_.size(); }
359 size_t codeLength() const { return code_.size(); }
360 size_t tailLength() const { return tail_.size(); }
361
362 public:
363 // Create a bytecode source with no bytecode.
364 BytecodeSource() = default;
365
366 // Create a bytecode source from regions that have already been split. Does
367 // not do any validation.
368 BytecodeSource(const BytecodeSpan& envSpan, const BytecodeSpan& codeSpan,
369 const BytecodeSpan& tailSpan)
370 : env_(envSpan), code_(codeSpan), tail_(tailSpan) {}
371
372 // Parse a contiguous buffer into a bytecode source. This cannot fail because
373 // invalid modules will result in a bytecode source with only an 'env' region
374 // that further validation will reject.
375 BytecodeSource(const uint8_t* begin, size_t length);
376
377 // Copying and moving is allowed.
378 BytecodeSource(const BytecodeSource&) = default;
379 BytecodeSource& operator=(const BytecodeSource&) = default;
380 BytecodeSource(BytecodeSource&&) = default;
381 BytecodeSource& operator=(BytecodeSource&&) = default;
382
383 // The length in bytes of this module.
384 size_t length() const { return env_.size() + code_.size() + tail_.size(); }
385
386 // Whether we have a code section region or not. If there is no code section,
387 // then the tail region will be in the env region and must be parsed from
388 // there.
389 bool hasCodeSection() const { return code_.size() != 0; }
390
391 BytecodeRange envRange() const {
392 return BytecodeRange(envOffset(), envLength());
393 }
394 BytecodeRange codeRange() const {
395 // Do not ask for the code range if we don't have a code section.
396 MOZ_ASSERT(hasCodeSection());
397 return BytecodeRange(codeOffset(), codeLength());
398 }
399 BytecodeRange tailRange() const {
400 // Do not ask for the tail range if we don't have a code section. Any
401 // contents that would be in the tail section will be in the env section,
402 // and the caller must use that section instead.
403 MOZ_ASSERT(hasCodeSection());
404 return BytecodeRange(tailOffset(), tailLength());
405 }
406
407 BytecodeSpan envSpan() const { return env_; }
408 BytecodeSpan codeSpan() const {
409 // Do not ask for the code span if we don't have a code section.
410 MOZ_ASSERT(hasCodeSection());
411 return code_;
412 }
413 BytecodeSpan tailSpan() const {
414 // Do not ask for the tail span if we don't have a code section. Any
415 // contents that would be in the tail section will be in the env section,
416 // and the caller must use that section instead.
417 MOZ_ASSERT(hasCodeSection());
418 return tail_;
419 }
420 BytecodeSpan getSpan(const BytecodeRange& range) const {
421 // Check if this range is within the env span
422 if (range.end <= codeOffset()) {
423 return range.toSpan(env_);
424 }
425
426 // Check if this range is within the code span
427 if (range.end <= tailOffset()) {
428 // The range cannot cross the span boundary
429 MOZ_RELEASE_ASSERT(range.start >= codeOffset());
430 return range.relativeTo(codeRange()).toSpan(code_);
431 }
432
433 // Otherwise we must be within the tail span
434 // The range cannot cross the span boundary
435 MOZ_RELEASE_ASSERT(range.start >= tailOffset());
436 return range.relativeTo(tailRange()).toSpan(tail_);
437 }
438
439 // Copy the contents of this buffer to the destination. The destination must
440 // be at least `this->length()` bytes.
441 void copyTo(uint8_t* dest) const {
442 memcpy(dest + envOffset(), env_.data(), env_.size());
443 memcpy(dest + codeOffset(), code_.data(), code_.size());
444 memcpy(dest + tailOffset(), tail_.data(), tail_.size());
445 }
446
447 // Compute a SHA1 hash of the module.
448 void computeHash(mozilla::SHA1Sum::Hash* hash) const {
449 mozilla::SHA1Sum sha1Sum;
450 sha1Sum.update(env_.data(), env_.size());
451 sha1Sum.update(code_.data(), code_.size());
452 sha1Sum.update(tail_.data(), tail_.size());
453 sha1Sum.finish(*hash);
454 }
455 };
456
457 // A version of `BytecodeSource` that owns the underlying buffers for each
458 // region of bytecode. See the comment on `BytecodeSource` for interpretation
459 // of the different regions.
460 //
461 // The regions are allocated in separate vectors so that we can just hold onto
462 // the code section after we've finished compiling the module without having to
463 // split apart the bytecode buffer.
464 class BytecodeBuffer {
465 SharedBytes env_;
466 SharedBytes code_;
467 SharedBytes tail_;
468 BytecodeSource source_;
469
470 public:
471 // Create an empty buffer.
472 BytecodeBuffer() = default;
473 // Create a buffer from pre-parsed regions.
474 BytecodeBuffer(const ShareableBytes* env, const ShareableBytes* code,
475 const ShareableBytes* tail);
476 // Create a buffer from a source by allocating memory for each region.
477 [[nodiscard]]
478 static bool fromSource(const BytecodeSource& bytecodeSource,
479 BytecodeBuffer* bytecodeBuffer);
480
481 // Copying and moving is allowed, we just hold references to the underyling
482 // buffers.
483 BytecodeBuffer(const BytecodeBuffer&) = default;
484 BytecodeBuffer& operator=(const BytecodeBuffer&) = default;
485 BytecodeBuffer(BytecodeBuffer&&) = default;
486 BytecodeBuffer& operator=(BytecodeBuffer&&) = default;
487
488 // Get a bytecode source that points into our owned memory.
489 const BytecodeSource& source() const { return source_; }
490
491 // Grab a reference to the code section region, if any.
492 SharedBytes codeSection() const { return code_; }
493 };
494
495 // Utility for passing either a bytecode buffer (which owns the bytecode) or
496 // just the source (which does not own the bytecode).
497 class BytecodeBufferOrSource {
498 union {
499 const BytecodeBuffer* buffer_;
500 BytecodeSource source_;
501 };
502 bool hasBuffer_;
503
504 public:
505 BytecodeBufferOrSource() : source_(BytecodeSource()), hasBuffer_(false) {}
506 explicit BytecodeBufferOrSource(const BytecodeBuffer& buffer)
507 : buffer_(&buffer), hasBuffer_(true) {}
508 explicit BytecodeBufferOrSource(const BytecodeSource& source)
509 : source_(source), hasBuffer_(false) {}
510
511 BytecodeBufferOrSource(const BytecodeBufferOrSource&) = delete;
512 const BytecodeBufferOrSource& operator=(const BytecodeBufferOrSource&) =
513 delete;
514
515 ~BytecodeBufferOrSource() {
516 if (!hasBuffer_) {
517 source_.~BytecodeSource();
518 }
519 }
520
521 bool hasBuffer() const { return hasBuffer_; }
522 const BytecodeBuffer& buffer() const {
523 MOZ_ASSERT(hasBuffer());
524 return *buffer_;
525 }
526 const BytecodeSource& source() const {
527 if (hasBuffer_) {
528 return buffer_->source();
529 }
530 return source_;
531 }
532
533 [[nodiscard]] bool getOrCreateBuffer(BytecodeBuffer* result) const {
534 if (hasBuffer()) {
535 *result = buffer();
536 }
537 return BytecodeBuffer::fromSource(source(), result);
538 }
539
540 [[nodiscard]] SharedBytes getOrCreateCodeSection() const {
541 if (hasBuffer()) {
542 return buffer().codeSection();
543 }
544 return ShareableBytes::fromSpan(source().codeSpan());
545 }
546 };
547
548 } // namespace wasm
549 } // namespace js
550
551 #endif // wasm_compile_args_h