Debian Codegraph @

js/src/jit/shared/CodeGenerator-shared.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_shared_CodeGenerator_shared_h
8 #define jit_shared_CodeGenerator_shared_h
9
10 #include "mozilla/Alignment.h"
11
12 #include <utility>
13
14 #include "jit/InlineList.h"
15 #include "jit/InlineScriptTree.h"
16 #include "jit/JitcodeMap.h"
17 #include "jit/LIR.h"
18 #include "jit/MacroAssembler.h"
19 #include "jit/MIRGenerator.h"
20 #include "jit/MIRGraph.h"
21 #include "jit/SafepointIndex.h"
22 #include "jit/Safepoints.h"
23 #include "jit/Snapshots.h"
24
25 namespace js {
26 namespace jit {
27
28 class OutOfLineCode;
29 class CodeGenerator;
30 class MacroAssembler;
31 class IonIC;
32
33 class OutOfLineTruncateSlow;
34
35 class CodeGeneratorShared : public LElementVisitor {
36 AppendOnlyList<OutOfLineCode> outOfLineCode_;
37
38 MacroAssembler& ensureMasm(MacroAssembler* masm, TempAllocator& alloc,
39 CompileRealm* realm);
40 mozilla::Maybe<OffThreadMacroAssembler> maybeMasm_;
41
42 public:
43 MacroAssembler& masm;
44
45 protected:
46 MIRGenerator* gen;
47 LIRGraph& graph;
48 const wasm::CodeMetadata* wasmCodeMeta_;
49 LBlock* current;
50 SnapshotWriter snapshots_;
51 RecoverWriter recovers_;
52 #ifdef DEBUG
53 uint32_t pushedArgs_;
54 #endif
55 uint32_t lastOsiPointOffset_;
56 SafepointWriter safepoints_;
57 Label invalidate_;
58 CodeOffset invalidateEpilogueData_;
59
60 // Label for the common return path.
61 NonAssertingLabel returnLabel_;
62
63 // Amount of bytes allocated for incoming args. Used for Wasm return calls.
64 uint32_t inboundStackArgBytes_;
65
66 js::Vector<CodegenSafepointIndex, 0, JitAllocPolicy> safepointIndices_;
67 js::Vector<OsiIndex, 0, BackgroundSystemAllocPolicy> osiIndices_;
68
69 // Allocated data space needed at runtime.
70 js::Vector<uint8_t, 0, BackgroundSystemAllocPolicy> runtimeData_;
71
72 // Vector mapping each IC index to its offset in runtimeData_.
73 js::Vector<uint32_t, 0, BackgroundSystemAllocPolicy> icList_;
74
75 // IC data we need at compile-time. Discarded after creating the IonScript.
76 struct CompileTimeICInfo {
77 CodeOffset icOffsetForJump;
78 CodeOffset icOffsetForPush;
79 };
80 js::Vector<CompileTimeICInfo, 0, BackgroundSystemAllocPolicy> icInfo_;
81
82 protected:
83 js::Vector<NativeToBytecode, 0, BackgroundSystemAllocPolicy>
84 nativeToBytecodeList_;
85 UniquePtr<uint8_t> nativeToBytecodeMap_;
86 uint32_t nativeToBytecodeMapSize_;
87 uint32_t nativeToBytecodeTableOffset_;
88
89 bool isProfilerInstrumentationEnabled() {
90 return gen->isProfilerInstrumentationEnabled();
91 }
92
93 gc::Heap initialStringHeap() const { return gen->initialStringHeap(); }
94 gc::Heap initialBigIntHeap() const { return gen->initialBigIntHeap(); }
95
96 protected:
97 // The offset of the first instruction of the OSR entry block from the
98 // beginning of the code buffer.
99 mozilla::Maybe<size_t> osrEntryOffset_ = {};
100
101 TempAllocator& alloc() const { return graph.mir().alloc(); }
102
103 void setOsrEntryOffset(size_t offset) { osrEntryOffset_.emplace(offset); }
104
105 size_t getOsrEntryOffset() const {
106 MOZ_RELEASE_ASSERT(osrEntryOffset_.isSome());
107 return *osrEntryOffset_;
108 }
109
110 using SafepointIndices =
111 js::Vector<CodegenSafepointIndex, 8, SystemAllocPolicy>;
112
113 protected:
114 #ifdef CHECK_OSIPOINT_REGISTERS
115 // See JitOptions.checkOsiPointRegisters. We set this here to avoid
116 // races when enableOsiPointRegisterChecks is called while we're generating
117 // code off-thread.
118 bool checkOsiPointRegisters;
119 #endif
120
121 // The initial size of the frame in bytes. These are bytes beyond the
122 // constant header present for every Ion frame, used for pre-determined
123 // spills.
124 uint32_t frameDepth_;
125
126 // Offset in bytes to the incoming arguments, relative to the frame pointer.
127 uint32_t offsetOfArgsFromFP_ = 0;
128
129 // Offset in bytes of the stack region reserved for passed argument Values.
130 uint32_t offsetOfPassedArgSlots_ = 0;
131
132 // For argument construction for calls. Argslots are Value-sized.
133 inline Address AddressOfPassedArg(uint32_t slot) const;
134 inline uint32_t UnusedStackBytesForCall(uint32_t numArgSlots) const;
135
136 template <BaseRegForAddress Base = BaseRegForAddress::Default>
137 inline Address ToAddress(const LAllocation& a) const;
138
139 template <BaseRegForAddress Base = BaseRegForAddress::Default>
140 inline Address ToAddress(const LAllocation* a) const;
141
142 template <BaseRegForAddress Base = BaseRegForAddress::Default>
143 inline Address ToAddress(const LInt64Allocation& a) const;
144
145 static inline Address ToAddress(Register elements, const LAllocation* index,
146 Scalar::Type type,
147 int32_t offsetAdjustment = 0);
148
149 uint32_t frameSize() const { return frameDepth_; }
150
151 protected:
152 bool addNativeToBytecodeEntry(const BytecodeSite* site);
153 void dumpNativeToBytecodeEntries();
154 void dumpNativeToBytecodeEntry(uint32_t idx);
155
156 public:
157 MIRGenerator& mirGen() const { return *gen; }
158 const wasm::CodeMetadata* wasmCodeMeta() const { return wasmCodeMeta_; }
159
160 // When appending to runtimeData_, the vector might realloc, leaving pointers
161 // int the origianl vector stale and unusable. DataPtr acts like a pointer,
162 // but allows safety in the face of potentially realloc'ing vector appends.
163 friend class DataPtr;
164 template <typename T>
165 class DataPtr {
166 CodeGeneratorShared* cg_;
167 size_t index_;
168
169 T* lookup() { return reinterpret_cast<T*>(&cg_->runtimeData_[index_]); }
170
171 public:
172 DataPtr(CodeGeneratorShared* cg, size_t index) : cg_(cg), index_(index) {}
173
174 T* operator->() { return lookup(); }
175 T* operator*() { return lookup(); }
176 };
177
178 protected:
179 [[nodiscard]] bool allocateData(size_t size, size_t* offset) {
180 MOZ_ASSERT(size % sizeof(void*) == 0);
181 *offset = runtimeData_.length();
182 masm.propagateOOM(runtimeData_.appendN(0, size));
183 return !masm.oom();
184 }
185
186 template <typename T>
187 inline size_t allocateIC(const T& cache) {
188 static_assert(std::is_base_of_v<IonIC, T>, "T must inherit from IonIC");
189 size_t index;
190 masm.propagateOOM(
191 allocateData(sizeof(mozilla::AlignedStorage2<T>), &index));
192 masm.propagateOOM(icList_.append(index));
193 masm.propagateOOM(icInfo_.append(CompileTimeICInfo()));
194 if (masm.oom()) {
195 return SIZE_MAX;
196 }
197 // Use the copy constructor on the allocated space.
198 MOZ_ASSERT(index == icList_.back());
199 new (&runtimeData_[index]) T(cache);
200 return index;
201 }
202
203 protected:
204 // Encodes an LSnapshot into the compressed snapshot buffer.
205 void encode(LRecoverInfo* recover);
206 void encode(LSnapshot* snapshot);
207 void encodeAllocation(LSnapshot* snapshot, MDefinition* def,
208 uint32_t* startIndex, bool hasSideEffects);
209
210 // Encode all encountered safepoints in CG-order, and resolve |indices| for
211 // safepoint offsets.
212 bool encodeSafepoints();
213
214 // Fixup offsets of native-to-bytecode map.
215 bool createNativeToBytecodeScriptList(JSContext* cx,
216 IonEntry::ScriptList& scripts);
217 bool generateCompactNativeToBytecodeMap(JSContext* cx, JitCode* code,
218 IonEntry::ScriptList& scripts);
219 void verifyCompactNativeToBytecodeMap(JitCode* code,
220 const IonEntry::ScriptList& scripts,
221 uint32_t numRegions);
222
223 // Mark the safepoint on |ins| as corresponding to the current assembler
224 // location. The location should be just after a call.
225 void markSafepoint(LInstruction* ins);
226 void markSafepointAt(uint32_t offset, LInstruction* ins);
227
228 // Mark the OSI point |ins| as corresponding to the current
229 // assembler location inside the |osiIndices_|. Return the assembler
230 // location for the OSI point return location.
231 uint32_t markOsiPoint(LOsiPoint* ins);
232
233 // Ensure that there is enough room between the last OSI point and the
234 // current instruction, such that:
235 // (1) Invalidation will not overwrite the current instruction, and
236 // (2) Overwriting the current instruction will not overwrite
237 // an invalidation marker.
238 void ensureOsiSpace();
239
240 OutOfLineCode* oolTruncateDouble(
241 FloatRegister src, Register dest, MInstruction* mir,
242 wasm::BytecodeOffset callOffset = wasm::BytecodeOffset());
243 void emitTruncateDouble(FloatRegister src, Register dest, MInstruction* mir);
244 void emitTruncateFloat32(FloatRegister src, Register dest, MInstruction* mir);
245
246 void emitPreBarrier(Register elements, const LAllocation* index);
247 void emitPreBarrier(Address address);
248
249 // We don't emit code for trivial blocks, so if we want to branch to the
250 // given block, and it's trivial, return the ultimate block we should
251 // actually branch directly to.
252 MBasicBlock* skipTrivialBlocks(MBasicBlock* block) {
253 while (block->lir()->isTrivial()) {
254 LGoto* ins = block->lir()->rbegin()->toGoto();
255 MOZ_ASSERT(ins->numSuccessors() == 1);
256 block = ins->getSuccessor(0);
257 }
258 return block;
259 }
260
261 // Test whether the given block can be reached via fallthrough from the
262 // current block.
263 inline bool isNextBlock(LBlock* block) {
264 uint32_t target = skipTrivialBlocks(block->mir())->id();
265 uint32_t i = current->mir()->id() + 1;
266 if (target < i) {
267 return false;
268 }
269 // Trivial blocks can be crossed via fallthrough.
270 for (; i != target; ++i) {
271 if (!graph.getBlock(i)->isTrivial()) {
272 return false;
273 }
274 }
275 return true;
276 }
277
278 protected:
279 // Save and restore all volatile registers to/from the stack, excluding the
280 // specified register(s), before a function call made using callWithABI and
281 // after storing the function call's return value to an output register.
282 // (The only registers that don't need to be saved/restored are 1) the
283 // temporary register used to store the return value of the function call,
284 // if there is one [otherwise that stored value would be overwritten]; and
285 // 2) temporary registers whose values aren't needed in the rest of the LIR
286 // instruction [this is purely an optimization]. All other volatiles must
287 // be saved and restored in case future LIR instructions need those values.)
288 void saveVolatile(Register output) {
289 LiveRegisterSet regs(RegisterSet::Volatile());
290 regs.takeUnchecked(output);
291 masm.PushRegsInMask(regs);
292 }
293 void restoreVolatile(Register output) {
294 LiveRegisterSet regs(RegisterSet::Volatile());
295 regs.takeUnchecked(output);
296 masm.PopRegsInMask(regs);
297 }
298 void saveVolatile(FloatRegister output) {
299 LiveRegisterSet regs(RegisterSet::Volatile());
300 regs.takeUnchecked(output);
301 masm.PushRegsInMask(regs);
302 }
303 void restoreVolatile(FloatRegister output) {
304 LiveRegisterSet regs(RegisterSet::Volatile());
305 regs.takeUnchecked(output);
306 masm.PopRegsInMask(regs);
307 }
308 void saveVolatile(LiveRegisterSet temps) {
309 masm.PushRegsInMask(LiveRegisterSet(RegisterSet::VolatileNot(temps.set())));
310 }
311 void restoreVolatile(LiveRegisterSet temps) {
312 masm.PopRegsInMask(LiveRegisterSet(RegisterSet::VolatileNot(temps.set())));
313 }
314 void saveVolatile() {
315 masm.PushRegsInMask(LiveRegisterSet(RegisterSet::Volatile()));
316 }
317 void restoreVolatile() {
318 masm.PopRegsInMask(LiveRegisterSet(RegisterSet::Volatile()));
319 }
320
321 // These functions have to be called before and after any callVM and before
322 // any modifications of the stack. Modification of the stack made after
323 // these calls should update the framePushed variable, needed by the exit
324 // frame produced by callVM.
325 inline void saveLive(LInstruction* ins);
326 inline void restoreLive(LInstruction* ins);
327 inline void restoreLiveIgnore(LInstruction* ins, LiveRegisterSet reg);
328
329 // Get/save/restore all registers that are both live and volatile.
330 inline LiveRegisterSet liveVolatileRegs(LInstruction* ins);
331 inline void saveLiveVolatile(LInstruction* ins);
332 inline void restoreLiveVolatile(LInstruction* ins);
333
334 public:
335 template <typename T>
336 void pushArg(const T& t) {
337 masm.Push(t);
338 #ifdef DEBUG
339 pushedArgs_++;
340 #endif
341 }
342
343 void pushArg(jsid id, Register temp) {
344 masm.Push(id, temp);
345 #ifdef DEBUG
346 pushedArgs_++;
347 #endif
348 }
349
350 template <typename T>
351 CodeOffset pushArgWithPatch(const T& t) {
352 #ifdef DEBUG
353 pushedArgs_++;
354 #endif
355 return masm.PushWithPatch(t);
356 }
357
358 void storePointerResultTo(Register reg) { masm.storeCallPointerResult(reg); }
359
360 void storeFloatResultTo(FloatRegister reg) { masm.storeCallFloatResult(reg); }
361
362 template <typename T>
363 void storeResultValueTo(const T& t) {
364 masm.storeCallResultValue(t);
365 }
366
367 protected:
368 void addIC(LInstruction* lir, size_t cacheIndex);
369
370 protected:
371 bool generatePrologue();
372 bool generateEpilogue();
373
374 void addOutOfLineCode(OutOfLineCode* code, const MInstruction* mir);
375 void addOutOfLineCode(OutOfLineCode* code, const BytecodeSite* site);
376 bool generateOutOfLineCode();
377
378 Label* getJumpLabelForBranch(MBasicBlock* block);
379
380 // Generate a jump to the start of the specified block. Use this in place of
381 // jumping directly to mir->lir()->label(), or use getJumpLabelForBranch()
382 // if a label to use directly is needed.
383 void jumpToBlock(MBasicBlock* mir);
384
385 // This function is not used for MIPS. MIPS has branchToBlock.
386 #if !defined(JS_CODEGEN_MIPS64)
387 void jumpToBlock(MBasicBlock* mir, Assembler::Condition cond);
388 #endif
389
390 private:
391 void generateInvalidateEpilogue();
392
393 public:
394 CodeGeneratorShared(MIRGenerator* gen, LIRGraph* graph, MacroAssembler* masm,
395 const wasm::CodeMetadata* wasmCodeMeta);
396
397 public:
398 void visitOutOfLineTruncateSlow(OutOfLineTruncateSlow* ool);
399
400 bool omitOverRecursedCheck() const;
401
402 public:
403 bool isGlobalObject(JSObject* object);
404 };
405
406 // An out-of-line path is generated at the end of the function.
407 class OutOfLineCode : public TempObject,
408 public AppendOnlyListNode<OutOfLineCode> {
409 Label entry_;
410 Label rejoin_;
411 uint32_t framePushed_;
412 const BytecodeSite* site_;
413
414 public:
415 OutOfLineCode() : framePushed_(0), site_() {}
416
417 virtual void generate(CodeGeneratorShared* codegen) = 0;
418
419 Label* entry() { return &entry_; }
420 virtual void bind(MacroAssembler* masm) { masm->bind(entry()); }
421 Label* rejoin() { return &rejoin_; }
422 void setFramePushed(uint32_t framePushed) { framePushed_ = framePushed; }
423 uint32_t framePushed() const { return framePushed_; }
424 void setBytecodeSite(const BytecodeSite* site) { site_ = site; }
425 const BytecodeSite* bytecodeSite() const { return site_; }
426 };
427
428 // An implementation of OutOfLineCode for quick and simple cases. The lambda
429 // should have the signature (OutOfLineCode& ool) -> void.
430 template <typename Func>
431 class LambdaOutOfLineCode : public OutOfLineCode {
432 Func generateFunc_;
433
434 public:
435 explicit LambdaOutOfLineCode(Func generateFunc)
436 : generateFunc_(std::move(generateFunc)) {}
437
438 void generate(CodeGeneratorShared*) override { generateFunc_(*this); }
439 };
440
441 // For OOL paths that want a specific-typed code generator.
442 template <typename T>
443 class OutOfLineCodeBase : public OutOfLineCode {
444 public:
445 virtual void generate(CodeGeneratorShared* codegen) override {
446 accept(static_cast<T*>(codegen));
447 }
448
449 public:
450 virtual void accept(T* codegen) = 0;
451 };
452
453 template <class CodeGen>
454 class OutOfLineWasmTruncateCheckBase : public OutOfLineCodeBase<CodeGen> {
455 MIRType fromType_;
456 MIRType toType_;
457 FloatRegister input_;
458 Register output_;
459 Register64 output64_;
460 TruncFlags flags_;
461 wasm::TrapSiteDesc trapSiteDesc_;
462
463 public:
464 OutOfLineWasmTruncateCheckBase(MWasmTruncateToInt32* mir, FloatRegister input,
465 Register output)
466 : fromType_(mir->input()->type()),
467 toType_(MIRType::Int32),
468 input_(input),
469 output_(output),
470 output64_(Register64::Invalid()),
471 flags_(mir->flags()),
472 trapSiteDesc_(mir->trapSiteDesc()) {}
473
474 OutOfLineWasmTruncateCheckBase(MWasmBuiltinTruncateToInt64* mir,
475 FloatRegister input, Register64 output)
476 : fromType_(mir->input()->type()),
477 toType_(MIRType::Int64),
478 input_(input),
479 output_(Register::Invalid()),
480 output64_(output),
481 flags_(mir->flags()),
482 trapSiteDesc_(mir->trapSiteDesc()) {}
483
484 OutOfLineWasmTruncateCheckBase(MWasmTruncateToInt64* mir, FloatRegister input,
485 Register64 output)
486 : fromType_(mir->input()->type()),
487 toType_(MIRType::Int64),
488 input_(input),
489 output_(Register::Invalid()),
490 output64_(output),
491 flags_(mir->flags()),
492 trapSiteDesc_(mir->trapSiteDesc()) {}
493
494 void accept(CodeGen* codegen) override {
495 codegen->visitOutOfLineWasmTruncateCheck(this);
496 }
497
498 FloatRegister input() const { return input_; }
499 Register output() const { return output_; }
500 Register64 output64() const { return output64_; }
501 MIRType toType() const { return toType_; }
502 MIRType fromType() const { return fromType_; }
503 bool isUnsigned() const { return flags_ & TRUNC_UNSIGNED; }
504 bool isSaturating() const { return flags_ & TRUNC_SATURATING; }
505 TruncFlags flags() const { return flags_; }
506 wasm::TrapSiteDesc trapSiteDesc() const { return trapSiteDesc_; }
507 };
508
509 } // namespace jit
510 } // namespace js
511
512 #endif /* jit_shared_CodeGenerator_shared_h */