Debian Codegraph @

js/src/wasm/WasmCodegenTypes.cpp

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 #include "wasm/WasmCodegenTypes.h"
20
21 #include "wasm/WasmExprType.h"
22 #include "wasm/WasmStubs.h"
23 #include "wasm/WasmSummarizeInsn.h"
24 #include "wasm/WasmTypeDef.h"
25 #include "wasm/WasmValidate.h"
26 #include "wasm/WasmValue.h"
27
28 using mozilla::MakeEnumeratedRange;
29 using mozilla::PodZero;
30
31 using namespace js;
32 using namespace js::wasm;
33
34 ArgTypeVector::ArgTypeVector(const FuncType& funcType)
35 : args_(funcType.args()),
36 hasStackResults_(ABIResultIter::HasStackResults(
37 ResultType::Vector(funcType.results()))) {}
38
39 bool TrapSitesForKind::lookup(uint32_t trapInstructionOffset,
40 const InliningContext& inliningContext,
41 TrapSite* trapOut) const {
42 size_t lowerBound = 0;
43 size_t upperBound = pcOffsets_.length();
44
45 size_t match;
46 if (BinarySearch(pcOffsets_, lowerBound, upperBound, trapInstructionOffset,
47 &match)) {
48 TrapSite site;
49 site.bytecodeOffset = bytecodeOffsets_[match];
50 if (auto inlinedCallerOffsetsIndex =
51 inlinedCallerOffsetsMap_.lookup(match)) {
52 site.inlinedCallerOffsets =
53 inliningContext[inlinedCallerOffsetsIndex->value()];
54 } else {
55 site.inlinedCallerOffsets = nullptr;
56 }
57 *trapOut = site;
58 return true;
59 }
60 return false;
61 }
62
63 #ifdef DEBUG
64 const char* wasm::ToString(Trap trap) {
65 switch (trap) {
66 case Trap::Unreachable:
67 return "Unreachable";
68 case Trap::IntegerOverflow:
69 return "IntegerOverflow";
70 case Trap::InvalidConversionToInteger:
71 return "InvalidConversionToInteger";
72 case Trap::IntegerDivideByZero:
73 return "IntegerDivideByZero";
74 case Trap::OutOfBounds:
75 return "OutOfBounds";
76 case Trap::UnalignedAccess:
77 return "UnalignedAccess";
78 case Trap::IndirectCallToNull:
79 return "IndirectCallToNull";
80 case Trap::IndirectCallBadSig:
81 return "IndirectCallBadSig";
82 case Trap::NullPointerDereference:
83 return "NullPointerDereference";
84 case Trap::BadCast:
85 return "BadCast";
86 case Trap::StackOverflow:
87 return "StackOverflow";
88 case Trap::CheckInterrupt:
89 return "CheckInterrupt";
90 case Trap::ThrowReported:
91 return "ThrowReported";
92 case Trap::Limit:
93 return "Limit";
94 default:
95 return "Unknown";
96 }
97 }
98
99 const char* wasm::ToString(TrapMachineInsn tmi) {
100 switch (tmi) {
101 case TrapMachineInsn::OfficialUD:
102 return "OfficialUD";
103 case TrapMachineInsn::Load8:
104 return "Load8";
105 case TrapMachineInsn::Load16:
106 return "Load16";
107 case TrapMachineInsn::Load32:
108 return "Load32";
109 case TrapMachineInsn::Load64:
110 return "Load64";
111 case TrapMachineInsn::Load128:
112 return "Load128";
113 case TrapMachineInsn::Store8:
114 return "Store8";
115 case TrapMachineInsn::Store16:
116 return "Store16";
117 case TrapMachineInsn::Store32:
118 return "Store32";
119 case TrapMachineInsn::Store64:
120 return "Store64";
121 case TrapMachineInsn::Store128:
122 return "Store128";
123 case TrapMachineInsn::Atomic:
124 return "Atomic";
125 default:
126 return "Unknown";
127 }
128 }
129 #endif // DEBUG
130
131 void TrapSitesForKind::checkInvariants(const uint8_t* codeBase) const {
132 #ifdef DEBUG
133 MOZ_ASSERT(machineInsns_.length() == pcOffsets_.length());
134 MOZ_ASSERT(pcOffsets_.length() == bytecodeOffsets_.length());
135
136 uint32_t last = 0;
137 for (uint32_t pcOffset : pcOffsets_) {
138 MOZ_ASSERT(pcOffset > last);
139 last = pcOffset;
140 }
141
142 # if (defined(JS_CODEGEN_X64) || defined(JS_CODEGEN_X86) || \
143 defined(JS_CODEGEN_ARM64) || defined(JS_CODEGEN_ARM) || \
144 defined(JS_CODEGEN_LOONG64) || defined(JS_CODEGEN_MIPS64))
145 // Check that each trapsite is associated with a plausible instruction. The
146 // required instruction kind depends on the trapsite kind.
147 //
148 // NOTE: currently enabled on x86_{32,64}, arm{32,64}, loongson64 and mips64.
149 // Ideally it should be extended to riscv64 too.
150 //
151 for (uint32_t i = 0; i < length(); i++) {
152 uint32_t pcOffset = pcOffsets_[i];
153 TrapMachineInsn expected = machineInsns_[i];
154
155 const uint8_t* insnAddr = codeBase + uintptr_t(pcOffset);
156 // `expected` describes the kind of instruction we expect to see at
157 // `insnAddr`. Find out what is actually there and check it matches.
158 mozilla::Maybe<TrapMachineInsn> actual = SummarizeTrapInstruction(insnAddr);
159 bool valid = actual.isSome() && actual.value() == expected;
160 // This is useful for diagnosing validation failures.
161 // if (!valid) {
162 // fprintf(stderr,
163 // "FAIL: reason=%-22s expected=%-12s "
164 // "pcOffset=%-5u addr= %p\n",
165 // ToString(trap), ToString(expected),
166 // pcOffset, insnAddr);
167 // if (actual.isSome()) {
168 // fprintf(stderr, "FAIL: identified as %s\n",
169 // actual.isSome() ? ToString(actual.value())
170 // : "(insn not identified)");
171 // }
172 // }
173 MOZ_ASSERT(valid, "wasm trapsite does not reference a valid insn");
174 }
175
176 for (auto iter = inlinedCallerOffsetsMap_.iter(); !iter.done(); iter.next()) {
177 MOZ_ASSERT(iter.get().key() < length());
178 MOZ_ASSERT(!iter.get().value().isNone());
179 }
180 # endif
181 #endif
182 }
183
184 CodeRange::CodeRange(Kind kind, Offsets offsets)
185 : begin_(offsets.begin), ret_(0), end_(offsets.end), kind_(kind) {
186 MOZ_ASSERT(begin_ <= end_);
187 PodZero(&u);
188 #ifdef DEBUG
189 switch (kind_) {
190 case FarJumpIsland:
191 case TrapExit:
192 case Throw:
193 break;
194 default:
195 MOZ_CRASH("should use more specific constructor");
196 }
197 #endif
198 }
199
200 CodeRange::CodeRange(Kind kind, uint32_t funcIndex, Offsets offsets)
201 : begin_(offsets.begin), ret_(0), end_(offsets.end), kind_(kind) {
202 u.funcIndex_ = funcIndex;
203 u.func.beginToUncheckedCallEntry_ = 0;
204 u.func.beginToTierEntry_ = 0;
205 u.func.hasUnwindInfo_ = false;
206 MOZ_ASSERT(isEntry());
207 MOZ_ASSERT(begin_ <= end_);
208 }
209
210 CodeRange::CodeRange(Kind kind, CallableOffsets offsets)
211 : begin_(offsets.begin), ret_(offsets.ret), end_(offsets.end), kind_(kind) {
212 MOZ_ASSERT(begin_ < ret_);
213 MOZ_ASSERT(ret_ < end_);
214 PodZero(&u);
215 #ifdef DEBUG
216 switch (kind_) {
217 case DebugStub:
218 case BuiltinThunk:
219 case RequestTierUpStub:
220 case UpdateCallRefMetricsStub:
221 break;
222 default:
223 MOZ_CRASH("should use more specific constructor");
224 }
225 #endif
226 }
227
228 CodeRange::CodeRange(Kind kind, uint32_t funcIndex, CallableOffsets offsets)
229 : begin_(offsets.begin), ret_(offsets.ret), end_(offsets.end), kind_(kind) {
230 MOZ_ASSERT(isImportExit() || isJitEntry());
231 MOZ_ASSERT(begin_ < ret_);
232 MOZ_ASSERT(ret_ < end_);
233 u.funcIndex_ = funcIndex;
234 u.func.beginToUncheckedCallEntry_ = 0;
235 u.func.beginToTierEntry_ = 0;
236 u.func.hasUnwindInfo_ = false;
237 }
238
239 CodeRange::CodeRange(Kind kind, uint32_t funcIndex, ImportOffsets offsets)
240 : begin_(offsets.begin), ret_(offsets.ret), end_(offsets.end), kind_(kind) {
241 MOZ_ASSERT(isImportJitExit());
242 MOZ_ASSERT(begin_ < ret_);
243 MOZ_ASSERT(ret_ < end_);
244 uint32_t entry = offsets.afterFallbackCheck;
245 MOZ_ASSERT(begin_ <= entry && entry <= ret_);
246 u.funcIndex_ = funcIndex;
247 u.jitExitEntry_ = entry - begin_;
248 }
249
250 CodeRange::CodeRange(uint32_t funcIndex, FuncOffsets offsets,
251 bool hasUnwindInfo)
252 : begin_(offsets.begin),
253 ret_(offsets.ret),
254 end_(offsets.end),
255 kind_(Function) {
256 MOZ_ASSERT(begin_ < ret_);
257 MOZ_ASSERT(ret_ < end_);
258 MOZ_ASSERT(offsets.uncheckedCallEntry - begin_ <= UINT16_MAX);
259 MOZ_ASSERT(offsets.tierEntry - begin_ <= UINT16_MAX);
260 u.funcIndex_ = funcIndex;
261 u.func.beginToUncheckedCallEntry_ = offsets.uncheckedCallEntry - begin_;
262 u.func.beginToTierEntry_ = offsets.tierEntry - begin_;
263 u.func.hasUnwindInfo_ = hasUnwindInfo;
264 }
265
266 const CodeRange* wasm::LookupInSorted(const CodeRangeVector& codeRanges,
267 CodeRange::OffsetInCode target) {
268 size_t lowerBound = 0;
269 size_t upperBound = codeRanges.length();
270
271 size_t match;
272 if (!BinarySearch(codeRanges, lowerBound, upperBound, target, &match)) {
273 return nullptr;
274 }
275
276 return &codeRanges[match];
277 }
278
279 bool CallSites::lookup(uint32_t returnAddressOffset,
280 const InliningContext& inliningContext,
281 CallSite* callSite) const {
282 size_t lowerBound = 0;
283 size_t upperBound = returnAddressOffsets_.length();
284
285 size_t match;
286 if (BinarySearch(returnAddressOffsets_, lowerBound, upperBound,
287 returnAddressOffset, &match)) {
288 *callSite = get(match, inliningContext);
289 return true;
290 }
291 return false;
292 }
293
294 CallIndirectId CallIndirectId::forAsmJSFunc() {
295 return CallIndirectId(CallIndirectIdKind::AsmJS);
296 }
297
298 CallIndirectId CallIndirectId::forFunc(const CodeMetadata& codeMeta,
299 uint32_t funcIndex) {
300 // asm.js tables are homogenous and don't require a signature check
301 if (codeMeta.isAsmJS()) {
302 return CallIndirectId::forAsmJSFunc();
303 }
304
305 FuncDesc func = codeMeta.funcs[funcIndex];
306 if (!func.canRefFunc()) {
307 return CallIndirectId();
308 }
309 return CallIndirectId::forFuncType(codeMeta,
310 codeMeta.funcs[funcIndex].typeIndex);
311 }
312
313 CallIndirectId CallIndirectId::forFuncType(const CodeMetadata& codeMeta,
314 uint32_t funcTypeIndex) {
315 // asm.js tables are homogenous and don't require a signature check
316 if (codeMeta.isAsmJS()) {
317 return CallIndirectId::forAsmJSFunc();
318 }
319
320 const TypeDef& typeDef = codeMeta.types->type(funcTypeIndex);
321 const FuncType& funcType = typeDef.funcType();
322 CallIndirectId callIndirectId;
323 if (funcType.hasImmediateTypeId()) {
324 callIndirectId.kind_ = CallIndirectIdKind::Immediate;
325 callIndirectId.immediate_ = funcType.immediateTypeId();
326 } else {
327 callIndirectId.kind_ = CallIndirectIdKind::Global;
328 callIndirectId.global_.instanceDataOffset_ =
329 codeMeta.offsetOfTypeDef(funcTypeIndex);
330 callIndirectId.global_.hasSuperType_ = typeDef.superTypeDef() != nullptr;
331 }
332 return callIndirectId;
333 }
334
335 CalleeDesc CalleeDesc::function(uint32_t funcIndex) {
336 CalleeDesc c;
337 c.which_ = Func;
338 c.u.funcIndex_ = funcIndex;
339 return c;
340 }
341 CalleeDesc CalleeDesc::import(uint32_t instanceDataOffset) {
342 CalleeDesc c;
343 c.which_ = Import;
344 c.u.import.instanceDataOffset_ = instanceDataOffset;
345 return c;
346 }
347 CalleeDesc CalleeDesc::wasmTable(const CodeMetadata& codeMeta,
348 const TableDesc& desc, uint32_t tableIndex,
349 CallIndirectId callIndirectId) {
350 CalleeDesc c;
351 c.which_ = WasmTable;
352 c.u.table.instanceDataOffset_ =
353 codeMeta.offsetOfTableInstanceData(tableIndex);
354 c.u.table.minLength_ = desc.initialLength();
355 c.u.table.maxLength_ = desc.maximumLength();
356 c.u.table.callIndirectId_ = callIndirectId;
357 return c;
358 }
359 CalleeDesc CalleeDesc::asmJSTable(const CodeMetadata& codeMeta,
360 uint32_t tableIndex) {
361 CalleeDesc c;
362 c.which_ = AsmJSTable;
363 c.u.table.instanceDataOffset_ =
364 codeMeta.offsetOfTableInstanceData(tableIndex);
365 return c;
366 }
367 CalleeDesc CalleeDesc::builtin(SymbolicAddress callee) {
368 CalleeDesc c;
369 c.which_ = Builtin;
370 c.u.builtin_ = callee;
371 return c;
372 }
373 CalleeDesc CalleeDesc::builtinInstanceMethod(SymbolicAddress callee) {
374 CalleeDesc c;
375 c.which_ = BuiltinInstanceMethod;
376 c.u.builtin_ = callee;
377 return c;
378 }
379 CalleeDesc CalleeDesc::wasmFuncRef() {
380 CalleeDesc c;
381 c.which_ = FuncRef;
382 return c;
383 }
384
385 void CompileStats::merge(const CompileStats& other) {
386 MOZ_ASSERT(&other != this);
387 numFuncs += other.numFuncs;
388 bytecodeSize += other.bytecodeSize;
389 inlinedDirectCallCount += other.inlinedDirectCallCount;
390 inlinedCallRefCount += other.inlinedCallRefCount;
391 inlinedDirectCallBytecodeSize += other.inlinedDirectCallBytecodeSize;
392 inlinedCallRefBytecodeSize += other.inlinedCallRefBytecodeSize;
393 numInliningBudgetOverruns += other.numInliningBudgetOverruns;
394 numLargeFunctionBackoffs += other.numLargeFunctionBackoffs;
395 }
396
397 void CompileAndLinkStats::merge(const CompileAndLinkStats& other) {
398 MOZ_ASSERT(&other != this);
399 CompileStats::merge(other);
400 codeBytesMapped += other.codeBytesMapped;
401 codeBytesUsed += other.codeBytesUsed;
402 }
403
404 void CompileAndLinkStats::print() const {
405 #ifdef JS_JITSPEW
406 // To see the statistics printed here:
407 // * configure with --enable-jitspew or --enable-debug
408 // * run with MOZ_LOG=wasmPerf:3
409 // * this works for both JS builds and full browser builds
410 JS_LOG(wasmPerf, Info, " %7zu functions compiled", numFuncs);
411 JS_LOG(wasmPerf, Info, " %7zu bytecode bytes compiled", bytecodeSize);
412 JS_LOG(wasmPerf, Info, " %7zu direct-calls inlined",
413 inlinedDirectCallCount);
414 JS_LOG(wasmPerf, Info, " %7zu call_ref-calls inlined",
415 inlinedCallRefCount);
416 JS_LOG(wasmPerf, Info, " %7zu direct-call bytecodes inlined",
417 inlinedDirectCallBytecodeSize);
418 JS_LOG(wasmPerf, Info, " %7zu call_ref-call bytecodes inlined",
419 inlinedCallRefBytecodeSize);
420 JS_LOG(wasmPerf, Info, " %7zu functions overran inlining budget",
421 numInliningBudgetOverruns);
422 JS_LOG(wasmPerf, Info, " %7zu functions needed large-function backoff",
423 numLargeFunctionBackoffs);
424 JS_LOG(wasmPerf, Info, " %7zu bytes mmap'd for code storage",
425 codeBytesMapped);
426 JS_LOG(wasmPerf, Info, " %7zu bytes actually used for code storage",
427 codeBytesUsed);
428
429 size_t inlinedTotalBytecodeSize =
430 inlinedDirectCallBytecodeSize + inlinedCallRefBytecodeSize;
431
432 // This value will be 0.0 if inlining did not cause any code expansion. A
433 // value of 1.0 means inlining doubled the total amount of bytecode, 2.0
434 // means tripled it, etc. Take care not to compute 0.0 / 0.0 as that is,
435 // confusingly, -nan.
436 float inliningExpansion =
437 inlinedTotalBytecodeSize == 0
438 ? 0.0
439 : float(inlinedTotalBytecodeSize) / float(bytecodeSize);
440
441 // This is always between 0.0 and 1.0.
442 float codeSpaceUseRatio =
443 codeBytesUsed == 0 ? 0.0 : float(codeBytesUsed) / float(codeBytesMapped);
444
445 JS_LOG(wasmPerf, Info, " %5.1f%% bytecode expansion caused by inlining",
446 inliningExpansion * 100.0);
447 JS_LOG(wasmPerf, Info, " %4.1f%% of mapped code space used",
448 codeSpaceUseRatio * 100.0);
449 #endif
450 }