Debian Codegraph @

js/src/jit/CodeGenerator.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 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #ifndef jit_CodeGenerator_h
8 #define jit_CodeGenerator_h
9
10 #include "jit/PerfSpewer.h"
11 #include "js/Prefs.h"
12 #include "js/ScalarType.h" // js::Scalar::Type
13
14 #if defined(JS_CODEGEN_X86)
15 # include "jit/x86/CodeGenerator-x86.h"
16 #elif defined(JS_CODEGEN_X64)
17 # include "jit/x64/CodeGenerator-x64.h"
18 #elif defined(JS_CODEGEN_ARM)
19 # include "jit/arm/CodeGenerator-arm.h"
20 #elif defined(JS_CODEGEN_ARM64)
21 # include "jit/arm64/CodeGenerator-arm64.h"
22 #elif defined(JS_CODEGEN_MIPS64)
23 # include "jit/mips64/CodeGenerator-mips64.h"
24 #elif defined(JS_CODEGEN_LOONG64)
25 # include "jit/loong64/CodeGenerator-loong64.h"
26 #elif defined(JS_CODEGEN_RISCV64)
27 # include "jit/riscv64/CodeGenerator-riscv64.h"
28 #elif defined(JS_CODEGEN_WASM32)
29 # include "jit/wasm32/CodeGenerator-wasm32.h"
30 #elif defined(JS_CODEGEN_NONE)
31 # include "jit/none/CodeGenerator-none.h"
32 #else
33 # error "Unknown architecture!"
34 #endif
35
36 namespace js {
37
38 namespace wasm {
39 class Decoder;
40 class StackMaps;
41 } // namespace wasm
42
43 namespace jit {
44
45 class WarpSnapshot;
46
47 template <typename Fn, Fn fn, class ArgSeq, class StoreOutputTo>
48 class OutOfLineCallVM;
49
50 class OutOfLineTestObject;
51 class OutOfLineICFallback;
52 class OutOfLineCallPostWriteBarrier;
53 class OutOfLineCallPostWriteElementBarrier;
54
55 class CodeGenerator final : public CodeGeneratorSpecific {
56 // Warp snapshot. This is nullptr for Wasm compilations.
57 const WarpSnapshot* snapshot_ = nullptr;
58
59 [[nodiscard]] bool generateBody();
60
61 ConstantOrRegister toConstantOrRegister(LInstruction* lir, size_t n,
62 MIRType type);
63
64 #ifdef CHECK_OSIPOINT_REGISTERS
65 void resetOsiPointRegs(LSafepoint* safepoint);
66 bool shouldVerifyOsiPointRegs(LSafepoint* safepoint);
67 void verifyOsiPointRegs(LSafepoint* safepoint);
68 #endif
69
70 void callVMInternal(VMFunctionId id, LInstruction* ins);
71
72 template <typename Fn, Fn fn>
73 void callVM(LInstruction* ins);
74
75 template <typename Fn, Fn fn, class ArgSeq, class StoreOutputTo>
76 inline OutOfLineCode* oolCallVM(LInstruction* ins, const ArgSeq& args,
77 const StoreOutputTo& out);
78
79 template <typename LCallIns>
80 void emitCallNative(LCallIns* call, JSNative native, Register argContextReg,
81 Register argUintNReg, Register argVpReg, Register tempReg,
82 uint32_t unusedStack);
83
84 template <typename LCallIns>
85 void emitCallNative(LCallIns* call, JSNative native);
86
87 public:
88 CodeGenerator(MIRGenerator* gen, LIRGraph* graph,
89 MacroAssembler* masm = nullptr,
90 const wasm::CodeMetadata* wasmCodeMeta = nullptr);
91 ~CodeGenerator();
92
93 [[nodiscard]] bool generate(const WarpSnapshot* snapshot);
94 [[nodiscard]] bool generateWasm(wasm::CallIndirectId callIndirectId,
95 const wasm::TrapSiteDesc& entryTrapSiteDesc,
96 const wasm::ArgTypeVector& argTys,
97 const RegisterOffsets& trapExitLayout,
98 size_t trapExitLayoutNumWords,
99 wasm::FuncOffsets* offsets,
100 wasm::StackMaps* stackMaps,
101 wasm::Decoder* decoder,
102 jit::IonPerfSpewer* spewer);
103
104 [[nodiscard]] bool link(JSContext* cx);
105
106 void emitOOLTestObject(Register objreg, Label* ifTruthy, Label* ifFalsy,
107 Register scratch);
108
109 void emitTypeOfCheck(JSValueType type, Register tag, Register output,
110 Label* done, Label* oolObject);
111 void emitTypeOfJSType(JSValueType type, Register output);
112 void emitTypeOfObject(Register obj, Register output, Label* done);
113 void emitTypeOfIsObject(MTypeOfIs* mir, Register obj, Register output,
114 Label* success, Label* fail, Label* slowCheck);
115 void emitTypeOfIsObjectOOL(MTypeOfIs* mir, Register obj, Register output);
116
117 template <typename Fn, Fn fn, class ArgSeq, class StoreOutputTo>
118 void visitOutOfLineCallVM(
119 OutOfLineCallVM<Fn, fn, ArgSeq, StoreOutputTo>* ool);
120
121 void emitIsCallableOOL(Register object, Register output);
122
123 void emitResumableWasmTrapOOL(LInstruction* lir, size_t framePushed,
124 const wasm::TrapSiteDesc& trapSiteDesc,
125 wasm::Trap trap);
126
127 void visitOutOfLineICFallback(OutOfLineICFallback* ool);
128
129 void visitOutOfLineCallPostWriteBarrier(OutOfLineCallPostWriteBarrier* ool);
130 void visitOutOfLineCallPostWriteElementBarrier(
131 OutOfLineCallPostWriteElementBarrier* ool);
132
133 void callWasmStructAllocFun(LInstruction* lir, wasm::SymbolicAddress fun,
134 Register typeDefData, Register allocSite,
135 Register output,
136 const wasm::TrapSiteDesc& trapSiteDesc);
137
138 void callWasmArrayAllocFun(LInstruction* lir, wasm::SymbolicAddress fun,
139 Register numElements, Register typeDefData,
140 Register allocSite, Register output,
141 const wasm::TrapSiteDesc& trapSiteDesc);
142
143 #ifdef ENABLE_WASM_JSPI
144 void callWasmUpdateSuspenderState(wasm::UpdateSuspenderStateAction kind,
145 Register suspender, Register temp);
146 // Stack switching trampoline requires two arguments (suspender and data) to
147 // be passed. The function prepares stack and registers according Wasm ABI.
148 void prepareWasmStackSwitchTrampolineCall(Register suspender, Register data);
149 #endif
150
151 void setCompilationTime(mozilla::TimeDuration duration) {
152 compileTime_ = duration;
153 }
154 mozilla::TimeDuration getCompilationTime() const { return compileTime_; }
155
156 private:
157 void emitPostWriteBarrier(const LAllocation* obj);
158 void emitPostWriteBarrier(Register objreg);
159 void emitPostWriteBarrierS(Address address, Register prev, Register next);
160
161 void emitElementPostWriteBarrier(MInstruction* mir,
162 const LiveRegisterSet& liveVolatileRegs,
163 Register obj, const LAllocation* index,
164 Register scratch,
165 const ConstantOrRegister& val,
166 int32_t indexDiff = 0);
167
168 template <class LPostBarrierType, MIRType nurseryType>
169 void visitPostWriteBarrierCommon(LPostBarrierType* lir, OutOfLineCode* ool);
170 template <class LPostBarrierType>
171 void visitPostWriteBarrierCommonV(LPostBarrierType* lir, OutOfLineCode* ool);
172
173 void emitCallInvokeFunction(LInstruction* call, Register callereg,
174 bool isConstructing, bool ignoresReturnValue,
175 uint32_t argc, uint32_t unusedStack);
176 template <typename T>
177 void emitApplyGeneric(T* apply);
178 template <typename T>
179 void emitCallInvokeFunction(T* apply);
180 void emitAllocateSpaceForApply(Register argcreg, Register scratch);
181 void emitAllocateSpaceForConstructAndPushNewTarget(
182 Register argcreg, Register newTargetAndScratch);
183 void emitCopyValuesForApply(Register argvSrcBase, Register argvIndex,
184 Register copyreg, size_t argvSrcOffset,
185 size_t argvDstOffset);
186 void emitRestoreStackPointerFromFP();
187 void emitPushArguments(Register argcreg, Register scratch, Register copyreg,
188 uint32_t extraFormals);
189 void emitPushArrayAsArguments(Register tmpArgc, Register srcBaseAndArgc,
190 Register scratch, size_t argvSrcOffset);
191 void emitPushArguments(LApplyArgsGeneric* apply);
192 void emitPushArguments(LApplyArgsObj* apply);
193 void emitPushArguments(LApplyArrayGeneric* apply);
194 void emitPushArguments(LConstructArgsGeneric* construct);
195 void emitPushArguments(LConstructArrayGeneric* construct);
196
197 template <typename T>
198 void emitApplyNative(T* apply);
199 template <typename T>
200 void emitAlignStackForApplyNative(T* apply, Register argc);
201 template <typename T>
202 void emitPushNativeArguments(T* apply);
203 template <typename T>
204 void emitPushArrayAsNativeArguments(T* apply);
205 void emitPushArguments(LApplyArgsNative* apply);
206 void emitPushArguments(LApplyArgsObjNative* apply);
207 void emitPushArguments(LApplyArrayNative* apply);
208 void emitPushArguments(LConstructArgsNative* construct);
209 void emitPushArguments(LConstructArrayNative* construct);
210
211 template <typename T>
212 void emitApplyArgsGuard(T* apply);
213
214 template <typename T>
215 void emitApplyArgsObjGuard(T* apply);
216
217 template <typename T>
218 void emitApplyArrayGuard(T* apply);
219
220 template <class GetInlinedArgument>
221 void emitGetInlinedArgument(GetInlinedArgument* lir, Register index,
222 ValueOperand output);
223
224 void emitMaybeAtomizeSlot(LInstruction* ins, Register stringReg,
225 Address slotAddr, TypedOrValueRegister dest);
226
227 using RegisterOrInt32 = mozilla::Variant<Register, int32_t>;
228
229 static RegisterOrInt32 ToRegisterOrInt32(const LAllocation* allocation);
230
231 #ifdef DEBUG
232 void emitAssertArgumentsSliceBounds(const RegisterOrInt32& begin,
233 const RegisterOrInt32& count,
234 Register numActualArgs);
235 #endif
236
237 template <class ArgumentsSlice>
238 void emitNewArray(ArgumentsSlice* lir, const RegisterOrInt32& count,
239 Register output, Register temp);
240
241 void visitNewArrayCallVM(LNewArray* lir);
242 void visitNewObjectVMCall(LNewObject* lir);
243
244 void emitConcat(LInstruction* lir, Register lhs, Register rhs,
245 Register output);
246
247 void emitInstanceOf(LInstruction* ins, Register protoReg);
248
249 #ifdef DEBUG
250 void emitAssertResultV(const ValueOperand output, const MDefinition* mir);
251 void emitAssertGCThingResult(Register input, const MDefinition* mir);
252 #endif
253
254 #ifdef DEBUG
255 void emitDebugForceBailing(LInstruction* lir);
256 #endif
257
258 IonScriptCounts* extractScriptCounts() {
259 IonScriptCounts* counts = scriptCounts_;
260 scriptCounts_ = nullptr; // prevent delete in dtor
261 return counts;
262 }
263
264 void addGetPropertyCache(LInstruction* ins, LiveRegisterSet liveRegs,
265 TypedOrValueRegister value,
266 const ConstantOrRegister& id, ValueOperand output);
267 void addSetPropertyCache(LInstruction* ins, LiveRegisterSet liveRegs,
268 Register objReg, Register temp,
269 const ConstantOrRegister& id,
270 const ConstantOrRegister& value, bool strict);
271
272 template <class IteratorObject, class TableObject>
273 void emitGetNextEntryForIterator(LGetNextEntryForIterator* lir);
274
275 template <class TableObject>
276 void emitLoadIteratorValues(Register result, Register temp, Register front);
277
278 void emitStringToInt64(LInstruction* lir, Register input, Register64 output);
279
280 OutOfLineCode* createBigIntOutOfLine(LInstruction* lir, Scalar::Type type,
281 Register64 input, Register output);
282
283 void emitCreateBigInt(LInstruction* lir, Scalar::Type type, Register64 input,
284 Register output, Register maybeTemp,
285 Register64 maybeTemp64 = Register64::Invalid());
286
287 void emitCallMegamorphicGetter(LInstruction* lir,
288 ValueOperand accessorAndOutput, Register obj,
289 Register calleeScratch, Register argcScratch,
290 Label* nullGetter);
291
292 template <size_t NumDefs>
293 void emitIonToWasmCallBase(LIonToWasmCallBase<NumDefs>* lir);
294
295 IonScriptCounts* maybeCreateScriptCounts();
296
297 template <typename InstructionWithMaybeTrapSite, class AddressOrBaseIndex>
298 void emitWasmValueLoad(InstructionWithMaybeTrapSite* ins, MIRType type,
299 MWideningOp wideningOp, AddressOrBaseIndex addr,
300 AnyRegister dst);
301 template <typename InstructionWithMaybeTrapSite, class AddressOrBaseIndex>
302 void emitWasmValueStore(InstructionWithMaybeTrapSite* ins, MIRType type,
303 MNarrowingOp narrowingOp, AnyRegister src,
304 AddressOrBaseIndex addr);
305
306 void testValueTruthyForType(JSValueType type, ScratchTagScope& tag,
307 const ValueOperand& value, Register tempToUnbox,
308 Register temp, FloatRegister floatTemp,
309 Label* ifTruthy, Label* ifFalsy,
310 OutOfLineTestObject* ool, bool skipTypeTest);
311
312 // Test whether value is truthy or not and jump to the corresponding label.
313 // The control flow falls through when the object is truthy, as an
314 // optimization.
315 void testValueTruthy(const ValueOperand& value, Register tempToUnbox,
316 Register temp, FloatRegister floatTemp,
317 const TypeDataList& observedTypes, Label* ifTruthy,
318 Label* ifFalsy, OutOfLineTestObject* ool);
319
320 // This function behaves like testObjectEmulatesUndefined with the exception
321 // that it can choose to let control flow fall through when the object
322 // doesn't emulate undefined, as an optimization. Use the regular
323 // testObjectEmulatesUndefined when it's required to branch to one of the
324 // two labels.
325 void testObjectEmulatesUndefinedKernel(Register objreg,
326 Label* ifEmulatesUndefined,
327 Label* ifDoesntEmulateUndefined,
328 Register scratch,
329 OutOfLineTestObject* ool);
330
331 // Test whether an object emulates |undefined|. If it does, jump to
332 // |ifEmulatesUndefined|; the caller is responsible for binding this label.
333 // If it doesn't, fall through; the label |ifDoesntEmulateUndefined| (which
334 // must be initially unbound) will be bound at this point.
335 void branchTestObjectEmulatesUndefined(Register objreg,
336 Label* ifEmulatesUndefined,
337 Label* ifDoesntEmulateUndefined,
338 Register scratch,
339 OutOfLineTestObject* ool);
340
341 // Test whether an object emulates |undefined|, and jump to the
342 // corresponding label.
343 //
344 // This method should be used when subsequent code can't be laid out in a
345 // straight line; if it can, branchTest* should be used instead.
346 void testObjectEmulatesUndefined(Register objreg, Label* ifEmulatesUndefined,
347 Label* ifDoesntEmulateUndefined,
348 Register scratch, OutOfLineTestObject* ool);
349
350 void emitStoreElementTyped(const LAllocation* value, MIRType valueType,
351 Register elements, const LAllocation* index);
352
353 // Bailout if an element about to be written to is a hole.
354 void emitStoreHoleCheck(Register elements, const LAllocation* index,
355 LSnapshot* snapshot);
356
357 void emitAssertRangeI(MIRType type, const Range* r, Register input);
358 void emitAssertRangeD(const Range* r, FloatRegister input,
359 FloatRegister temp);
360
361 void maybeEmitGlobalBarrierCheck(const LAllocation* maybeGlobal,
362 OutOfLineCode* ool);
363
364 void incrementWarmUpCounter(AbsoluteAddress warmUpCount, JSScript* script,
365 Register tmp);
366
367 Vector<CodeOffset, 0, JitAllocPolicy> ionScriptLabels_;
368
369 // Used to bake in a pointer into the IonScript's list of nursery objects, for
370 // MNurseryObject codegen.
371 struct NurseryObjectLabel {
372 CodeOffset offset;
373 uint32_t nurseryIndex;
374 NurseryObjectLabel(CodeOffset offset, uint32_t nurseryIndex)
375 : offset(offset), nurseryIndex(nurseryIndex) {}
376 };
377 Vector<NurseryObjectLabel, 0, JitAllocPolicy> ionNurseryObjectLabels_;
378
379 void branchIfInvalidated(Register temp, Label* invalidated);
380
381 #ifdef DEBUG
382 void emitDebugResultChecks(LInstruction* ins);
383 void emitGCThingResultChecks(LInstruction* lir, MDefinition* mir);
384 void emitValueResultChecks(LInstruction* lir, MDefinition* mir);
385 void emitWasmAnyrefResultChecks(LInstruction* lir, MDefinition* mir);
386 #endif
387
388 // Script counts created during code generation.
389 IonScriptCounts* scriptCounts_;
390
391 IonPerfSpewer perfSpewer_;
392
393 // Total Ion compilation time.
394 mozilla::TimeDuration compileTime_;
395
396 #ifdef FUZZING_JS_FUZZILLI
397 void emitFuzzilliHashObject(LInstruction* lir, Register obj, Register output);
398 void emitFuzzilliHashBigInt(LInstruction* lir, Register bigInt,
399 Register output);
400 #endif
401
402 #define LIR_OP(op) void visit##op(L##op* ins);
403 LIR_OPCODE_LIST(LIR_OP)
404 #undef LIR_OP
405
406 // In debug mode, we need to validate that we've not made a mistake with the
407 // fuse.
408 void assertObjectDoesNotEmulateUndefined(Register input, Register temp,
409 const MInstruction* mir);
410
411 // Register a dependency on the HasSeenObjectEmulateUndefined fuse.
412 bool addHasSeenObjectEmulateUndefinedFuseDependency();
413
414 // Register a dependency on the HasSeenArrayExceedsInt32Length fuse.
415 bool addHasSeenArrayExceedsInt32LengthFuseDependency();
416
417 // Return true if the fuse is intact, and if the fuse is intact note the
418 // dependency
419 bool hasSeenObjectEmulateUndefinedFuseIntactAndDependencyNoted() {
420 bool intact = gen->outerInfo().hasSeenObjectEmulateUndefinedFuseIntact();
421 if (intact) {
422 bool tryToAdd = addHasSeenObjectEmulateUndefinedFuseDependency();
423 // If we oom, just pretend that the fuse is popped.
424 return tryToAdd;
425 }
426 return false;
427 }
428
429 bool hasSeenArrayExceedsInt32LengthFuseIntactAndDependencyNoted() {
430 bool intact = gen->outerInfo().hasSeenArrayExceedsInt32LengthFuseIntact();
431 if (intact) {
432 return addHasSeenArrayExceedsInt32LengthFuseDependency();
433 }
434 return false;
435 }
436 };
437
438 } // namespace jit
439 } // namespace js
440
441 #endif /* jit_CodeGenerator_h */