LLVM 24.0.0git
RISCVFrameLowering.cpp
Go to the documentation of this file.
1//===-- RISCVFrameLowering.cpp - RISC-V Frame Information -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the RISC-V implementation of TargetFrameLowering class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "RISCVFrameLowering.h"
17#include "RISCVSubtarget.h"
28#include "llvm/MC/MCDwarf.h"
29#include "llvm/Support/LEB128.h"
30
31#include <algorithm>
32#include <cstdint>
33
34#define DEBUG_TYPE "riscv-frame"
35
36using namespace llvm;
37
39 if (ABI == RISCVABI::ABI_ILP32E)
40 return Align(4);
41 if (ABI == RISCVABI::ABI_LP64E)
42 return Align(8);
43 return Align(16);
44}
45
49 /*LocalAreaOffset=*/0,
50 /*TransientStackAlignment=*/getABIStackAlignment(STI.getTargetABI())),
51 STI(STI) {}
52
53// The register used to hold the frame pointer.
54static constexpr MCPhysReg FPReg = RISCV::X8;
55
56// The register used to hold the stack pointer.
57static constexpr MCPhysReg SPReg = RISCV::X2;
58
59// The register used to hold the return address.
60static constexpr MCPhysReg RAReg = RISCV::X1;
61
62// LIst of CSRs that are given a fixed location by save/restore libcalls or
63// Zcmp/Xqccmp Push/Pop. The order in this table indicates the order the
64// registers are saved on the stack. Zcmp uses the reverse order of save/restore
65// and Xqccmp on the stack, but this is handled when offsets are calculated.
66static const MCPhysReg FixedCSRFIMap[] = {
67 /*ra*/ RAReg, /*s0*/ FPReg, /*s1*/ RISCV::X9,
68 /*s2*/ RISCV::X18, /*s3*/ RISCV::X19, /*s4*/ RISCV::X20,
69 /*s5*/ RISCV::X21, /*s6*/ RISCV::X22, /*s7*/ RISCV::X23,
70 /*s8*/ RISCV::X24, /*s9*/ RISCV::X25, /*s10*/ RISCV::X26,
71 /*s11*/ RISCV::X27};
72
73// The number of stack bytes allocated by `QC.C.MIENTER(.NEST)` and popped by
74// `QC.C.MILEAVERET`.
75static constexpr uint64_t QCIInterruptPushAmount = 96;
76
77static const std::pair<MCPhysReg, int8_t> FixedCSRFIQCIInterruptMap[] = {
78 /* -1 is a gap for mepc/mnepc */
79 {/*fp*/ FPReg, -2},
80 /* -3 is a gap for qc.mcause */
81 {/*ra*/ RAReg, -4},
82 /* -5 is reserved */
83 {/*t0*/ RISCV::X5, -6},
84 {/*t1*/ RISCV::X6, -7},
85 {/*t2*/ RISCV::X7, -8},
86 {/*a0*/ RISCV::X10, -9},
87 {/*a1*/ RISCV::X11, -10},
88 {/*a2*/ RISCV::X12, -11},
89 {/*a3*/ RISCV::X13, -12},
90 {/*a4*/ RISCV::X14, -13},
91 {/*a5*/ RISCV::X15, -14},
92 {/*a6*/ RISCV::X16, -15},
93 {/*a7*/ RISCV::X17, -16},
94 {/*t3*/ RISCV::X28, -17},
95 {/*t4*/ RISCV::X29, -18},
96 {/*t5*/ RISCV::X30, -19},
97 {/*t6*/ RISCV::X31, -20},
98 /* -21, -22, -23, -24 are reserved */
99};
100
101/// Returns true if DWARF CFI instructions ("frame moves") should be emitted.
102static bool needsDwarfCFI(const MachineFunction &MF) {
103 return MF.needsFrameMoves();
104}
105
106// For now we use x3, a.k.a gp, as pointer to shadow call stack.
107// User should not use x3 in their asm.
110 const DebugLoc &DL) {
111 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
112 // We check Zimop instead of (Zimop || Zcmop) to determine whether HW shadow
113 // stack is available despite the fact that sspush/sspopchk both have a
114 // compressed form, because if only Zcmop is available, we would need to
115 // reserve X5 due to c.sspopchk only takes X5 and we currently do not support
116 // using X5 as the return address register.
117 // However, we can still aggressively use c.sspush x1 if zcmop is available.
118 bool HasHWShadowStack = MF.getFunction().hasFnAttribute("hw-shadow-stack") &&
119 STI.hasStdExtZimop();
120 bool HasSWShadowStack =
121 MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack);
122 if (!HasHWShadowStack && !HasSWShadowStack)
123 return;
124
125 const llvm::RISCVRegisterInfo *TRI = STI.getRegisterInfo();
126
127 // Do not save RA to the SCS if it's not saved to the regular stack,
128 // i.e. RA is not at risk of being overwritten.
129 std::vector<CalleeSavedInfo> &CSI = MF.getFrameInfo().getCalleeSavedInfo();
130 if (llvm::none_of(
131 CSI, [&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
132 return;
133
134 const RISCVInstrInfo *TII = STI.getInstrInfo();
135 if (HasHWShadowStack) {
136 BuildMI(MBB, MI, DL, TII->get(RISCV::SSPUSH))
137 .addReg(RAReg)
139 return;
140 }
141
142 Register SCSPReg = RISCVABI::getSCSPReg();
143
144 bool IsRV64 = STI.is64Bit();
145 int64_t SlotSize = STI.getXLen() / 8;
146 // Store return address to shadow call stack
147 // addi gp, gp, [4|8]
148 // s[w|d] ra, -[4|8](gp)
149 BuildMI(MBB, MI, DL, TII->get(RISCV::ADDI))
150 .addReg(SCSPReg, RegState::Define)
151 .addReg(SCSPReg)
152 .addImm(SlotSize)
154 BuildMI(MBB, MI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
155 .addReg(RAReg)
156 .addReg(SCSPReg)
157 .addImm(-SlotSize)
159
160 if (!needsDwarfCFI(MF))
161 return;
162
163 // Emit a CFI instruction that causes SlotSize to be subtracted from the value
164 // of the shadow stack pointer when unwinding past this frame.
165 char DwarfSCSReg = TRI->getDwarfRegNum(SCSPReg, /*IsEH*/ true);
166 assert(DwarfSCSReg < 32 && "SCS Register should be < 32 (X3).");
167
168 char Offset = static_cast<char>(-SlotSize) & 0x7f;
169 const char CFIInst[] = {
170 dwarf::DW_CFA_val_expression,
171 DwarfSCSReg, // register
172 2, // length
173 static_cast<char>(unsigned(dwarf::DW_OP_breg0 + DwarfSCSReg)),
174 Offset, // addend (sleb128)
175 };
176
178 .buildEscape(StringRef(CFIInst, sizeof(CFIInst)));
179}
180
183 const DebugLoc &DL) {
184 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
185 bool HasHWShadowStack = MF.getFunction().hasFnAttribute("hw-shadow-stack") &&
186 STI.hasStdExtZimop();
187 bool HasSWShadowStack =
188 MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack);
189 if (!HasHWShadowStack && !HasSWShadowStack)
190 return;
191
192 // See emitSCSPrologue() above.
193 std::vector<CalleeSavedInfo> &CSI = MF.getFrameInfo().getCalleeSavedInfo();
194 if (llvm::none_of(
195 CSI, [&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
196 return;
197
198 // The shadow call stack popchk needs to happen after cm.pop that loads ra.
199 if (MI != MBB.end() &&
200 (MI->getOpcode() == RISCV::CM_POP || MI->getOpcode() == RISCV::QC_CM_POP))
201 ++MI;
202 const RISCVInstrInfo *TII = STI.getInstrInfo();
203 if (HasHWShadowStack) {
204 BuildMI(MBB, MI, DL, TII->get(RISCV::SSPOPCHK))
205 .addReg(RAReg)
207 return;
208 }
209
210 Register SCSPReg = RISCVABI::getSCSPReg();
211
212 bool IsRV64 = STI.is64Bit();
213 int64_t SlotSize = STI.getXLen() / 8;
214 // Load return address from shadow call stack
215 // l[w|d] ra, -[4|8](gp)
216 // addi gp, gp, -[4|8]
217 BuildMI(MBB, MI, DL, TII->get(IsRV64 ? RISCV::LD : RISCV::LW))
219 .addReg(SCSPReg)
220 .addImm(-SlotSize)
222 BuildMI(MBB, MI, DL, TII->get(RISCV::ADDI))
223 .addReg(SCSPReg, RegState::Define)
224 .addReg(SCSPReg)
225 .addImm(-SlotSize)
227 if (needsDwarfCFI(MF)) {
228 // Restore the SCS pointer
230 }
231}
232
233// Insert instruction to swap mscratchsw with sp
236 const DebugLoc &DL,
237 MachineInstr::MIFlag FrameFlag) {
238 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
239
240 if (!RVFI->isSiFiveStackSwapInterrupt(MF))
241 return;
242
243 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
244 const RISCVInstrInfo *TII = STI.getInstrInfo();
245
246 assert(STI.hasVendorXSfmclic() && "Stack Swapping Requires XSfmclic");
247
248 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRW))
250 .addImm(RISCVSysReg::sf_mscratchcsw)
252 .setMIFlag(FrameFlag);
253
254 // FIXME: CFI Information for this swap.
255}
256
257static void
260 if (!RVFI.isSiFivePreemptibleInterrupt(MF))
261 return;
262
263 const TargetRegisterClass &RC = RISCV::GPRRegClass;
264 const TargetRegisterInfo &TRI =
265 *MF.getSubtarget<RISCVSubtarget>().getRegisterInfo();
266 MachineFrameInfo &MFI = MF.getFrameInfo();
267
268 // Create two frame objects for saving `mcause` and `mepc`.
269 for (int I = 0; I < 2; ++I) {
270 int FI = MFI.CreateStackObject(TRI.getSpillSize(RC), TRI.getSpillAlign(RC),
271 true);
273 }
274}
275
276// The scratch register retains an ordinary CSI slot, but its save and restore
277// are emitted explicitly as part of the SiFive CLIC interrupt sequence.
279 const auto &CSI = MF.getFrameInfo().getCalleeSavedInfo();
280 auto ScratchCS = llvm::find_if(
281 CSI, [](const CalleeSavedInfo &CS) { return CS.getReg() == RISCV::X5; });
282 assert(ScratchCS != CSI.end() && "Missing SiFive CLIC scratch spill slot");
283 return ScratchCS->getFrameIdx();
284}
285
289 const DebugLoc &DL) {
290 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
291
292 if (!RVFI->isSiFivePreemptibleInterrupt(MF))
293 return;
294
295 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
296 const RISCVInstrInfo *TII = STI.getInstrInfo();
297
298 // FIXME: CFI information for `mcause` and `mepc` is missing.
299
300 // Preserve X5 before using it to save the interrupt CSRs. Other GPRs
301 // are saved by the ordinary spill sequence after preemption is enabled.
302 int ScratchFI = getSiFiveCLICScratchFrameIndex(MF);
303 TII->storeRegToStackSlot(MBB, MBBI, RISCV::X5, /*IsKill=*/true, ScratchFI,
304 &RISCV::GPRRegClass, Register(),
306 if (needsDwarfCFI(MF))
308 .buildOffset(RISCV::X5, MF.getFrameInfo().getObjectOffset(ScratchFI));
309
310 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRS))
311 .addReg(RISCV::X5, RegState::Define)
312 .addImm(RISCVSysReg::mcause)
313 .addReg(RISCV::X0)
315 TII->storeRegToStackSlot(MBB, MBBI, RISCV::X5, /* IsKill=*/true,
316 RVFI->getInterruptCSRFrameIndex(0),
317 &RISCV::GPRRegClass, Register(),
319
320 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRS))
321 .addReg(RISCV::X5, RegState::Define)
322 .addImm(RISCVSysReg::mepc)
323 .addReg(RISCV::X0)
325
326 // Enable interrupts.
327 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRSI))
328 .addReg(RISCV::X0, RegState::Define)
329 .addImm(RISCVSysReg::mstatus)
330 .addImm(8)
332 TII->storeRegToStackSlot(MBB, MBBI, RISCV::X5, /* IsKill=*/true,
333 RVFI->getInterruptCSRFrameIndex(1),
334 &RISCV::GPRRegClass, Register(),
336}
337
341 CFIInstBuilder &CFIBuilder,
342 const DebugLoc &DL) {
343 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
344
345 if (!RVFI->isSiFivePreemptibleInterrupt(MF))
346 return;
347
348 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
349 const RISCVInstrInfo *TII = STI.getInstrInfo();
350
351 // FIXME: CFI information for `mcause` and `mepc` is missing.
352
353 // Load mepc while preemption is still enabled. A nested handler preserves
354 // X5. Interrupts only need to be disabled before writing the CSRs back.
355 TII->loadRegFromStackSlot(MBB, MBBI, RISCV::X5,
356 RVFI->getInterruptCSRFrameIndex(1),
357 &RISCV::GPRRegClass, Register(),
358 RISCV::NoSubRegister, MachineInstr::FrameDestroy);
359
360 // Disable interrupts.
361 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRCI))
362 .addReg(RISCV::X0, RegState::Define)
363 .addImm(RISCVSysReg::mstatus)
364 .addImm(8)
366
367 // Restore `mepc` and `mcause` through X5, then restore the value X5 held
368 // on entry to the handler.
369 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRW))
370 .addReg(RISCV::X0, RegState::Define)
371 .addImm(RISCVSysReg::mepc)
372 .addReg(RISCV::X5, RegState::Kill)
374
375 TII->loadRegFromStackSlot(MBB, MBBI, RISCV::X5,
376 RVFI->getInterruptCSRFrameIndex(0),
377 &RISCV::GPRRegClass, Register(),
378 RISCV::NoSubRegister, MachineInstr::FrameDestroy);
379 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRW))
380 .addReg(RISCV::X0, RegState::Define)
381 .addImm(RISCVSysReg::mcause)
382 .addReg(RISCV::X5, RegState::Kill)
384
385 // The ordinary reloads have finished. Recover the interrupted value of X5
386 // only after it has restored both CSRs.
387 TII->loadRegFromStackSlot(MBB, MBBI, RISCV::X5,
389 &RISCV::GPRRegClass, Register(),
390 RISCV::NoSubRegister, MachineInstr::FrameDestroy);
391 if (needsDwarfCFI(MF))
392 CFIBuilder.buildRestore(RISCV::X5);
393}
394
395// Get the ID of the libcall used for spilling and restoring callee saved
396// registers. The ID is representative of the number of registers saved or
397// restored by the libcall, except it is zero-indexed - ID 0 corresponds to a
398// single register.
399static int getLibCallID(const MachineFunction &MF,
400 const std::vector<CalleeSavedInfo> &CSI) {
401 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
402
403 if (CSI.empty() || !RVFI->useSaveRestoreLibCalls(MF))
404 return -1;
405
406 MCRegister MaxReg;
407 for (auto &CS : CSI)
408 // assignCalleeSavedSpillSlots assigns negative frame indexes to
409 // registers which can be saved by libcall.
410 if (CS.getFrameIdx() < 0)
411 MaxReg = std::max(MaxReg.id(), CS.getReg().id());
412
413 if (!MaxReg)
414 return -1;
415
416 switch (MaxReg.id()) {
417 default:
418 llvm_unreachable("Something has gone wrong!");
419 // clang-format off
420 case /*s11*/ RISCV::X27: return 12;
421 case /*s10*/ RISCV::X26: return 11;
422 case /*s9*/ RISCV::X25: return 10;
423 case /*s8*/ RISCV::X24: return 9;
424 case /*s7*/ RISCV::X23: return 8;
425 case /*s6*/ RISCV::X22: return 7;
426 case /*s5*/ RISCV::X21: return 6;
427 case /*s4*/ RISCV::X20: return 5;
428 case /*s3*/ RISCV::X19: return 4;
429 case /*s2*/ RISCV::X18: return 3;
430 case /*s1*/ RISCV::X9: return 2;
431 case /*s0*/ FPReg: return 1;
432 case /*ra*/ RAReg: return 0;
433 // clang-format on
434 }
435}
436
437// Get the name of the libcall used for spilling callee saved registers.
438// If this function will not use save/restore libcalls, then return a nullptr.
439static const char *
441 const std::vector<CalleeSavedInfo> &CSI) {
442 static const char *const SpillLibCalls[] = {
443 "__riscv_save_0",
444 "__riscv_save_1",
445 "__riscv_save_2",
446 "__riscv_save_3",
447 "__riscv_save_4",
448 "__riscv_save_5",
449 "__riscv_save_6",
450 "__riscv_save_7",
451 "__riscv_save_8",
452 "__riscv_save_9",
453 "__riscv_save_10",
454 "__riscv_save_11",
455 "__riscv_save_12"
456 };
457
458 int LibCallID = getLibCallID(MF, CSI);
459 if (LibCallID == -1)
460 return nullptr;
461 return SpillLibCalls[LibCallID];
462}
463
464// Get the name of the libcall used for restoring callee saved registers.
465// If this function will not use save/restore libcalls, then return a nullptr.
466static const char *
468 const std::vector<CalleeSavedInfo> &CSI) {
469 static const char *const RestoreLibCalls[] = {
470 "__riscv_restore_0",
471 "__riscv_restore_1",
472 "__riscv_restore_2",
473 "__riscv_restore_3",
474 "__riscv_restore_4",
475 "__riscv_restore_5",
476 "__riscv_restore_6",
477 "__riscv_restore_7",
478 "__riscv_restore_8",
479 "__riscv_restore_9",
480 "__riscv_restore_10",
481 "__riscv_restore_11",
482 "__riscv_restore_12"
483 };
484
485 int LibCallID = getLibCallID(MF, CSI);
486 if (LibCallID == -1)
487 return nullptr;
488 return RestoreLibCalls[LibCallID];
489}
490
491// Get the max reg of Push/Pop for restoring callee saved registers.
492static unsigned getNumPushPopRegs(const std::vector<CalleeSavedInfo> &CSI) {
493 unsigned NumPushPopRegs = 0;
494 for (auto &CS : CSI) {
495 auto *FII = llvm::find_if(FixedCSRFIMap,
496 [&](MCPhysReg P) { return P == CS.getReg(); });
497 if (FII != std::end(FixedCSRFIMap)) {
498 unsigned RegNum = std::distance(std::begin(FixedCSRFIMap), FII);
499 NumPushPopRegs = std::max(NumPushPopRegs, RegNum + 1);
500 }
501 }
502 assert(NumPushPopRegs != 12 && "x26 requires x27 to also be pushed");
503 return NumPushPopRegs;
504}
505
506// Return true if the specified function should have a dedicated frame
507// pointer register. This is true if frame pointer elimination is
508// disabled, if it needs dynamic stack realignment, if the function has
509// variable sized allocas, or if the frame address is taken.
511 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
512
513 const MachineFrameInfo &MFI = MF.getFrameInfo();
514 if (MF.disableFramePointerElim() || RegInfo->hasStackRealignment(MF) ||
516 return true;
517
518 // With large callframes around we may need to use FP to access the scavenging
519 // emergency spillslot.
520 //
521 // We calculate the MaxCallFrameSize at the end of isel so this value should
522 // be stable for the whole post-isel MIR pipeline.
523 //
524 // NOTE: The idea of forcing a frame pointer is copied from AArch64, but they
525 // conservatively return true when the call frame size hasd not been
526 // computed yet. On RISC-V that caused MachineOutliner tests to fail the
527 // MachineVerifier due to outlined functions not computing max call frame
528 // size thus the frame pointer would always be reserved.
529 if (MFI.isMaxCallFrameSizeComputed() && MFI.getMaxCallFrameSize() > 2047)
530 return true;
531
532 return false;
533}
534
536 const MachineFrameInfo &MFI = MF.getFrameInfo();
537 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
538
539 // If we do not reserve stack space for outgoing arguments in prologue,
540 // we will adjust the stack pointer before call instruction. After the
541 // adjustment, we can not use SP to access the stack objects for the
542 // arguments. Instead, use BP to access these stack objects.
543 return (MFI.hasVarSizedObjects() ||
545 MFI.getMaxCallFrameSize() != 0))) &&
546 TRI->hasStackRealignment(MF);
547}
548
549// Determines the size of the frame and maximum call frame size.
550void RISCVFrameLowering::determineFrameLayout(MachineFunction &MF) const {
551 MachineFrameInfo &MFI = MF.getFrameInfo();
552 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
553
554 // Get the number of bytes to allocate from the FrameInfo.
555 uint64_t FrameSize = MFI.getStackSize();
556
557 // QCI Interrupts use at least 96 bytes of stack space
558 if (RVFI->useQCIInterrupt(MF))
559 FrameSize = std::max(FrameSize, QCIInterruptPushAmount);
560
561 // Get the alignment.
562 Align StackAlign = getStackAlign();
563
564 // Make sure the frame is aligned.
565 FrameSize = alignTo(FrameSize, StackAlign);
566
567 // Update frame info.
568 MFI.setStackSize(FrameSize);
569
570 // When using SP or BP to access stack objects, we may require extra padding
571 // to ensure the bottom of the RVV stack is correctly aligned within the main
572 // stack. We calculate this as the amount required to align the scalar local
573 // variable section up to the RVV alignment.
575 if (RVFI->getRVVStackSize() && (!hasFP(MF) || TRI->hasStackRealignment(MF))) {
576 int ScalarLocalVarSize = FrameSize - RVFI->getCalleeSavedStackSize() -
577 RVFI->getVarArgsSaveSize();
578 if (auto RVVPadding =
579 offsetToAlignment(ScalarLocalVarSize, RVFI->getRVVStackAlign()))
580 RVFI->setRVVPadding(RVVPadding);
581 }
582}
583
584// Returns the stack size including RVV padding (when required), rounded back
585// up to the required stack alignment.
587 const MachineFunction &MF) const {
588 const MachineFrameInfo &MFI = MF.getFrameInfo();
589 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
590 return alignTo(MFI.getStackSize() + RVFI->getRVVPadding(), getStackAlign());
591}
592
595 const std::vector<CalleeSavedInfo> &CSI,
596 bool ReverseOrder = false) {
597 const MachineFrameInfo &MFI = MF.getFrameInfo();
599
600 for (auto &CS : CSI) {
601 int FI = CS.getFrameIdx();
602 if (FI >= 0 && MFI.getStackID(FI) == TargetStackID::Default)
603 NonLibcallCSI.push_back(CS);
604 }
605
606 // Reverse the order so that load/store operations use ascending addresses,
607 // enabling better load/store clustering and fusion.
608 if (ReverseOrder)
609 std::reverse(NonLibcallCSI.begin(), NonLibcallCSI.end());
610
611 return NonLibcallCSI;
612}
613
614// Exclude X5 from ordinary spills and restores for SiFive CLIC preemptible
615// handlers, which save and restore it explicitly.
618 const std::vector<CalleeSavedInfo> &CSI,
619 bool ReverseOrder = false) {
620 auto InterruptCSI = getUnmanagedCSI(MF, CSI, ReverseOrder);
622 llvm::erase_if(InterruptCSI, [](const CalleeSavedInfo &CS) {
623 return CS.getReg() == RISCV::X5;
624 });
625 return InterruptCSI;
626}
627
630 const std::vector<CalleeSavedInfo> &CSI) {
631 const MachineFrameInfo &MFI = MF.getFrameInfo();
633
634 for (auto &CS : CSI) {
635 int FI = CS.getFrameIdx();
636 if (FI >= 0 && MFI.getStackID(FI) == TargetStackID::ScalableVector)
637 RVVCSI.push_back(CS);
638 }
639
640 return RVVCSI;
641}
642
645 const std::vector<CalleeSavedInfo> &CSI) {
646 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
647
648 SmallVector<CalleeSavedInfo, 8> PushOrLibCallsCSI;
649 if (!RVFI->useSaveRestoreLibCalls(MF) && !RVFI->isPushable(MF))
650 return PushOrLibCallsCSI;
651
652 for (const auto &CS : CSI) {
653 if (RVFI->useQCIInterrupt(MF)) {
654 // Some registers are saved by both `QC.C.MIENTER(.NEST)` and
655 // `QC.CM.PUSH(FP)`. In these cases, prioritise the CFI info that points
656 // to the versions saved by `QC.C.MIENTER(.NEST)` which is what FP
657 // unwinding would use.
659 CS.getReg()))
660 continue;
661 }
662
663 if (llvm::is_contained(FixedCSRFIMap, CS.getReg()))
664 PushOrLibCallsCSI.push_back(CS);
665 }
666
667 return PushOrLibCallsCSI;
668}
669
672 const std::vector<CalleeSavedInfo> &CSI) {
673 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
674
675 SmallVector<CalleeSavedInfo, 8> QCIInterruptCSI;
676 if (!RVFI->useQCIInterrupt(MF))
677 return QCIInterruptCSI;
678
679 for (const auto &CS : CSI) {
681 CS.getReg()))
682 QCIInterruptCSI.push_back(CS);
683 }
684
685 return QCIInterruptCSI;
686}
687
689 const MachineBasicBlock &MBB) {
690 const MachineFunction *MF = MBB.getParent();
691 LiveRegs.addLiveIns(MBB);
692 const MCPhysReg *CSRegs = MF->getRegInfo().getCalleeSavedRegs();
693 for (unsigned i = 0; CSRegs[i]; ++i)
694 LiveRegs.addReg(CSRegs[i]);
695}
696
698 MachineBasicBlock *MBB, Register PreferredReg, Register DontUseReg) const {
699 MachineFunction *MF = MBB->getParent();
700
701 // Stack protection code is being inserted at beginning of function, use
702 // register which has been historically used
703 if (&MF->front() == MBB)
704 return PreferredReg;
705
706 const RISCVSubtarget &Subtarget = MF->getSubtarget<RISCVSubtarget>();
707 const TargetRegisterInfo &TRI = *Subtarget.getRegisterInfo();
710
711 const MachineRegisterInfo &MRI = MF->getRegInfo();
712 // Prefer the register which has been historically used for stack protector
713 if (LiveRegs.available(MRI, PreferredReg))
714 return PreferredReg;
715
716 static const MCPhysReg CandidateRegs[] = {
717 RISCV::X5, RISCV::X6, RISCV::X7, RISCV::X28,
718 RISCV::X29, RISCV::X30, RISCV::X31,
719 };
720
721 for (unsigned Reg : CandidateRegs) {
722 if (Reg != DontUseReg && LiveRegs.available(MRI, Reg))
723 return Reg;
724 }
725
726 return Register();
727}
728
729void RISCVFrameLowering::allocateAndProbeStackForRVV(
731 MachineBasicBlock::iterator MBBI, const DebugLoc &DL, int64_t Amount,
732 MachineInstr::MIFlag Flag, bool EmitCFI, bool DynAllocation) const {
733 assert(Amount != 0 && "Did not need to adjust stack pointer for RVV.");
734
735 // Emit a variable-length allocation probing loop.
736
737 // Get VLEN in TargetReg
738 Register TargetReg = findScratchNonCalleeSaveRegister(&MBB, RISCV::X6);
739 assert(TargetReg.isValid() &&
740 "No available scratch register for stack probing");
742 uint32_t NumOfVReg = Amount / RISCV::RVVBytesPerBlock;
743 BuildMI(MBB, MBBI, DL, TII->get(RISCV::PseudoReadVLENB), TargetReg)
744 .setMIFlag(Flag);
745 TII->mulImm(MF, MBB, MBBI, DL, TargetReg, NumOfVReg, Flag);
746
748 if (EmitCFI) {
749 // Set the CFA register to TargetReg.
750 CFIBuilder.buildDefCFA(TargetReg, -Amount);
751 }
752
753 // It will be expanded to a probe loop in `inlineStackProbe`.
754 BuildMI(MBB, MBBI, DL, TII->get(RISCV::PROBED_STACKALLOC_RVV))
755 .addReg(TargetReg);
756
757 if (EmitCFI) {
758 // Set the CFA register back to SP.
759 CFIBuilder.buildDefCFARegister(SPReg);
760 }
761
762 // SUB SP, SP, T1
763 BuildMI(MBB, MBBI, DL, TII->get(RISCV::SUB), SPReg)
764 .addReg(SPReg)
765 .addReg(TargetReg)
766 .setMIFlag(Flag);
767
768 // If we have a dynamic allocation later we need to probe any residuals.
769 if (DynAllocation) {
770 BuildMI(MBB, MBBI, DL, TII->get(STI.is64Bit() ? RISCV::SD : RISCV::SW))
771 .addReg(RISCV::X0)
772 .addReg(SPReg)
773 .addImm(0)
775 }
776}
777
781 llvm::raw_string_ostream &Comment) {
782 int64_t FixedOffset = Offset.getFixed();
783 int64_t ScalableOffset = Offset.getScalable();
784 unsigned DwarfVLenB = TRI.getDwarfRegNum(RISCV::VLENB, true);
785 if (FixedOffset) {
786 Expr.push_back(dwarf::DW_OP_consts);
787 appendLEB128<LEB128Sign::Signed>(Expr, FixedOffset);
788 Expr.push_back((uint8_t)dwarf::DW_OP_plus);
789 Comment << (FixedOffset < 0 ? " - " : " + ") << std::abs(FixedOffset);
790 }
791
792 Expr.push_back((uint8_t)dwarf::DW_OP_consts);
793 appendLEB128<LEB128Sign::Signed>(Expr, ScalableOffset);
794
795 Expr.push_back((uint8_t)dwarf::DW_OP_bregx);
796 appendLEB128<LEB128Sign::Unsigned>(Expr, DwarfVLenB);
797 Expr.push_back(0);
798
799 Expr.push_back((uint8_t)dwarf::DW_OP_mul);
800 Expr.push_back((uint8_t)dwarf::DW_OP_plus);
801
802 Comment << (ScalableOffset < 0 ? " - " : " + ") << std::abs(ScalableOffset)
803 << " * vlenb";
804}
805
809 assert(Offset.getScalable() != 0 && "Did not need to adjust CFA for RVV");
810 SmallString<64> Expr;
811 std::string CommentBuffer;
812 llvm::raw_string_ostream Comment(CommentBuffer);
813 // Build up the expression (Reg + FixedOffset + ScalableOffset * VLENB).
814 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
815 Expr.push_back((uint8_t)(dwarf::DW_OP_breg0 + DwarfReg));
816 Expr.push_back(0);
817 if (Reg == SPReg)
818 Comment << "sp";
819 else
820 Comment << printReg(Reg, &TRI);
821
823
824 SmallString<64> DefCfaExpr;
825 DefCfaExpr.push_back(dwarf::DW_CFA_def_cfa_expression);
826 appendLEB128<LEB128Sign::Unsigned>(DefCfaExpr, Expr.size());
827 DefCfaExpr.append(Expr.str());
828
829 return MCCFIInstruction::createEscape(nullptr, DefCfaExpr.str(), SMLoc(),
830 Comment.str());
831}
832
835 assert(Offset.getScalable() != 0 && "Did not need to adjust CFA for RVV");
836 SmallString<64> Expr;
837 std::string CommentBuffer;
838 llvm::raw_string_ostream Comment(CommentBuffer);
839 Comment << printReg(Reg, &TRI) << " @ cfa";
840
841 // Build up the expression (FixedOffset + ScalableOffset * VLENB).
843
844 SmallString<64> DefCfaExpr;
845 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
846 DefCfaExpr.push_back(dwarf::DW_CFA_expression);
847 appendLEB128<LEB128Sign::Unsigned>(DefCfaExpr, DwarfReg);
848 appendLEB128<LEB128Sign::Unsigned>(DefCfaExpr, Expr.size());
849 DefCfaExpr.append(Expr.str());
850
851 return MCCFIInstruction::createEscape(nullptr, DefCfaExpr.str(), SMLoc(),
852 Comment.str());
853}
854
855// Allocate stack space and probe it if necessary.
858 MachineFunction &MF, uint64_t Offset,
859 uint64_t RealStackSize, bool EmitCFI,
860 bool NeedProbe, uint64_t ProbeSize,
861 bool DynAllocation,
862 MachineInstr::MIFlag Flag) const {
863 DebugLoc DL;
864 const RISCVRegisterInfo *RI = STI.getRegisterInfo();
865 const RISCVInstrInfo *TII = STI.getInstrInfo();
866 bool IsRV64 = STI.is64Bit();
868
869 // Simply allocate the stack if it's not big enough to require a probe.
870 if (!NeedProbe || Offset <= ProbeSize) {
872 Flag, getStackAlign());
873
874 if (EmitCFI)
875 CFIBuilder.buildDefCFAOffset(RealStackSize);
876
877 if (NeedProbe && DynAllocation) {
878 // s[d|w] zero, 0(sp)
879 BuildMI(MBB, MBBI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
880 .addReg(RISCV::X0)
881 .addReg(SPReg)
882 .addImm(0)
883 .setMIFlags(Flag);
884 }
885
886 return;
887 }
888
889 // Unroll the probe loop depending on the number of iterations.
890 if (Offset < ProbeSize * 5) {
891 uint64_t CFAAdjust = RealStackSize - Offset;
892
893 uint64_t CurrentOffset = 0;
894 while (CurrentOffset + ProbeSize <= Offset) {
895 RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg,
896 StackOffset::getFixed(-ProbeSize), Flag, getStackAlign());
897 // s[d|w] zero, 0(sp)
898 BuildMI(MBB, MBBI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
899 .addReg(RISCV::X0)
900 .addReg(SPReg)
901 .addImm(0)
902 .setMIFlags(Flag);
903
904 CurrentOffset += ProbeSize;
905 if (EmitCFI)
906 CFIBuilder.buildDefCFAOffset(CurrentOffset + CFAAdjust);
907 }
908
909 uint64_t Residual = Offset - CurrentOffset;
910 if (Residual) {
911 RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg,
912 StackOffset::getFixed(-Residual), Flag, getStackAlign());
913 if (EmitCFI)
914 CFIBuilder.buildDefCFAOffset(RealStackSize);
915
916 if (DynAllocation) {
917 // s[d|w] zero, 0(sp)
918 BuildMI(MBB, MBBI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
919 .addReg(RISCV::X0)
920 .addReg(SPReg)
921 .addImm(0)
922 .setMIFlags(Flag);
923 }
924 }
925
926 return;
927 }
928
929 // Emit a variable-length allocation probing loop.
930 uint64_t RoundedSize = alignDown(Offset, ProbeSize);
931 uint64_t Residual = Offset - RoundedSize;
932
933 Register TargetReg = findScratchNonCalleeSaveRegister(&MBB, RISCV::X6);
934 assert(TargetReg.isValid() &&
935 "No available scratch register for stack probing");
936 // SUB TargetReg, SP, RoundedSize
937 RI->adjustReg(MBB, MBBI, DL, TargetReg, SPReg,
938 StackOffset::getFixed(-RoundedSize), Flag, getStackAlign());
939
940 if (EmitCFI) {
941 // Set the CFA register to TargetReg.
942 CFIBuilder.buildDefCFA(TargetReg, RoundedSize);
943 }
944
945 // It will be expanded to a probe loop in `inlineStackProbe`.
946 BuildMI(MBB, MBBI, DL, TII->get(RISCV::PROBED_STACKALLOC)).addReg(TargetReg);
947
948 if (EmitCFI) {
949 // Set the CFA register back to SP.
950 CFIBuilder.buildDefCFARegister(SPReg);
951 }
952
953 if (Residual) {
955 Flag, getStackAlign());
956 if (DynAllocation) {
957 // s[d|w] zero, 0(sp)
958 BuildMI(MBB, MBBI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
959 .addReg(RISCV::X0)
960 .addReg(SPReg)
961 .addImm(0)
962 .setMIFlags(Flag);
963 }
964 }
965
966 if (EmitCFI)
967 CFIBuilder.buildDefCFAOffset(Offset);
968}
969
970static bool isPush(unsigned Opcode) {
971 switch (Opcode) {
972 case RISCV::CM_PUSH:
973 case RISCV::QC_CM_PUSH:
974 case RISCV::QC_CM_PUSHFP:
975 return true;
976 default:
977 return false;
978 }
979}
980
981static bool isPop(unsigned Opcode) {
982 // There are other pops but these are the only ones introduced during this
983 // pass.
984 switch (Opcode) {
985 case RISCV::CM_POP:
986 case RISCV::QC_CM_POP:
987 return true;
988 default:
989 return false;
990 }
991}
992
994 bool UpdateFP) {
995 switch (Kind) {
997 return RISCV::CM_PUSH;
999 return UpdateFP ? RISCV::QC_CM_PUSHFP : RISCV::QC_CM_PUSH;
1000 default:
1001 llvm_unreachable("Unhandled PushPopKind");
1002 }
1003}
1004
1006 // There are other pops but they are introduced later by the Push/Pop
1007 // Optimizer.
1008 switch (Kind) {
1010 return RISCV::CM_POP;
1012 return RISCV::QC_CM_POP;
1013 default:
1014 llvm_unreachable("Unhandled PushPopKind");
1015 }
1016}
1017
1019 MachineBasicBlock &MBB) const {
1020 MachineFrameInfo &MFI = MF.getFrameInfo();
1021 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1022 const RISCVRegisterInfo *RI = STI.getRegisterInfo();
1024 bool PreferAscendingLS = STI.preferAscendingLoadStore();
1025
1026 Register BPReg = RISCVABI::getBPReg();
1027
1028 // Debug location must be unknown since the first debug location is used
1029 // to determine the end of the prologue.
1030 DebugLoc DL;
1031
1032 // All calls are tail calls in GHC calling conv, and functions have no
1033 // prologue/epilogue.
1035 return;
1036
1037 // SiFive CLIC needs to swap `sp` into `sf.mscratchcsw`
1039
1040 // Emit prologue for shadow call stack.
1041 emitSCSPrologue(MF, MBB, MBBI, DL);
1042
1043 // We keep track of the first instruction because it might be a
1044 // `(QC.)CM.PUSH(FP)`, and we may need to adjust the immediate rather than
1045 // inserting an `addi sp, sp, -N*16`
1046 auto PossiblePush = MBBI;
1047
1048 // Skip past all callee-saved register spill instructions.
1049 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
1050 ++MBBI;
1051
1052 // Determine the correct frame layout
1053 determineFrameLayout(MF);
1054
1055 const auto &CSI = MFI.getCalleeSavedInfo();
1056
1057 // Skip to before the spills of scalar callee-saved registers
1058 // FIXME: assumes exactly one instruction is used to restore each
1059 // callee-saved register.
1060 MBBI = std::prev(
1061 MBBI, getRVVCalleeSavedInfo(MF, CSI).size() +
1062 getUnmanagedInterruptCSI(MF, CSI, PreferAscendingLS).size());
1064 bool NeedsDwarfCFI = needsDwarfCFI(MF);
1065
1066 // If libcalls are used to spill and restore callee-saved registers, the frame
1067 // has two sections; the opaque section managed by the libcalls, and the
1068 // section managed by MachineFrameInfo which can also hold callee saved
1069 // registers in fixed stack slots, both of which have negative frame indices.
1070 // This gets even more complicated when incoming arguments are passed via the
1071 // stack, as these too have negative frame indices. An example is detailed
1072 // below:
1073 //
1074 // | incoming arg | <- FI[-3]
1075 // | libcallspill |
1076 // | calleespill | <- FI[-2]
1077 // | calleespill | <- FI[-1]
1078 // | this_frame | <- FI[0]
1079 //
1080 // For negative frame indices, the offset from the frame pointer will differ
1081 // depending on which of these groups the frame index applies to.
1082 // The following calculates the correct offset knowing the number of callee
1083 // saved registers spilt by the two methods.
1084 if (int LibCallRegs = getLibCallID(MF, MFI.getCalleeSavedInfo()) + 1) {
1085 // Calculate the size of the frame managed by the libcall. The stack
1086 // alignment of these libcalls should be the same as how we set it in
1087 // getABIStackAlignment.
1088 unsigned LibCallFrameSize =
1089 alignTo((STI.getXLen() / 8) * LibCallRegs, getStackAlign());
1090 RVFI->setLibCallStackSize(LibCallFrameSize);
1091
1092 if (NeedsDwarfCFI) {
1093 CFIBuilder.buildDefCFAOffset(LibCallFrameSize);
1094 for (const CalleeSavedInfo &CS : getPushOrLibCallsSavedInfo(MF, CSI))
1095 CFIBuilder.buildOffset(CS.getReg(),
1096 MFI.getObjectOffset(CS.getFrameIdx()));
1097 }
1098 }
1099
1100 // FIXME (note copied from Lanai): This appears to be overallocating. Needs
1101 // investigation. Get the number of bytes to allocate from the FrameInfo.
1102 uint64_t RealStackSize = getStackSizeWithRVVPadding(MF);
1103 uint64_t StackSize = RealStackSize - RVFI->getReservedSpillsSize();
1104 uint64_t RVVStackSize = RVFI->getRVVStackSize();
1105
1106 // Early exit if there is no need to allocate on the stack
1107 if (RealStackSize == 0 && !MFI.adjustsStack() && RVVStackSize == 0)
1108 return;
1109
1110 // If the stack pointer has been marked as reserved, then produce an error if
1111 // the frame requires stack allocation
1112 if (STI.isRegisterReservedByUser(SPReg))
1114 MF.getFunction(), "Stack pointer required, but has been reserved."});
1115
1116 uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
1117 // Split the SP adjustment to reduce the offsets of callee saved spill.
1118 if (FirstSPAdjustAmount) {
1119 StackSize = FirstSPAdjustAmount;
1120 RealStackSize = FirstSPAdjustAmount;
1121 }
1122
1123 if (RVFI->useQCIInterrupt(MF)) {
1124 // The function starts with `QC.C.MIENTER(.NEST)`, so the `(QC.)CM.PUSH(FP)`
1125 // could only be the next instruction.
1126 ++PossiblePush;
1127
1128 if (NeedsDwarfCFI) {
1129 // Insert the CFI metadata before where we think the `(QC.)CM.PUSH(FP)`
1130 // could be. The PUSH will also get its own CFI metadata for its own
1131 // modifications, which should come after the PUSH.
1132 CFIInstBuilder PushCFIBuilder(MBB, PossiblePush,
1135 for (const CalleeSavedInfo &CS : getQCISavedInfo(MF, CSI))
1136 PushCFIBuilder.buildOffset(CS.getReg(),
1137 MFI.getObjectOffset(CS.getFrameIdx()));
1138 }
1139 }
1140
1141 if (RVFI->isPushable(MF) && PossiblePush != MBB.end() &&
1142 isPush(PossiblePush->getOpcode())) {
1143 // Use available stack adjustment in push instruction to allocate additional
1144 // stack space. Align the stack size down to a multiple of 16. This is
1145 // needed for RVE.
1146 // FIXME: Can we increase the stack size to a multiple of 16 instead?
1147 uint64_t StackAdj =
1148 std::min(alignDown(StackSize, 16), static_cast<uint64_t>(48));
1149 PossiblePush->getOperand(1).setImm(StackAdj);
1150 StackSize -= StackAdj;
1151
1152 if (NeedsDwarfCFI) {
1153 CFIBuilder.buildDefCFAOffset(RealStackSize - StackSize);
1154 for (const CalleeSavedInfo &CS : getPushOrLibCallsSavedInfo(MF, CSI))
1155 CFIBuilder.buildOffset(CS.getReg(),
1156 MFI.getObjectOffset(CS.getFrameIdx()));
1157 }
1158 }
1159
1160 // Allocate space on the stack if necessary.
1161 auto &Subtarget = MF.getSubtarget<RISCVSubtarget>();
1162 const RISCVTargetLowering *TLI = Subtarget.getTargetLowering();
1163 bool NeedProbe = TLI->hasInlineStackProbe(MF);
1164 uint64_t ProbeSize = TLI->getStackProbeSize(MF, getStackAlign());
1165 bool DynAllocation =
1166 MF.getInfo<RISCVMachineFunctionInfo>()->hasDynamicAllocation();
1167 if (StackSize != 0)
1168 allocateStack(MBB, MBBI, MF, StackSize, RealStackSize, NeedsDwarfCFI,
1169 NeedProbe, ProbeSize, DynAllocation,
1171
1172 // Save SiFive CLIC CSRs into Stack
1174
1175 // The frame pointer is callee-saved, and code has been generated for us to
1176 // save it to the stack. We need to skip over the storing of callee-saved
1177 // registers as the frame pointer must be modified after it has been saved
1178 // to the stack, not before.
1179 // FIXME: assumes exactly one instruction is used to save each callee-saved
1180 // register.
1181 std::advance(MBBI,
1182 getUnmanagedInterruptCSI(MF, CSI, PreferAscendingLS).size());
1183 CFIBuilder.setInsertPoint(MBBI);
1184
1185 // Iterate over list of callee-saved registers and emit .cfi_offset
1186 // directives.
1187 if (NeedsDwarfCFI) {
1188 for (const CalleeSavedInfo &CS :
1189 getUnmanagedInterruptCSI(MF, CSI, PreferAscendingLS)) {
1190 MCRegister Reg = CS.getReg();
1191 int64_t Offset = MFI.getObjectOffset(CS.getFrameIdx());
1192 // Emit CFI for both sub-registers. The even register is at the base
1193 // offset and odd at base+4.
1194 if (RISCV::GPRPairRegClass.contains(Reg)) {
1195 MCRegister EvenReg = RI->getSubReg(Reg, RISCV::sub_gpr_even);
1196 MCRegister OddReg = RI->getSubReg(Reg, RISCV::sub_gpr_odd);
1197 CFIBuilder.buildOffset(EvenReg, Offset);
1198 CFIBuilder.buildOffset(OddReg, Offset + 4);
1199 } else {
1200 CFIBuilder.buildOffset(Reg, Offset);
1201 }
1202 }
1203 }
1204
1205 // Generate new FP.
1206 if (hasFP(MF)) {
1207 if (STI.isRegisterReservedByUser(FPReg))
1209 MF.getFunction(), "Frame pointer required, but has been reserved."});
1210 // The frame pointer does need to be reserved from register allocation.
1211 assert(MF.getRegInfo().isReserved(FPReg) && "FP not reserved");
1212
1213 // Some stack management variants automatically keep FP updated, so we don't
1214 // need an instruction to do so.
1215 if (!RVFI->hasImplicitFPUpdates(MF)) {
1216 RI->adjustReg(
1217 MBB, MBBI, DL, FPReg, SPReg,
1218 StackOffset::getFixed(RealStackSize - RVFI->getVarArgsSaveSize()),
1220 }
1221
1222 if (NeedsDwarfCFI)
1223 CFIBuilder.buildDefCFA(FPReg, RVFI->getVarArgsSaveSize());
1224 }
1225
1226 uint64_t SecondSPAdjustAmount = 0;
1227 // Emit the second SP adjustment after saving callee saved registers.
1228 if (FirstSPAdjustAmount) {
1229 SecondSPAdjustAmount = getStackSizeWithRVVPadding(MF) - FirstSPAdjustAmount;
1230 assert(SecondSPAdjustAmount > 0 &&
1231 "SecondSPAdjustAmount should be greater than zero");
1232
1233 allocateStack(MBB, MBBI, MF, SecondSPAdjustAmount,
1234 getStackSizeWithRVVPadding(MF), NeedsDwarfCFI && !hasFP(MF),
1235 NeedProbe, ProbeSize, DynAllocation,
1237 }
1238
1239 if (RVVStackSize) {
1240 if (NeedProbe) {
1241 allocateAndProbeStackForRVV(MF, MBB, MBBI, DL, RVVStackSize,
1243 NeedsDwarfCFI && !hasFP(MF), DynAllocation);
1244 } else {
1245 // We must keep the stack pointer aligned through any intermediate
1246 // updates.
1247 RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg,
1248 StackOffset::getScalable(-RVVStackSize),
1250 }
1251
1252 if (NeedsDwarfCFI && !hasFP(MF)) {
1253 // Emit .cfi_def_cfa_expression "sp + StackSize + RVVStackSize * vlenb".
1255 *RI, SPReg,
1256 StackOffset::get(getStackSizeWithRVVPadding(MF), RVVStackSize / 8)));
1257 }
1258
1259 std::advance(MBBI, getRVVCalleeSavedInfo(MF, CSI).size());
1260 if (NeedsDwarfCFI)
1261 emitCalleeSavedRVVPrologCFI(MBB, MBBI, hasFP(MF));
1262 }
1263
1264 if (hasFP(MF)) {
1265 // Realign Stack
1266 const RISCVRegisterInfo *RI = STI.getRegisterInfo();
1267 if (RI->hasStackRealignment(MF)) {
1268 Align MaxAlignment = MFI.getMaxAlign();
1269
1270 const RISCVInstrInfo *TII = STI.getInstrInfo();
1271 if (isInt<12>(-(int)MaxAlignment.value())) {
1272 BuildMI(MBB, MBBI, DL, TII->get(RISCV::ANDI), SPReg)
1273 .addReg(SPReg)
1274 .addImm(-(int)MaxAlignment.value())
1276 } else {
1277 unsigned ShiftAmount = Log2(MaxAlignment);
1278 Register VR =
1279 MF.getRegInfo().createVirtualRegister(&RISCV::GPRRegClass);
1280 BuildMI(MBB, MBBI, DL, TII->get(RISCV::SRLI), VR)
1281 .addReg(SPReg)
1282 .addImm(ShiftAmount)
1284 BuildMI(MBB, MBBI, DL, TII->get(RISCV::SLLI), SPReg)
1285 .addReg(VR)
1286 .addImm(ShiftAmount)
1288 }
1289 if (NeedProbe && RVVStackSize == 0) {
1290 // Do a probe if the align + size allocated just passed the probe size
1291 // and was not yet probed.
1292 if (SecondSPAdjustAmount < ProbeSize &&
1293 SecondSPAdjustAmount + MaxAlignment.value() >= ProbeSize) {
1294 bool IsRV64 = STI.is64Bit();
1295 BuildMI(MBB, MBBI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
1296 .addReg(RISCV::X0)
1297 .addReg(SPReg)
1298 .addImm(0)
1300 }
1301 }
1302 // FP will be used to restore the frame in the epilogue, so we need
1303 // another base register BP to record SP after re-alignment. SP will
1304 // track the current stack after allocating variable sized objects.
1305 if (hasBP(MF)) {
1306 // move BP, SP
1307 BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), BPReg)
1308 .addReg(SPReg)
1309 .addImm(0)
1311 }
1312 }
1313 }
1314}
1315
1316void RISCVFrameLowering::deallocateStack(MachineFunction &MF,
1319 const DebugLoc &DL,
1320 uint64_t &StackSize,
1321 int64_t CFAOffset) const {
1323
1324 RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg, StackOffset::getFixed(StackSize),
1326 StackSize = 0;
1327
1328 if (needsDwarfCFI(MF))
1330 .buildDefCFAOffset(CFAOffset);
1331}
1332
1334 MachineBasicBlock &MBB) const {
1335 const RISCVRegisterInfo *RI = STI.getRegisterInfo();
1336 MachineFrameInfo &MFI = MF.getFrameInfo();
1337 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1338 bool PreferAscendingLS = STI.preferAscendingLoadStore();
1339
1340 // All calls are tail calls in GHC calling conv, and functions have no
1341 // prologue/epilogue.
1343 return;
1344
1345 // Get the insert location for the epilogue. If there were no terminators in
1346 // the block, get the last instruction.
1348 DebugLoc DL;
1349 if (!MBB.empty()) {
1350 MBBI = MBB.getLastNonDebugInstr();
1351 if (MBBI != MBB.end())
1352 DL = MBBI->getDebugLoc();
1353
1354 MBBI = MBB.getFirstTerminator();
1355
1356 // Skip to before the restores of all callee-saved registers.
1357 while (MBBI != MBB.begin() &&
1358 std::prev(MBBI)->getFlag(MachineInstr::FrameDestroy))
1359 --MBBI;
1360 }
1361
1362 const auto &CSI = MFI.getCalleeSavedInfo();
1363
1364 // Skip to before the restores of scalar callee-saved registers
1365 // FIXME: assumes exactly one instruction is used to restore each
1366 // callee-saved register.
1367 auto FirstScalarCSRRestoreInsn =
1368 std::next(MBBI, getRVVCalleeSavedInfo(MF, CSI).size());
1369 CFIInstBuilder CFIBuilder(MBB, FirstScalarCSRRestoreInsn,
1371 bool NeedsDwarfCFI = needsDwarfCFI(MF);
1372
1373 uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
1374 uint64_t RealStackSize = FirstSPAdjustAmount ? FirstSPAdjustAmount
1376 uint64_t StackSize = FirstSPAdjustAmount ? FirstSPAdjustAmount
1378 RVFI->getReservedSpillsSize();
1379 uint64_t FPOffset = RealStackSize - RVFI->getVarArgsSaveSize();
1380 uint64_t RVVStackSize = RVFI->getRVVStackSize();
1381
1382 bool RestoreSPFromFP = RI->hasStackRealignment(MF) ||
1384 if (RVVStackSize) {
1385 // If RestoreSPFromFP the stack pointer will be restored using the frame
1386 // pointer value.
1387 if (!RestoreSPFromFP)
1388 RI->adjustReg(MBB, FirstScalarCSRRestoreInsn, DL, SPReg, SPReg,
1389 StackOffset::getScalable(RVVStackSize),
1391
1392 if (NeedsDwarfCFI) {
1393 if (!hasFP(MF))
1394 CFIBuilder.buildDefCFA(SPReg, RealStackSize);
1395 emitCalleeSavedRVVEpilogCFI(MBB, FirstScalarCSRRestoreInsn);
1396 }
1397 }
1398
1399 if (FirstSPAdjustAmount) {
1400 uint64_t SecondSPAdjustAmount =
1401 getStackSizeWithRVVPadding(MF) - FirstSPAdjustAmount;
1402 assert(SecondSPAdjustAmount > 0 &&
1403 "SecondSPAdjustAmount should be greater than zero");
1404
1405 // If RestoreSPFromFP the stack pointer will be restored using the frame
1406 // pointer value.
1407 if (!RestoreSPFromFP)
1408 RI->adjustReg(MBB, FirstScalarCSRRestoreInsn, DL, SPReg, SPReg,
1409 StackOffset::getFixed(SecondSPAdjustAmount),
1411
1412 if (NeedsDwarfCFI && !hasFP(MF))
1413 CFIBuilder.buildDefCFAOffset(FirstSPAdjustAmount);
1414 }
1415
1416 // Restore the stack pointer using the value of the frame pointer. Only
1417 // necessary if the stack pointer was modified, meaning the stack size is
1418 // unknown.
1419 //
1420 // In order to make sure the stack point is right through the EH region,
1421 // we also need to restore stack pointer from the frame pointer if we
1422 // don't preserve stack space within prologue/epilogue for outgoing variables,
1423 // normally it's just checking the variable sized object is present or not
1424 // is enough, but we also don't preserve that at prologue/epilogue when
1425 // have vector objects in stack.
1426 if (RestoreSPFromFP) {
1427 assert(hasFP(MF) && "frame pointer should not have been eliminated");
1428 RI->adjustReg(MBB, FirstScalarCSRRestoreInsn, DL, SPReg, FPReg,
1430 getStackAlign());
1431 }
1432
1433 if (NeedsDwarfCFI && hasFP(MF))
1434 CFIBuilder.buildDefCFA(SPReg, RealStackSize);
1435
1436 // Skip to after the restores of scalar callee-saved registers
1437 // FIXME: assumes exactly one instruction is used to restore each
1438 // callee-saved register.
1439 MBBI = std::next(FirstScalarCSRRestoreInsn,
1440 getUnmanagedInterruptCSI(MF, CSI, PreferAscendingLS).size());
1441 CFIBuilder.setInsertPoint(MBBI);
1442 emitSiFiveCLICPreemptibleRestores(MF, MBB, MBBI, CFIBuilder, DL);
1443
1444 if (getLibCallID(MF, CSI) != -1) {
1445 // tail __riscv_restore_[0-12] instruction is considered as a terminator,
1446 // therefore it is unnecessary to place any CFI instructions after it. Just
1447 // deallocate stack if needed and return.
1448 if (StackSize != 0)
1449 deallocateStack(MF, MBB, MBBI, DL, StackSize,
1450 RVFI->getLibCallStackSize());
1451
1452 // Emit epilogue for shadow call stack.
1453 emitSCSEpilogue(MF, MBB, MBBI, DL);
1454 return;
1455 }
1456
1457 // Recover callee-saved registers.
1458 if (NeedsDwarfCFI) {
1459 for (const CalleeSavedInfo &CS :
1460 getUnmanagedInterruptCSI(MF, CSI, PreferAscendingLS)) {
1461 MCRegister Reg = CS.getReg();
1462 // Emit CFI for both sub-registers.
1463 if (RISCV::GPRPairRegClass.contains(Reg)) {
1464 MCRegister EvenReg = RI->getSubReg(Reg, RISCV::sub_gpr_even);
1465 MCRegister OddReg = RI->getSubReg(Reg, RISCV::sub_gpr_odd);
1466 CFIBuilder.buildRestore(EvenReg);
1467 CFIBuilder.buildRestore(OddReg);
1468 } else {
1469 CFIBuilder.buildRestore(Reg);
1470 }
1471 }
1472 }
1473
1474 if (RVFI->isPushable(MF) && MBBI != MBB.end() && isPop(MBBI->getOpcode())) {
1475 // Use available stack adjustment in pop instruction to deallocate stack
1476 // space. Align the stack size down to a multiple of 16. This is needed for
1477 // RVE.
1478 // FIXME: Can we increase the stack size to a multiple of 16 instead?
1479 uint64_t StackAdj =
1480 std::min(alignDown(StackSize, 16), static_cast<uint64_t>(48));
1481 MBBI->getOperand(1).setImm(StackAdj);
1482 StackSize -= StackAdj;
1483
1484 if (StackSize != 0)
1485 deallocateStack(MF, MBB, MBBI, DL, StackSize,
1486 /*stack_adj of cm.pop instr*/ RealStackSize - StackSize);
1487
1488 auto NextI = next_nodbg(MBBI, MBB.end());
1489 if (NextI == MBB.end() || NextI->getOpcode() != RISCV::PseudoRET) {
1490 ++MBBI;
1491 if (NeedsDwarfCFI) {
1492 CFIBuilder.setInsertPoint(MBBI);
1493
1494 for (const CalleeSavedInfo &CS : getPushOrLibCallsSavedInfo(MF, CSI))
1495 CFIBuilder.buildRestore(CS.getReg());
1496
1497 // Update CFA Offset. If this is a QCI interrupt function, there will
1498 // be a leftover offset which is deallocated by `QC.C.MILEAVERET`,
1499 // otherwise getQCIInterruptStackSize() will be 0.
1500 CFIBuilder.buildDefCFAOffset(RVFI->getQCIInterruptStackSize());
1501 }
1502 }
1503 }
1504
1505 // Deallocate stack if StackSize isn't a zero yet. If this is a QCI interrupt
1506 // function, there will be a leftover offset which is deallocated by
1507 // `QC.C.MILEAVERET`, otherwise getQCIInterruptStackSize() will be 0.
1508 if (StackSize != 0)
1509 deallocateStack(MF, MBB, MBBI, DL, StackSize,
1510 RVFI->getQCIInterruptStackSize());
1511
1512 // Emit epilogue for shadow call stack.
1513 emitSCSEpilogue(MF, MBB, MBBI, DL);
1514
1515 // SiFive CLIC needs to swap `sf.mscratchcsw` into `sp`
1517}
1518
1520 MCRegister Reg) {
1521 if (RISCV::GPRRegClass.contains(Reg))
1522 return Reg;
1523
1524 std::array<TargetRegisterClass const *, 2> RegisterClasses = {
1525 &RISCV::GPRF16RegClass, &RISCV::GPRF32RegClass};
1526 std::array<unsigned, 2> SubIdx = {RISCV::sub_16, RISCV::sub_32};
1527
1528 for (auto [RegClass, SubReg] : zip(RegisterClasses, SubIdx)) {
1529 if (RegClass->contains(Reg)) {
1530 if (MCRegister Super =
1531 TRI.getMatchingSuperReg(Reg, SubReg, &RISCV::GPRRegClass))
1532 return Super;
1533 }
1534 }
1535
1537 "getPhysicalGPR called with unsupported register");
1538}
1539
1541 const TargetRegisterInfo &TRI,
1542 MCRegister Reg) {
1543 if (!STI.hasStdExtF())
1544 return MCRegister();
1545
1546 TargetRegisterClass const *LargestFPRegClass = STI.getLargestFPRegClass();
1547 assert(LargestFPRegClass);
1548
1549 if (LargestFPRegClass->contains(Reg))
1550 return Reg;
1551
1552 std::array<TargetRegisterClass const *, 3> RegisterClasses = {
1553 &RISCV::FPR16RegClass, &RISCV::FPR32RegClass, &RISCV::FPR64RegClass};
1554 std::array<unsigned, 3> SubIdx = {RISCV::sub_16, RISCV::sub_32,
1555 RISCV::sub_64};
1556
1557 for (auto [RegClass, SubReg] : zip(RegisterClasses, SubIdx)) {
1558 if (RegClass->contains(Reg)) {
1559 if (MCRegister Super =
1560 TRI.getMatchingSuperReg(Reg, SubReg, LargestFPRegClass))
1561 return Super;
1562 }
1563 }
1564
1565 // Reg is bigger than what's currently available for the target, we can ignore
1566 // it.
1567 return MCRegister();
1568}
1569
1570void RISCVFrameLowering::emitZeroCallUsedRegs(BitVector RegsToZero,
1572 RegScavenger *RS) const {
1573 // Insertion point.
1575
1576 // Fake a debug loc.
1577 DebugLoc DL;
1578 if (MBBI != MBB.end())
1579 DL = MBBI->getDebugLoc();
1580
1581 const MachineFunction &MF = *MBB.getParent();
1582 const RISCVRegisterInfo &TRI = *STI.getRegisterInfo();
1583 const RISCVInstrInfo &TII = *STI.getInstrInfo();
1584
1585 BitVector FinalRegsToZero(TRI.getNumRegs());
1586
1587 bool HasVRegister = false;
1588
1589 for (MCRegister Reg : RegsToZero.set_bits()) {
1590 if (TRI.isGeneralPurposeRegister(MF, Reg)) {
1591 FinalRegsToZero.set(getPhysicalGPR(TRI, Reg).id());
1592 } else if (RISCV::GPRPairRegClass.contains(Reg)) {
1593 FinalRegsToZero.set(
1594 getPhysicalGPR(TRI, TRI.getSubReg(Reg, RISCV::sub_gpr_even)).id());
1595 FinalRegsToZero.set(
1596 getPhysicalGPR(TRI, TRI.getSubReg(Reg, RISCV::sub_gpr_odd)).id());
1597 } else if (TRI.isFPRegister(Reg)) {
1598 if (MCRegister MaybeReg = getLargestFPRegisterOrZero(STI, TRI, Reg))
1599 FinalRegsToZero.set(MaybeReg.id());
1601 TRI.getMinimalPhysRegClass(Reg))) {
1602 if (!STI.hasVInstructions())
1603 continue;
1604 HasVRegister = true;
1605
1606 for (MCRegister SubReg : TRI.subregs_inclusive(Reg)) {
1607 if (TRI.subregs(SubReg).empty())
1608 FinalRegsToZero.set(SubReg.id());
1609 }
1610 }
1611 }
1612
1613 if (HasVRegister) {
1614 RISCVVType::VLMUL VLMUL = RISCVVType::encodeLMUL(1, /*Fractional=*/false);
1615 unsigned VTypeImm = RISCVVType::encodeVTYPE(
1616 VLMUL, /*SEW=*/32, /*TailAgnostic=*/true, /*MaskAgnostic=*/true);
1617
1618 MCRegister TemporaryReg = RISCV::NoRegister;
1619 for (MCRegister Reg : FinalRegsToZero.set_bits()) {
1620 if (TRI.isGeneralPurposeRegister(MF, Reg)) {
1621 TemporaryReg = Reg;
1622 break;
1623 }
1624 }
1625
1626 if (TemporaryReg == RISCV::NoRegister) {
1627 RS->enterBasicBlockEnd(MBB);
1628 TemporaryReg = RS->scavengeRegisterBackwards(RISCV::GPRRegClass, MBBI,
1629 /*RestoreAfter=*/false,
1630 /*SPAdj=*/0);
1631 }
1632
1633 if (MBB.getParent()
1634 ->getFunction()
1635 .getFnAttribute("zero-call-used-regs")
1636 .getValueAsString() == "used")
1637 FinalRegsToZero.set(TemporaryReg.id());
1638
1639 BuildMI(MBB, MBBI, DL, TII.get(RISCV::VSETVLI), TemporaryReg)
1640 .addReg(RISCV::X0)
1641 .addImm(VTypeImm)
1642 .addReg(RISCV::VL, RegState::ImplicitDefine)
1643 .addReg(RISCV::VTYPE, RegState::ImplicitDefine);
1644 }
1645
1646 for (MCRegister Reg : FinalRegsToZero.set_bits())
1647 TII.buildClearRegister(Reg, MBB, MBBI, DL);
1648}
1649
1652 Register &FrameReg) const {
1653 const MachineFrameInfo &MFI = MF.getFrameInfo();
1655 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1656
1657 // Callee-saved registers should be referenced relative to the stack
1658 // pointer (positive offset), otherwise use the frame pointer (negative
1659 // offset).
1660 const auto &CSI = getUnmanagedCSI(MF, MFI.getCalleeSavedInfo(),
1661 STI.preferAscendingLoadStore());
1662 int MinCSFI = 0;
1663 int MaxCSFI = -1;
1665 auto StackID = MFI.getStackID(FI);
1666
1667 assert((StackID == TargetStackID::Default ||
1668 StackID == TargetStackID::ScalableVector) &&
1669 "Unexpected stack ID for the frame object.");
1670 if (StackID == TargetStackID::Default) {
1671 assert(getOffsetOfLocalArea() == 0 && "LocalAreaOffset is not 0!");
1673 MFI.getOffsetAdjustment());
1674 } else if (StackID == TargetStackID::ScalableVector) {
1676 }
1677
1678 uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
1679
1680 if (CSI.size()) {
1681 MinCSFI = std::min(CSI.front().getFrameIdx(), CSI.back().getFrameIdx());
1682 MaxCSFI = std::max(CSI.front().getFrameIdx(), CSI.back().getFrameIdx());
1683 }
1684
1685 bool IsInterruptCSR = RVFI->isSiFivePreemptibleInterrupt(MF) &&
1686 (FI == RVFI->getInterruptCSRFrameIndex(0) ||
1687 FI == RVFI->getInterruptCSRFrameIndex(1));
1688 if ((FI >= MinCSFI && FI <= MaxCSFI) || IsInterruptCSR) {
1689 FrameReg = SPReg;
1690
1691 if (FirstSPAdjustAmount)
1692 Offset += StackOffset::getFixed(FirstSPAdjustAmount);
1693 else
1695 return Offset;
1696 }
1697
1698 if (RI->hasStackRealignment(MF) && !MFI.isFixedObjectIndex(FI)) {
1699 // If the stack was realigned, the frame pointer is set in order to allow
1700 // SP to be restored, so we need another base register to record the stack
1701 // after realignment.
1702 // |--------------------------| --
1703 // | callee-allocated save | | <----|
1704 // | area for register varargs| | |
1705 // |--------------------------| <-- FP |
1706 // | callee-saved registers | | |
1707 // |--------------------------| -- |
1708 // | realignment (the size of | | |
1709 // | this area is not counted | | |
1710 // | in MFI.getStackSize()) | | |
1711 // |--------------------------| -- |-- MFI.getStackSize()
1712 // | RVV alignment padding | | |
1713 // | (not counted in | | |
1714 // | MFI.getStackSize() but | | |
1715 // | counted in | | |
1716 // | RVFI.getRVVStackSize()) | | |
1717 // |--------------------------| -- |
1718 // | RVV objects | | |
1719 // | (not counted in | | |
1720 // | MFI.getStackSize()) | | |
1721 // |--------------------------| -- |
1722 // | padding before RVV | | |
1723 // | (not counted in | | |
1724 // | MFI.getStackSize() or in | | |
1725 // | RVFI.getRVVStackSize()) | | |
1726 // |--------------------------| -- |
1727 // | scalar local variables | | <----'
1728 // |--------------------------| -- <-- BP (if var sized objects present)
1729 // | VarSize objects | |
1730 // |--------------------------| -- <-- SP
1731 if (hasBP(MF)) {
1732 FrameReg = RISCVABI::getBPReg();
1733 } else {
1734 // VarSize objects must be empty in this case!
1735 assert(!MFI.hasVarSizedObjects());
1736 FrameReg = SPReg;
1737 }
1738 } else if (!RI->hasStackRealignment(MF)) {
1739 // Note: Keeping the following as multiple 'if' statements rather than
1740 // merging to a single expression for readability.
1741 if (!hasFP(MF)) {
1742 // No FP available, must use SP.
1743 FrameReg = SPReg;
1744 } else {
1745 FrameReg = FPReg;
1746 // SP-relative addressing is only valid when SP is stable throughout
1747 // the function body: no dynamic SP adjustments for outgoing call args,
1748 // no variable-sized objects, and no RVV scalable stack regions.
1749 // hasReservedCallFrame() conservatively encompasses all these checks.
1750 if (hasReservedCallFrame(MF)) {
1751 // Both FP and SP are candidates.
1752 // Prefer SP when the SP-relative offset fits in the compressed
1753 // instruction immediate range.
1754 int64_t SPOff = Offset.getFixed() + MFI.getStackSize();
1755 int64_t CLWSPMaxOffset = 252;
1756 int64_t CLDSPMaxOffset = 504;
1757 int64_t SPThreshold = STI.is64Bit() ? CLDSPMaxOffset : CLWSPMaxOffset;
1758 if (SPOff >= 0 && SPOff <= SPThreshold)
1759 FrameReg = SPReg;
1760 }
1761 }
1762 } else {
1763 assert(RI->hasStackRealignment(MF) && MFI.isFixedObjectIndex(FI) &&
1764 "Expected fixed object with stack realignment");
1765 assert(hasFP(MF) && "Re-aligned stack must have frame pointer");
1766 FrameReg = FPReg;
1767 }
1768
1769 if (FrameReg == FPReg) {
1770 Offset += StackOffset::getFixed(RVFI->getVarArgsSaveSize());
1771 // When using FP to access scalable vector objects, we need to minus
1772 // the frame size.
1773 //
1774 // |--------------------------| --
1775 // | callee-allocated save | |
1776 // | area for register varargs| |
1777 // |--------------------------| | -- <-- FP
1778 // | callee-saved registers | |
1779 // |--------------------------| | MFI.getStackSize()
1780 // | scalar local variables | |
1781 // |--------------------------| -- (Offset of RVV objects is from here.)
1782 // | RVV objects |
1783 // |--------------------------|
1784 // | VarSize objects |
1785 // |--------------------------| <-- SP
1786 if (StackID == TargetStackID::ScalableVector) {
1787 assert(!RI->hasStackRealignment(MF) &&
1788 "Can't index across variable sized realign");
1789 // We don't expect any extra RVV alignment padding, as the stack size
1790 // and RVV object sections should be correct aligned in their own
1791 // right.
1793 "Inconsistent stack layout");
1795 }
1796 return Offset;
1797 }
1798
1799 // This case handles indexing off both SP and BP.
1800 // If indexing off SP, there must not be any var sized objects
1801 assert(FrameReg == RISCVABI::getBPReg() || !MFI.hasVarSizedObjects());
1802
1803 // When using SP to access frame objects, we need to add RVV stack size.
1804 //
1805 // |--------------------------| --
1806 // | callee-allocated save | | <----|
1807 // | area for register varargs| | |
1808 // |--------------------------| | | <-- FP
1809 // | callee-saved registers | | |
1810 // |--------------------------| -- |
1811 // | RVV alignment padding | | |
1812 // | (not counted in | | |
1813 // | MFI.getStackSize() but | | |
1814 // | counted in | | |
1815 // | RVFI.getRVVStackSize()) | | |
1816 // |--------------------------| -- |
1817 // | RVV objects | | |-- MFI.getStackSize()
1818 // | (not counted in | | |
1819 // | MFI.getStackSize()) | | |
1820 // |--------------------------| -- |
1821 // | padding before RVV | | |
1822 // | (not counted in | | |
1823 // | MFI.getStackSize()) | | |
1824 // |--------------------------| -- |
1825 // | scalar local variables | | <----'
1826 // |--------------------------| -- <-- BP (if var sized objects present)
1827 // | VarSize objects | |
1828 // |--------------------------| -- <-- SP
1829 //
1830 // The total amount of padding surrounding RVV objects is described by
1831 // RVV->getRVVPadding() and it can be zero. It allows us to align the RVV
1832 // objects to the required alignment.
1833 if (MFI.getStackID(FI) == TargetStackID::Default) {
1834 if (MFI.isFixedObjectIndex(FI)) {
1835 assert(!RI->hasStackRealignment(MF) &&
1836 "Can't index across variable sized realign");
1838 RVFI->getRVVStackSize());
1839 } else {
1841 }
1842 } else if (MFI.getStackID(FI) == TargetStackID::ScalableVector) {
1843 // Ensure the base of the RVV stack is correctly aligned: add on the
1844 // alignment padding.
1845 int64_t ScalarLocalVarSize =
1846 MFI.getStackSize() - RVFI->getCalleeSavedStackSize() -
1847 RVFI->getVarArgsSaveSize() + RVFI->getRVVPadding();
1848 Offset += StackOffset::get(ScalarLocalVarSize, RVFI->getRVVStackSize());
1849 }
1850 return Offset;
1851}
1852
1854 const Register &Reg) {
1855 MCRegister BaseReg = TRI.getSubReg(Reg, RISCV::sub_vrm1_0);
1856 // If it's not a grouped vector register, it doesn't have subregister, so
1857 // the base register is just itself.
1858 if (!BaseReg.isValid())
1859 BaseReg = Reg;
1860 return BaseReg;
1861}
1862
1864 BitVector &SavedRegs,
1865 RegScavenger *RS) const {
1867
1868 // In TargetFrameLowering::determineCalleeSaves, any vector register is marked
1869 // as saved if any of its subregister is clobbered, this is not correct in
1870 // vector registers. We only want the vector register to be marked as saved
1871 // if all of its subregisters are clobbered.
1872 // For example:
1873 // Original behavior: If v24 is marked, v24m2, v24m4, v24m8 are also marked.
1874 // Correct behavior: v24m2 is marked only if v24 and v25 are marked.
1875 MachineRegisterInfo &MRI = MF.getRegInfo();
1876 const MCPhysReg *CSRegs = MRI.getCalleeSavedRegs();
1877 const RISCVRegisterInfo &TRI = *STI.getRegisterInfo();
1878 for (unsigned i = 0; CSRegs[i]; ++i) {
1879 unsigned CSReg = CSRegs[i];
1880 // Only vector registers need special care.
1881 if (!RISCV::VRRegClass.contains(getRVVBaseRegister(TRI, CSReg)))
1882 continue;
1883
1884 SavedRegs.reset(CSReg);
1885
1886 auto SubRegs = TRI.subregs(CSReg);
1887 // Set the register and all its subregisters.
1888 if (!MRI.def_empty(CSReg) || MRI.getUsedPhysRegsMask().test(CSReg)) {
1889 SavedRegs.set(CSReg);
1890 for (unsigned Reg : SubRegs)
1891 SavedRegs.set(Reg);
1892 }
1893
1894 }
1895
1896 // Unconditionally spill RA and FP only if the function uses a frame
1897 // pointer.
1898 if (hasFP(MF)) {
1899 SavedRegs.set(RAReg);
1900 SavedRegs.set(FPReg);
1901 }
1902 // Mark BP as used if function has dedicated base pointer.
1903 if (hasBP(MF))
1904 SavedRegs.set(RISCVABI::getBPReg());
1905
1906 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1907 // X5 is used as a temporary for saving and restoring `mcause` and `mepc`.
1908 if (RVFI->isSiFivePreemptibleInterrupt(MF))
1909 SavedRegs.set(RISCV::X5);
1910
1911 // When using cm.push/pop we must save X27 if we save X26.
1912 if (RVFI->isPushable(MF) && SavedRegs.test(RISCV::X26))
1913 SavedRegs.set(RISCV::X27);
1914
1915 // For Zilsd on RV32, append GPRPair registers to the CSR list. This prevents
1916 // the need to create register sets for each abi which is a lot more complex.
1917 // Don't use Zilsd for callee-saved coalescing if the required alignment
1918 // exceeds the stack alignment or when Zcmp/Xqccmp or save/restore libcalls
1919 // are enabled.
1920 bool UseZilsd = !STI.is64Bit() && STI.hasStdExtZilsd() &&
1921 STI.getZilsdAlign() <= getStackAlign() &&
1922 !RVFI->isPushable(MF) && !RVFI->useSaveRestoreLibCalls(MF);
1923 if (UseZilsd) {
1926 for (unsigned i = 0; CSRegs[i]; ++i) {
1927 NewCSRs.push_back(CSRegs[i]);
1928 CSRSet.insert(CSRegs[i]);
1929 }
1930
1931 // Append GPRPair registers for pairs where both sub-registers are in CSR
1932 // list. Iterate through all GPRPairs and check if both sub-regs are CSRs.
1933 for (MCPhysReg Pair : RISCV::GPRPairRegClass) {
1934 // Do not append a pair that's already in the CSR list.
1935 if (CSRSet.contains(Pair))
1936 continue;
1937 MCRegister EvenReg = TRI.getSubReg(Pair, RISCV::sub_gpr_even);
1938 MCRegister OddReg = TRI.getSubReg(Pair, RISCV::sub_gpr_odd);
1939 if (CSRSet.contains(EvenReg.id()) && CSRSet.contains(OddReg.id())) {
1940 NewCSRs.push_back(Pair);
1941 CSRSet.insert(Pair);
1942 }
1943 }
1944
1945 MRI.setCalleeSavedRegs(NewCSRs);
1946 CSRegs = MRI.getCalleeSavedRegs();
1947 }
1948
1949 // Check if all subregisters are marked for saving. If so, set the super
1950 // register bit. For GPRPair, only check sub_gpr_even and sub_gpr_odd, not
1951 // aliases like X8_W or X8_H which are not set in SavedRegs.
1952 for (unsigned i = 0; CSRegs[i]; ++i) {
1953 MCRegister CSReg = CSRegs[i];
1954 bool CombineToSuperReg;
1955 if (RISCV::GPRPairRegClass.contains(CSReg)) {
1956 MCRegister EvenReg = TRI.getSubReg(CSReg, RISCV::sub_gpr_even);
1957 MCRegister OddReg = TRI.getSubReg(CSReg, RISCV::sub_gpr_odd);
1958 CombineToSuperReg =
1959 SavedRegs.test(EvenReg.id()) && SavedRegs.test(OddReg.id());
1960 // If s0(x8) is used as FP we can't generate load/store pair because it
1961 // breaks the frame chain.
1962 if (hasFP(MF) && CSReg == RISCV::X8_X9)
1963 CombineToSuperReg = false;
1964 } else {
1965 auto SubRegs = TRI.subregs(CSReg);
1966 CombineToSuperReg =
1967 !SubRegs.empty() && llvm::all_of(SubRegs, [&](unsigned Reg) {
1968 return SavedRegs.test(Reg);
1969 });
1970 }
1971
1972 if (CombineToSuperReg)
1973 SavedRegs.set(CSReg);
1974 }
1975
1976 // SiFive Preemptible Interrupt Handlers need additional frame entries
1978}
1979
1980std::pair<int64_t, Align>
1981RISCVFrameLowering::assignRVVStackObjectOffsets(MachineFunction &MF) const {
1982 MachineFrameInfo &MFI = MF.getFrameInfo();
1983 // Create a buffer of RVV objects to allocate.
1984 SmallVector<int, 8> ObjectsToAllocate;
1985 auto pushRVVObjects = [&](int FIBegin, int FIEnd) {
1986 for (int I = FIBegin, E = FIEnd; I != E; ++I) {
1987 unsigned StackID = MFI.getStackID(I);
1988 if (StackID != TargetStackID::ScalableVector)
1989 continue;
1990 if (MFI.isDeadObjectIndex(I))
1991 continue;
1992
1993 ObjectsToAllocate.push_back(I);
1994 }
1995 };
1996 // First push RVV Callee Saved object, then push RVV stack object
1997 std::vector<CalleeSavedInfo> &CSI = MF.getFrameInfo().getCalleeSavedInfo();
1998 const auto &RVVCSI = getRVVCalleeSavedInfo(MF, CSI);
1999 if (!RVVCSI.empty())
2000 pushRVVObjects(RVVCSI[0].getFrameIdx(),
2001 RVVCSI[RVVCSI.size() - 1].getFrameIdx() + 1);
2002 pushRVVObjects(0, MFI.getObjectIndexEnd() - RVVCSI.size());
2003
2004 // The minimum alignment is 16 bytes.
2005 Align RVVStackAlign(16);
2006 const auto &ST = MF.getSubtarget<RISCVSubtarget>();
2007
2008 if (!ST.hasVInstructions()) {
2009 assert(ObjectsToAllocate.empty() &&
2010 "Can't allocate scalable-vector objects without V instructions");
2011 return std::make_pair(0, RVVStackAlign);
2012 }
2013
2014 // Allocate all RVV locals and spills
2015 int64_t Offset = 0;
2016 for (int FI : ObjectsToAllocate) {
2017 // ObjectSize in bytes.
2018 int64_t ObjectSize = MFI.getObjectSize(FI);
2019 auto ObjectAlign =
2020 std::max(Align(RISCV::RVVBytesPerBlock), MFI.getObjectAlign(FI));
2021 // If the data type is the fractional vector type, reserve one vector
2022 // register for it.
2023 if (ObjectSize < RISCV::RVVBytesPerBlock)
2024 ObjectSize = RISCV::RVVBytesPerBlock;
2025 Offset = alignTo(Offset + ObjectSize, ObjectAlign);
2026 MFI.setObjectOffset(FI, -Offset);
2027 // Update the maximum alignment of the RVV stack section
2028 RVVStackAlign = std::max(RVVStackAlign, ObjectAlign);
2029 }
2030
2031 uint64_t StackSize = Offset;
2032
2033 // Ensure the alignment of the RVV stack. Since we want the most-aligned
2034 // object right at the bottom (i.e., any padding at the top of the frame),
2035 // readjust all RVV objects down by the alignment padding.
2036 // Stack size and offsets are multiples of vscale, stack alignment is in
2037 // bytes, we can divide stack alignment by minimum vscale to get a maximum
2038 // stack alignment multiple of vscale.
2039 auto VScale =
2040 std::max<uint64_t>(ST.getRealMinVLen() / RISCV::RVVBitsPerBlock, 1);
2041 if (auto RVVStackAlignVScale = RVVStackAlign.value() / VScale) {
2042 if (auto AlignmentPadding =
2043 offsetToAlignment(StackSize, Align(RVVStackAlignVScale))) {
2044 StackSize += AlignmentPadding;
2045 for (int FI : ObjectsToAllocate)
2046 MFI.setObjectOffset(FI, MFI.getObjectOffset(FI) - AlignmentPadding);
2047 }
2048 }
2049
2050 return std::make_pair(StackSize, RVVStackAlign);
2051}
2052
2054 // For RVV spill, scalable stack offsets computing requires up to two scratch
2055 // registers
2056 static constexpr unsigned ScavSlotsNumRVVSpillScalableObject = 2;
2057
2058 // For RVV spill, non-scalable stack offsets computing requires up to one
2059 // scratch register.
2060 static constexpr unsigned ScavSlotsNumRVVSpillNonScalableObject = 1;
2061
2062 // ADDI instruction's destination register can be used for computing
2063 // offsets. So Scalable stack offsets require up to one scratch register.
2064 static constexpr unsigned ScavSlotsADDIScalableObject = 1;
2065
2066 static constexpr unsigned MaxScavSlotsNumKnown =
2067 std::max({ScavSlotsADDIScalableObject, ScavSlotsNumRVVSpillScalableObject,
2068 ScavSlotsNumRVVSpillNonScalableObject});
2069
2070 unsigned MaxScavSlotsNum = 0;
2072 return false;
2073 for (const MachineBasicBlock &MBB : MF)
2074 for (const MachineInstr &MI : MBB) {
2075 bool IsRVVSpill = RISCV::isRVVSpill(MI);
2076 for (auto &MO : MI.operands()) {
2077 if (!MO.isFI())
2078 continue;
2079 bool IsScalableVectorID = MF.getFrameInfo().getStackID(MO.getIndex()) ==
2081 if (IsRVVSpill) {
2082 MaxScavSlotsNum = std::max(
2083 MaxScavSlotsNum, IsScalableVectorID
2084 ? ScavSlotsNumRVVSpillScalableObject
2085 : ScavSlotsNumRVVSpillNonScalableObject);
2086 } else if (MI.getOpcode() == RISCV::ADDI && IsScalableVectorID) {
2087 MaxScavSlotsNum =
2088 std::max(MaxScavSlotsNum, ScavSlotsADDIScalableObject);
2089 }
2090 }
2091 if (MaxScavSlotsNum == MaxScavSlotsNumKnown)
2092 return MaxScavSlotsNumKnown;
2093 }
2094 return MaxScavSlotsNum;
2095}
2096
2097static bool hasRVVFrameObject(const MachineFunction &MF) {
2098 // Originally, the function will scan all the stack objects to check whether
2099 // if there is any scalable vector object on the stack or not. However, it
2100 // causes errors in the register allocator. In issue 53016, it returns false
2101 // before RA because there is no RVV stack objects. After RA, it returns true
2102 // because there are spilling slots for RVV values during RA. It will not
2103 // reserve BP during register allocation and generate BP access in the PEI
2104 // pass due to the inconsistent behavior of the function.
2105 //
2106 // The function is changed to use hasVInstructions() as the return value. It
2107 // is not precise, but it can make the register allocation correct.
2108 //
2109 // FIXME: Find a better way to make the decision or revisit the solution in
2110 // D103622.
2111 //
2112 // Refer to https://github.com/llvm/llvm-project/issues/53016.
2113 return MF.getSubtarget<RISCVSubtarget>().hasVInstructions();
2114}
2115
2117 const RISCVInstrInfo &TII) {
2118 unsigned FnSize = 0;
2119 for (auto &MBB : MF) {
2120 for (auto &MI : MBB) {
2121 // Far branches over 20-bit offset will be relaxed in branch relaxation
2122 // pass. In the worst case, conditional branches will be relaxed into
2123 // the following instruction sequence. Unconditional branches are
2124 // relaxed in the same way, with the exception that there is no first
2125 // branch instruction.
2126 //
2127 // foo
2128 // bne t5, t6, .rev_cond # `TII->getInstSizeInBytes(MI)` bytes
2129 // sd s11, 0(sp) # 4 bytes, or 2 bytes with Zca
2130 // jump .restore, s11 # 8 bytes
2131 // .rev_cond
2132 // bar
2133 // j .dest_bb # 4 bytes, or 2 bytes with Zca
2134 // .restore:
2135 // ld s11, 0(sp) # 4 bytes, or 2 bytes with Zca
2136 // .dest:
2137 // baz
2138 if (MI.isConditionalBranch())
2139 FnSize += TII.getInstSizeInBytes(MI);
2140 if (MI.isConditionalBranch() || MI.isUnconditionalBranch()) {
2141 if (MF.getSubtarget<RISCVSubtarget>().hasStdExtZca())
2142 FnSize += 2 + 8 + 2 + 2;
2143 else
2144 FnSize += 4 + 8 + 4 + 4;
2145 continue;
2146 }
2147
2148 FnSize += TII.getInstSizeInBytes(MI);
2149 }
2150 }
2151 return FnSize;
2152}
2153
2155 MachineFunction &MF, RegScavenger *RS) const {
2156 const RISCVRegisterInfo *RegInfo =
2157 MF.getSubtarget<RISCVSubtarget>().getRegisterInfo();
2158 const RISCVInstrInfo *TII = MF.getSubtarget<RISCVSubtarget>().getInstrInfo();
2159 MachineFrameInfo &MFI = MF.getFrameInfo();
2160 const TargetRegisterClass *RC = &RISCV::GPRRegClass;
2161 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
2162
2163 int64_t RVVStackSize;
2164 Align RVVStackAlign;
2165 std::tie(RVVStackSize, RVVStackAlign) = assignRVVStackObjectOffsets(MF);
2166
2167 RVFI->setRVVStackSize(RVVStackSize);
2168 RVFI->setRVVStackAlign(RVVStackAlign);
2169
2170 if (hasRVVFrameObject(MF)) {
2171 // Ensure the entire stack is aligned to at least the RVV requirement: some
2172 // scalable-vector object alignments are not considered by the
2173 // target-independent code.
2174 MFI.ensureMaxAlignment(RVVStackAlign);
2175 }
2176
2177 unsigned ScavSlotsNum = 0;
2178
2179 // estimateStackSize has been observed to under-estimate the final stack
2180 // size, so give ourselves wiggle-room by checking for stack size
2181 // representable an 11-bit signed field rather than 12-bits.
2182 if (!isInt<11>(MFI.estimateStackSize(MF)))
2183 ScavSlotsNum = 1;
2184
2185 // Far branches over 20-bit offset require a spill slot for scratch register.
2186 bool IsLargeFunction = !isInt<20>(estimateFunctionSizeInBytes(MF, *TII));
2187 if (IsLargeFunction)
2188 ScavSlotsNum = std::max(ScavSlotsNum, 1u);
2189
2190 // RVV loads & stores have no capacity to hold the immediate address offsets
2191 // so we must always reserve an emergency spill slot if the MachineFunction
2192 // contains any RVV spills.
2193 ScavSlotsNum = std::max(ScavSlotsNum, getScavSlotsNumForRVV(MF));
2194
2195 for (unsigned I = 0; I < ScavSlotsNum; I++) {
2196 int FI = MFI.CreateSpillStackObject(RegInfo->getSpillSize(*RC),
2197 RegInfo->getSpillAlign(*RC));
2198 RS->addScavengingFrameIndex(FI);
2199
2200 if (IsLargeFunction && RVFI->getBranchRelaxationScratchFrameIndex() == -1)
2201 RVFI->setBranchRelaxationScratchFrameIndex(FI);
2202 }
2203
2204 unsigned Size = RVFI->getReservedSpillsSize();
2205 for (const auto &Info : MFI.getCalleeSavedInfo()) {
2206 int FrameIdx = Info.getFrameIdx();
2207 if (FrameIdx < 0 || MFI.getStackID(FrameIdx) != TargetStackID::Default)
2208 continue;
2209
2210 Size += MFI.getObjectSize(FrameIdx);
2211 }
2212 RVFI->setCalleeSavedStackSize(Size);
2213}
2214
2215// Not preserve stack space within prologue for outgoing variables when the
2216// function contains variable size objects or there are vector objects accessed
2217// by the frame pointer.
2218// Let eliminateCallFramePseudoInstr preserve stack space for it.
2220 return !MF.getFrameInfo().hasVarSizedObjects() &&
2221 !(hasFP(MF) && hasRVVFrameObject(MF));
2222}
2223
2224// Eliminate ADJCALLSTACKDOWN, ADJCALLSTACKUP pseudo instructions.
2228 DebugLoc DL = MI->getDebugLoc();
2229
2230 if (!hasReservedCallFrame(MF)) {
2231 // If space has not been reserved for a call frame, ADJCALLSTACKDOWN and
2232 // ADJCALLSTACKUP must be converted to instructions manipulating the stack
2233 // pointer. This is necessary when there is a variable length stack
2234 // allocation (e.g. alloca), which means it's not possible to allocate
2235 // space for outgoing arguments from within the function prologue.
2236 int64_t Amount = MI->getOperand(0).getImm();
2237
2238 if (Amount != 0) {
2239 // Ensure the stack remains aligned after adjustment.
2240 Amount = alignSPAdjust(Amount);
2241
2242 if (MI->getOpcode() == RISCV::ADJCALLSTACKDOWN)
2243 Amount = -Amount;
2244
2245 const RISCVTargetLowering *TLI =
2246 MF.getSubtarget<RISCVSubtarget>().getTargetLowering();
2247 int64_t ProbeSize = TLI->getStackProbeSize(MF, getStackAlign());
2248 if (TLI->hasInlineStackProbe(MF) && -Amount >= ProbeSize) {
2249 // When stack probing is enabled, the decrement of SP may need to be
2250 // probed. We can handle both the decrement and the probing in
2251 // allocateStack.
2252 bool DynAllocation =
2253 MF.getInfo<RISCVMachineFunctionInfo>()->hasDynamicAllocation();
2254 allocateStack(MBB, MI, MF, -Amount, -Amount,
2255 needsDwarfCFI(MF) && !hasFP(MF),
2256 /*NeedProbe=*/true, ProbeSize, DynAllocation,
2258 inlineStackProbe(MF, MBB);
2259 } else {
2260 const RISCVRegisterInfo &RI = *STI.getRegisterInfo();
2263 }
2264 }
2265 }
2266
2267 return MBB.erase(MI);
2268}
2269
2270// We would like to split the SP adjustment to reduce prologue/epilogue
2271// as following instructions. In this way, the offset of the callee saved
2272// register could fit in a single store. Supposed that the first sp adjust
2273// amount is 2032.
2274// add sp,sp,-2032
2275// sw ra,2028(sp)
2276// sw s0,2024(sp)
2277// sw s1,2020(sp)
2278// sw s3,2012(sp)
2279// sw s4,2008(sp)
2280// add sp,sp,-64
2281uint64_t
2283 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
2284 const MachineFrameInfo &MFI = MF.getFrameInfo();
2285 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
2286 uint64_t StackSize = getStackSizeWithRVVPadding(MF);
2287
2288 // Disable SplitSPAdjust if save-restore libcall, push/pop or QCI interrupts
2289 // are used. The callee-saved registers will be pushed by the save-restore
2290 // libcalls, so we don't have to split the SP adjustment in this case.
2291 if (RVFI->getReservedSpillsSize())
2292 return 0;
2293
2294 // Return the FirstSPAdjustAmount if the StackSize can not fit in a signed
2295 // 12-bit and there exists a callee-saved register needing to be pushed.
2296 if (!isInt<12>(StackSize) && (CSI.size() > 0)) {
2297 // FirstSPAdjustAmount is chosen at most as (2048 - StackAlign) because
2298 // 2048 will cause sp = sp + 2048 in the epilogue to be split into multiple
2299 // instructions. Offsets smaller than 2048 can fit in a single load/store
2300 // instruction, and we have to stick with the stack alignment. 2048 has
2301 // 16-byte alignment. The stack alignment for RV32 and RV64 is 16 and for
2302 // RV32E it is 4. So (2048 - StackAlign) will satisfy the stack alignment.
2303 const uint64_t StackAlign = getStackAlign().value();
2304
2305 // Amount of (2048 - StackAlign) will prevent callee saved and restored
2306 // instructions be compressed, so try to adjust the amount to the largest
2307 // offset that stack compression instructions accept when target supports
2308 // compression instructions.
2309 if (STI.hasStdExtZca()) {
2310 // The compression extensions may support the following instructions:
2311 // riscv32: c.lwsp rd, offset[7:2] => 2^(6 + 2)
2312 // c.swsp rs2, offset[7:2] => 2^(6 + 2)
2313 // c.flwsp rd, offset[7:2] => 2^(6 + 2)
2314 // c.fswsp rs2, offset[7:2] => 2^(6 + 2)
2315 // riscv64: c.ldsp rd, offset[8:3] => 2^(6 + 3)
2316 // c.sdsp rs2, offset[8:3] => 2^(6 + 3)
2317 // c.fldsp rd, offset[8:3] => 2^(6 + 3)
2318 // c.fsdsp rs2, offset[8:3] => 2^(6 + 3)
2319 const uint64_t RVCompressLen = STI.getXLen() * 8;
2320 // Compared with amount (2048 - StackAlign), StackSize needs to
2321 // satisfy the following conditions to avoid using more instructions
2322 // to adjust the sp after adjusting the amount, such as
2323 // StackSize meets the condition (StackSize <= 2048 + RVCompressLen),
2324 // case1: Amount is 2048 - StackAlign: use addi + addi to adjust sp.
2325 // case2: Amount is RVCompressLen: use addi + addi to adjust sp.
2326 auto CanCompress = [&](uint64_t CompressLen) -> bool {
2327 if (StackSize <= 2047 + CompressLen ||
2328 (StackSize > 2048 * 2 - StackAlign &&
2329 StackSize <= 2047 * 2 + CompressLen) ||
2330 StackSize > 2048 * 3 - StackAlign)
2331 return true;
2332
2333 return false;
2334 };
2335 // In the epilogue, addi sp, sp, 496 is used to recover the sp and it
2336 // can be compressed(C.ADDI16SP, offset can be [-512, 496]), but
2337 // addi sp, sp, 512 can not be compressed. So try to use 496 first.
2338 const uint64_t ADDI16SPCompressLen = 496;
2339 if (STI.is64Bit() && CanCompress(ADDI16SPCompressLen))
2340 return ADDI16SPCompressLen;
2341 if (CanCompress(RVCompressLen))
2342 return RVCompressLen;
2343 }
2344 return 2048 - StackAlign;
2345 }
2346 return 0;
2347}
2348
2351 std::vector<CalleeSavedInfo> &CSI) const {
2352 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
2353 MachineFrameInfo &MFI = MF.getFrameInfo();
2354 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
2355
2356 // Preemptible Interrupts have two additional Callee-save Frame Indexes,
2357 // not tracked by `CSI`.
2358 if (RVFI->isSiFivePreemptibleInterrupt(MF)) {
2359 for (int I = 0; I < 2; ++I) {
2360 int FI = RVFI->getInterruptCSRFrameIndex(I);
2361 MFI.setIsCalleeSavedObjectIndex(FI, true);
2362 }
2363 }
2364
2365 // Early exit if no callee saved registers are modified!
2366 if (CSI.empty())
2367 return true;
2368
2369 if (RVFI->useQCIInterrupt(MF)) {
2370 RVFI->setQCIInterruptStackSize(QCIInterruptPushAmount);
2371 }
2372
2373 if (RVFI->isPushable(MF)) {
2374 // Determine how many GPRs we need to push and save it to RVFI.
2375 unsigned PushedRegNum = getNumPushPopRegs(CSI);
2376
2377 // `QC.C.MIENTER(.NEST)` will save `ra` and `s0`, so we should only push if
2378 // we want to push more than 2 registers. Otherwise, we should push if we
2379 // want to push more than 0 registers.
2380 unsigned OnlyPushIfMoreThan = RVFI->useQCIInterrupt(MF) ? 2 : 0;
2381 if (PushedRegNum > OnlyPushIfMoreThan) {
2382 RVFI->setRVPushRegs(PushedRegNum);
2383 RVFI->setRVPushStackSize(alignTo((STI.getXLen() / 8) * PushedRegNum, 16));
2384 }
2385 }
2386
2387 for (auto &CS : CSI) {
2388 MCRegister Reg = CS.getReg();
2389 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
2390 unsigned Size = RegInfo->getSpillSize(*RC);
2391
2392 if (RVFI->useQCIInterrupt(MF)) {
2393 const auto *FFI = llvm::find_if(FixedCSRFIQCIInterruptMap, [&](auto P) {
2394 return P.first == CS.getReg();
2395 });
2396 if (FFI != std::end(FixedCSRFIQCIInterruptMap)) {
2397 int64_t Offset = FFI->second * (int64_t)Size;
2398
2399 int FrameIdx = MFI.CreateFixedSpillStackObject(Size, Offset);
2400 assert(FrameIdx < 0);
2401 CS.setFrameIdx(FrameIdx);
2402 continue;
2403 }
2404 }
2405
2406 if (RVFI->useSaveRestoreLibCalls(MF) || RVFI->isPushable(MF)) {
2407 const auto *FII = llvm::find_if(
2408 FixedCSRFIMap, [&](MCPhysReg P) { return P == CS.getReg(); });
2409 unsigned RegNum = std::distance(std::begin(FixedCSRFIMap), FII);
2410
2411 if (FII != std::end(FixedCSRFIMap)) {
2412 int64_t Offset;
2413 if (RVFI->getPushPopKind(MF) ==
2415 Offset = -int64_t(RVFI->getRVPushRegs() - RegNum) * Size;
2416 else
2417 Offset = -int64_t(RegNum + 1) * Size;
2418
2419 if (RVFI->useQCIInterrupt(MF))
2421
2422 int FrameIdx = MFI.CreateFixedSpillStackObject(Size, Offset);
2423 assert(FrameIdx < 0);
2424 CS.setFrameIdx(FrameIdx);
2425 continue;
2426 }
2427 }
2428
2429 // For GPRPair registers, use 8-byte slots with required alignment by zilsd.
2430 if (!STI.is64Bit() && STI.hasStdExtZilsd() &&
2431 RISCV::GPRPairRegClass.contains(Reg)) {
2432 Align PairAlign = STI.getZilsdAlign();
2433 int FrameIdx = MFI.CreateStackObject(8, PairAlign, true);
2434 MFI.setIsCalleeSavedObjectIndex(FrameIdx, true);
2435 CS.setFrameIdx(FrameIdx);
2436 continue;
2437 }
2438
2439 // Not a fixed slot.
2440 Align Alignment = RegInfo->getSpillAlign(*RC);
2441 // We may not be able to satisfy the desired alignment specification of
2442 // the TargetRegisterClass if the stack alignment is smaller. Use the
2443 // min.
2444 Alignment = std::min(Alignment, getStackAlign());
2445 int FrameIdx = MFI.CreateStackObject(Size, Alignment, true);
2446 MFI.setIsCalleeSavedObjectIndex(FrameIdx, true);
2447 CS.setFrameIdx(FrameIdx);
2449 MFI.setStackID(FrameIdx, TargetStackID::ScalableVector);
2450 }
2451
2452 if (RVFI->useQCIInterrupt(MF)) {
2453 // Allocate a fixed object that covers the entire QCI stack allocation,
2454 // because there are gaps which are reserved for future use.
2455 MFI.CreateFixedSpillStackObject(
2456 QCIInterruptPushAmount, -static_cast<int64_t>(QCIInterruptPushAmount));
2457 }
2458
2459 if (RVFI->isPushable(MF)) {
2460 int64_t QCIOffset = RVFI->useQCIInterrupt(MF) ? QCIInterruptPushAmount : 0;
2461 // Allocate a fixed object that covers the full push.
2462 if (int64_t PushSize = RVFI->getRVPushStackSize())
2463 MFI.CreateFixedSpillStackObject(PushSize, -PushSize - QCIOffset);
2464 } else if (int LibCallRegs = getLibCallID(MF, CSI) + 1) {
2465 int64_t LibCallFrameSize =
2466 alignTo((STI.getXLen() / 8) * LibCallRegs, getStackAlign());
2467 MFI.CreateFixedSpillStackObject(LibCallFrameSize, -LibCallFrameSize);
2468 }
2469
2470 return true;
2471}
2472
2476 if (CSI.empty())
2477 return true;
2478
2479 MachineFunction *MF = MBB.getParent();
2480 const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
2481 DebugLoc DL;
2482 if (MI != MBB.end() && !MI->isDebugInstr())
2483 DL = MI->getDebugLoc();
2484
2486 if (RVFI->useQCIInterrupt(*MF)) {
2487 // Emit QC.C.MIENTER(.NEST)
2488 BuildMI(
2489 MBB, MI, DL,
2490 TII.get(RVFI->getInterruptStackKind(*MF) ==
2492 ? RISCV::QC_C_MIENTER_NEST
2493 : RISCV::QC_C_MIENTER))
2495
2496 for (auto [Reg, _Offset] : FixedCSRFIQCIInterruptMap)
2497 MBB.addLiveIn(Reg);
2498 }
2499
2500 if (RVFI->isPushable(*MF)) {
2501 // Emit CM.PUSH with base StackAdj & evaluate Push stack
2502 unsigned PushedRegNum = RVFI->getRVPushRegs();
2503 if (PushedRegNum > 0) {
2504 // Use encoded number to represent registers to spill.
2505 unsigned Opcode = getPushOpcode(
2506 RVFI->getPushPopKind(*MF), hasFP(*MF) && !RVFI->useQCIInterrupt(*MF));
2507 unsigned RegEnc = RISCVZC::encodeRegListNumRegs(PushedRegNum);
2508 MachineInstrBuilder PushBuilder =
2509 BuildMI(MBB, MI, DL, TII.get(Opcode))
2511 PushBuilder.addImm(RegEnc);
2512 PushBuilder.addImm(0);
2513
2514 for (unsigned i = 0; i < PushedRegNum; i++)
2515 PushBuilder.addUse(FixedCSRFIMap[i], RegState::Implicit);
2516 }
2517 } else if (const char *SpillLibCall = getSpillLibCallName(*MF, CSI)) {
2518 // Add spill libcall via non-callee-saved register t0.
2519 MachineInstrBuilder NewMI =
2520 BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoCALLReg), RISCV::X5)
2521 .addExternalSymbol(SpillLibCall, RISCVII::MO_CALL)
2523 .addUse(RISCV::X2, RegState::Implicit)
2524 .addDef(RISCV::X2, RegState::ImplicitDefine);
2525
2526 // Add registers spilled as implicit used.
2527 for (auto &CS : CSI)
2528 NewMI.addUse(CS.getReg(), RegState::Implicit);
2529 }
2530
2531 // Manually spill values not spilled by libcall & Push/Pop.
2532 const auto &UnmanagedCSI =
2533 getUnmanagedInterruptCSI(*MF, CSI, STI.preferAscendingLoadStore());
2534 const auto &RVVCSI = getRVVCalleeSavedInfo(*MF, CSI);
2535
2536 auto storeRegsToStackSlots = [&](ArrayRef<CalleeSavedInfo> CSInfo) {
2537 for (auto &CS : CSInfo) {
2538 // Insert the spill to the stack frame.
2539 MCRegister Reg = CS.getReg();
2540 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
2541 TII.storeRegToStackSlot(MBB, MI, Reg, !MBB.isLiveIn(Reg),
2542 CS.getFrameIdx(), RC, Register(),
2544 }
2545 };
2546 storeRegsToStackSlots(UnmanagedCSI);
2547 storeRegsToStackSlots(RVVCSI);
2548
2549 return true;
2550}
2551
2552static unsigned getCalleeSavedRVVNumRegs(const Register &BaseReg) {
2553 return RISCV::VRRegClass.contains(BaseReg) ? 1
2554 : RISCV::VRM2RegClass.contains(BaseReg) ? 2
2555 : RISCV::VRM4RegClass.contains(BaseReg) ? 4
2556 : 8;
2557}
2558
2559void RISCVFrameLowering::emitCalleeSavedRVVPrologCFI(
2562 const MachineFrameInfo &MFI = MF->getFrameInfo();
2563 RISCVMachineFunctionInfo *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
2564 const RISCVRegisterInfo &TRI = *STI.getRegisterInfo();
2565
2566 const auto &RVVCSI = getRVVCalleeSavedInfo(*MF, MFI.getCalleeSavedInfo());
2567 if (RVVCSI.empty())
2568 return;
2569
2570 uint64_t FixedSize = getStackSizeWithRVVPadding(*MF);
2571 if (!HasFP) {
2572 uint64_t ScalarLocalVarSize =
2573 MFI.getStackSize() - RVFI->getCalleeSavedStackSize() -
2574 RVFI->getVarArgsSaveSize() + RVFI->getRVVPadding();
2575 FixedSize -= ScalarLocalVarSize;
2576 }
2577
2578 CFIInstBuilder CFIBuilder(MBB, MI, MachineInstr::FrameSetup);
2579 for (auto &CS : RVVCSI) {
2580 // Insert the spill to the stack frame.
2581 int FI = CS.getFrameIdx();
2582 MCRegister BaseReg = getRVVBaseRegister(TRI, CS.getReg());
2583 unsigned NumRegs = getCalleeSavedRVVNumRegs(CS.getReg());
2584 for (unsigned i = 0; i < NumRegs; ++i) {
2585 CFIBuilder.insertCFIInst(createDefCFAOffset(
2586 TRI, BaseReg + i,
2587 StackOffset::get(-FixedSize, MFI.getObjectOffset(FI) / 8 + i)));
2588 }
2589 }
2590}
2591
2592void RISCVFrameLowering::emitCalleeSavedRVVEpilogCFI(
2595 const MachineFrameInfo &MFI = MF->getFrameInfo();
2596 const RISCVRegisterInfo &TRI = *STI.getRegisterInfo();
2597
2598 CFIInstBuilder CFIHelper(MBB, MI, MachineInstr::FrameDestroy);
2599 const auto &RVVCSI = getRVVCalleeSavedInfo(*MF, MFI.getCalleeSavedInfo());
2600 for (auto &CS : RVVCSI) {
2601 MCRegister BaseReg = getRVVBaseRegister(TRI, CS.getReg());
2602 unsigned NumRegs = getCalleeSavedRVVNumRegs(CS.getReg());
2603 for (unsigned i = 0; i < NumRegs; ++i)
2604 CFIHelper.buildRestore(BaseReg + i);
2605 }
2606}
2607
2611 if (CSI.empty())
2612 return true;
2613
2614 MachineFunction *MF = MBB.getParent();
2615 const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
2616 DebugLoc DL;
2617 if (MI != MBB.end() && !MI->isDebugInstr())
2618 DL = MI->getDebugLoc();
2619
2620 // Manually restore values not restored by libcall & Push/Pop.
2621 // Reverse the restore order in epilog. In addition, the return
2622 // address will be restored first in the epilogue. It increases
2623 // the opportunity to avoid the load-to-use data hazard between
2624 // loading RA and return by RA. loadRegFromStackSlot can insert
2625 // multiple instructions.
2626 const auto &UnmanagedCSI =
2627 getUnmanagedInterruptCSI(*MF, CSI, STI.preferAscendingLoadStore());
2628 const auto &RVVCSI = getRVVCalleeSavedInfo(*MF, CSI);
2629
2630 auto loadRegFromStackSlot = [&](ArrayRef<CalleeSavedInfo> CSInfo) {
2631 for (auto &CS : CSInfo) {
2632 MCRegister Reg = CS.getReg();
2633 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
2634 TII.loadRegFromStackSlot(MBB, MI, Reg, CS.getFrameIdx(), RC, Register(),
2635 RISCV::NoSubRegister,
2637 assert(MI != MBB.begin() &&
2638 "loadRegFromStackSlot didn't insert any code!");
2639 }
2640 };
2641 loadRegFromStackSlot(RVVCSI);
2642 loadRegFromStackSlot(UnmanagedCSI);
2643
2645 if (RVFI->useQCIInterrupt(*MF)) {
2646 // Don't emit anything here because restoration is handled by
2647 // QC.C.MILEAVERET which we already inserted to return.
2648 assert(MI->getOpcode() == RISCV::QC_C_MILEAVERET &&
2649 "Unexpected QCI Interrupt Return Instruction");
2650 }
2651
2652 if (RVFI->isPushable(*MF)) {
2653 unsigned PushedRegNum = RVFI->getRVPushRegs();
2654 if (PushedRegNum > 0) {
2655 unsigned Opcode = getPopOpcode(RVFI->getPushPopKind(*MF));
2656 unsigned RegEnc = RISCVZC::encodeRegListNumRegs(PushedRegNum);
2657 MachineInstrBuilder PopBuilder =
2658 BuildMI(MBB, MI, DL, TII.get(Opcode))
2660 // Use encoded number to represent registers to restore.
2661 PopBuilder.addImm(RegEnc);
2662 PopBuilder.addImm(0);
2663
2664 for (unsigned i = 0; i < RVFI->getRVPushRegs(); i++)
2666 }
2667 } else if (const char *RestoreLibCall = getRestoreLibCallName(*MF, CSI)) {
2668 // Add restore libcall via tail call.
2669 MachineInstrBuilder NewMI =
2670 BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoTAIL))
2671 .addExternalSymbol(RestoreLibCall, RISCVII::MO_CALL)
2673 .addDef(RISCV::X2, RegState::ImplicitDefine);
2674
2675 // Add registers restored as implicit defined.
2676 for (auto &CS : CSI)
2677 NewMI.addDef(CS.getReg(), RegState::ImplicitDefine);
2678
2679 // Remove trailing returns, since the terminator is now a tail call to the
2680 // restore function.
2681 if (MI != MBB.end() && MI->getOpcode() == RISCV::PseudoRET) {
2682 NewMI.getInstr()->copyImplicitOps(*MF, *MI);
2683 MI->eraseFromParent();
2684 }
2685 }
2686 return true;
2687}
2688
2690 // Keep the conventional code flow when not optimizing.
2691 if (MF.getFunction().hasOptNone())
2692 return false;
2693
2694 // QCI and SiFive CLIC interrupt entry sequences must precede all handler
2695 // code.
2696 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
2697 if (RVFI->useQCIInterrupt(MF) || RVFI->useSiFiveInterrupt(MF))
2698 return false;
2699
2700 return true;
2701}
2702
2704 MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
2705 const MachineFunction *MF = MBB.getParent();
2706 const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
2707
2708 // Make sure VTYPE and VL are not live-in since we will use vsetvli in the
2709 // prologue to get the VLEN, and that will clobber these registers.
2710 //
2711 // We may do also check the stack contains objects with scalable vector type,
2712 // but this will require iterating over all the stack objects, but this may
2713 // not worth since the situation is rare, we could do further check in future
2714 // if we find it is necessary.
2715 if (STI.preferVsetvliOverReadVLENB() &&
2716 (MBB.isLiveIn(RISCV::VTYPE) || MBB.isLiveIn(RISCV::VL)))
2717 return false;
2718
2719 if (!RVFI->useSaveRestoreLibCalls(*MF))
2720 return true;
2721
2722 // Inserting a call to a __riscv_save libcall requires the use of the register
2723 // t0 (X5) to hold the return address. Therefore if this register is already
2724 // used we can't insert the call.
2725
2726 RegScavenger RS;
2727 RS.enterBasicBlock(*TmpMBB);
2728 return !RS.isRegUsed(RISCV::X5);
2729}
2730
2732 const MachineFunction *MF = MBB.getParent();
2733 MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
2734 const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
2735
2736 if (!RVFI->useSaveRestoreLibCalls(*MF))
2737 return true;
2738
2739 // Using the __riscv_restore libcalls to restore CSRs requires a tail call.
2740 // This means if we still need to continue executing code within this function
2741 // the restore cannot take place in this basic block.
2742
2743 if (MBB.succ_size() > 1)
2744 return false;
2745
2746 MachineBasicBlock *SuccMBB =
2747 MBB.succ_empty() ? TmpMBB->getFallThrough() : *MBB.succ_begin();
2748
2749 // Doing a tail call should be safe if there are no successors, because either
2750 // we have a returning block or the end of the block is unreachable, so the
2751 // restore will be eliminated regardless.
2752 if (!SuccMBB)
2753 return true;
2754
2755 // The successor can only contain a return and debug instructions, since we
2756 // would effectively replace it with our own tail return at the end of this
2757 // block. The debug instructions would not execute on the tail-return path.
2758 return SuccMBB->isReturnBlock() &&
2759 llvm::count_if(SuccMBB->instrs(), [](const MachineInstr &MI) {
2760 return !MI.isDebugInstr();
2761 }) == 1;
2762}
2763
2765 switch (ID) {
2768 return true;
2774 return false;
2775 }
2776 llvm_unreachable("Invalid TargetStackID::Value");
2777}
2778
2782
2783// Synthesize the probe loop.
2785 Register TargetReg, Register ScratchReg,
2786 bool IsRVV) {
2787 assert(TargetReg != RISCV::X2 && "New top of stack cannot already be in SP");
2788 assert(ScratchReg != RISCV::X2 && "Scratch register cannot be SP");
2789 assert(TargetReg != ScratchReg && "Target and scratch must be different");
2790
2791 MachineBasicBlock &MBB = *MBBI->getParent();
2792 MachineFunction &MF = *MBB.getParent();
2793
2794 auto &Subtarget = MF.getSubtarget<RISCVSubtarget>();
2795 const RISCVInstrInfo *TII = Subtarget.getInstrInfo();
2796 bool IsRV64 = Subtarget.is64Bit();
2797 Align StackAlign = Subtarget.getFrameLowering()->getStackAlign();
2798 const RISCVTargetLowering *TLI = Subtarget.getTargetLowering();
2799 uint64_t ProbeSize = TLI->getStackProbeSize(MF, StackAlign);
2800
2801 MachineFunction::iterator MBBInsertPoint = std::next(MBB.getIterator());
2802 MachineBasicBlock *LoopTestMBB =
2803 MF.CreateMachineBasicBlock(MBB.getBasicBlock());
2804 MF.insert(MBBInsertPoint, LoopTestMBB);
2805 MachineBasicBlock *ExitMBB = MF.CreateMachineBasicBlock(MBB.getBasicBlock());
2806 MF.insert(MBBInsertPoint, ExitMBB);
2808
2809 // ScratchReg = ProbeSize
2810 TII->movImm(MBB, MBBI, DL, ScratchReg, ProbeSize, Flags);
2811
2812 // LoopTest:
2813 // SUB SP, SP, ProbeSize
2814 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(RISCV::SUB), SPReg)
2815 .addReg(SPReg)
2816 .addReg(ScratchReg)
2817 .setMIFlags(Flags);
2818
2819 // s[d|w] zero, 0(sp)
2820 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL,
2821 TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
2822 .addReg(RISCV::X0)
2823 .addReg(SPReg)
2824 .addImm(0)
2825 .setMIFlags(Flags);
2826
2827 if (IsRVV) {
2828 // SUB TargetReg, TargetReg, ProbeSize
2829 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(RISCV::SUB),
2830 TargetReg)
2831 .addReg(TargetReg)
2832 .addReg(ScratchReg)
2833 .setMIFlags(Flags);
2834
2835 // BGE TargetReg, ProbeSize, LoopTest
2836 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(RISCV::BGE))
2837 .addReg(TargetReg)
2838 .addReg(ScratchReg)
2839 .addMBB(LoopTestMBB)
2840 .setMIFlags(Flags);
2841
2842 } else {
2843 // BNE SP, TargetReg, LoopTest
2844 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(RISCV::BNE))
2845 .addReg(SPReg)
2846 .addReg(TargetReg)
2847 .addMBB(LoopTestMBB)
2848 .setMIFlags(Flags);
2849 }
2850
2851 ExitMBB->splice(ExitMBB->end(), &MBB, std::next(MBBI), MBB.end());
2853
2854 LoopTestMBB->addSuccessor(ExitMBB);
2855 LoopTestMBB->addSuccessor(LoopTestMBB);
2856 MBB.addSuccessor(LoopTestMBB);
2857 // Update liveins.
2858 fullyRecomputeLiveIns({ExitMBB, LoopTestMBB});
2859}
2860
2861void RISCVFrameLowering::inlineStackProbe(MachineFunction &MF,
2862 MachineBasicBlock &MBB) const {
2863 // Get the instructions that need to be replaced. We emit at most two of
2864 // these. Remember them in order to avoid complications coming from the need
2865 // to traverse the block while potentially creating more blocks.
2866 SmallVector<MachineInstr *, 4> ToReplace;
2867 for (MachineInstr &MI : MBB) {
2868 unsigned Opc = MI.getOpcode();
2869 if (Opc == RISCV::PROBED_STACKALLOC ||
2870 Opc == RISCV::PROBED_STACKALLOC_RVV) {
2871 ToReplace.push_back(&MI);
2872 }
2873 }
2874
2875 for (MachineInstr *MI : ToReplace) {
2876 if (MI->getOpcode() == RISCV::PROBED_STACKALLOC ||
2877 MI->getOpcode() == RISCV::PROBED_STACKALLOC_RVV) {
2880 Register TargetReg = MI->getOperand(0).getReg();
2881
2882 Register ScratchReg =
2883 findScratchNonCalleeSaveRegister(&MBB, RISCV::X7, TargetReg);
2884
2885 assert(ScratchReg.isValid() &&
2886 "No available scratch register for stack probe loop");
2887
2888 emitStackProbeInline(MBBI, DL, TargetReg, ScratchReg,
2889 (MI->getOpcode() == RISCV::PROBED_STACKALLOC_RVV));
2891 }
2892 }
2893}
2894
2896 return 0;
2897}
2898
2901 return RISCV::X2;
2902}
2903
2904// On 64-bit systems the fixed stack can hold INT64_MAX bytes, since
2905// stack-offset calculation is done in 2s-complement.
2906// NOTE: In theory a register can hold any 64-bit number, so this constraint
2907// might be relaxed to UINT64_MAX in the future, if anyone actually needs
2908// that.
2910 return STI.is64Bit() ? INT64_MAX : UINT32_MAX;
2911}
static void getLiveRegsForEntryMBB(LivePhysRegs &LiveRegs, const MachineBasicBlock &MBB)
static MCCFIInstruction createDefCFAExpression(const TargetRegisterInfo &TRI, unsigned Reg, const StackOffset &Offset)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
This file contains constants used for implementing Dwarf debug support.
const HexagonInstrInfo * TII
static void emitSCSPrologue(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL)
static void emitSCSEpilogue(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL)
IRTranslator LLVM IR MI
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
static uint64_t estimateFunctionSizeInBytes(const LoongArchInstrInfo *TII, const MachineFunction &MF)
static void emitStackProbeInline(MachineBasicBlock::iterator MBBI, DebugLoc DL, Register TargetReg)
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define P(N)
static constexpr uint64_t QCIInterruptPushAmount
static void emitSiFiveCLICStackSwap(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, MachineInstr::MIFlag FrameFlag)
static unsigned getPushOpcode(RISCVMachineFunctionInfo::PushPopKind Kind, bool UpdateFP)
static void emitSiFiveCLICPreemptibleSaves(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL)
static MCRegister getRVVBaseRegister(const RISCVRegisterInfo &TRI, const Register &Reg)
static void createSiFivePreemptibleInterruptFrameEntries(MachineFunction &MF, RISCVMachineFunctionInfo &RVFI)
static constexpr MCPhysReg FPReg
static const char * getRestoreLibCallName(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI)
static bool needsDwarfCFI(const MachineFunction &MF)
Returns true if DWARF CFI instructions ("frame moves") should be emitted.
static constexpr MCPhysReg SPReg
static const char * getSpillLibCallName(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI)
static bool hasRVVFrameObject(const MachineFunction &MF)
static SmallVector< CalleeSavedInfo, 8 > getUnmanagedInterruptCSI(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI, bool ReverseOrder=false)
static void appendScalableVectorExpression(const TargetRegisterInfo &TRI, SmallVectorImpl< char > &Expr, StackOffset Offset, llvm::raw_string_ostream &Comment)
static SmallVector< CalleeSavedInfo, 8 > getQCISavedInfo(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI)
static SmallVector< CalleeSavedInfo, 8 > getRVVCalleeSavedInfo(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI)
static SmallVector< CalleeSavedInfo, 8 > getUnmanagedCSI(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI, bool ReverseOrder=false)
static void emitSiFiveCLICPreemptibleRestores(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, CFIInstBuilder &CFIBuilder, const DebugLoc &DL)
static bool isPop(unsigned Opcode)
static unsigned getCalleeSavedRVVNumRegs(const Register &BaseReg)
static MCCFIInstruction createDefCFAOffset(const TargetRegisterInfo &TRI, Register Reg, StackOffset Offset)
static Align getABIStackAlignment(RISCVABI::ABI ABI)
static unsigned getPopOpcode(RISCVMachineFunctionInfo::PushPopKind Kind)
static SmallVector< CalleeSavedInfo, 8 > getPushOrLibCallsSavedInfo(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI)
static int getLibCallID(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI)
static const std::pair< MCPhysReg, int8_t > FixedCSRFIQCIInterruptMap[]
static bool isPush(unsigned Opcode)
static constexpr MCPhysReg RAReg
static MCRegister getLargestFPRegisterOrZero(const RISCVSubtarget &STI, const TargetRegisterInfo &TRI, MCRegister Reg)
static const MCPhysReg FixedCSRFIMap[]
static int getSiFiveCLICScratchFrameIndex(const MachineFunction &MF)
static unsigned getNumPushPopRegs(const std::vector< CalleeSavedInfo > &CSI)
static MCRegister getPhysicalGPR(const TargetRegisterInfo &TRI, MCRegister Reg)
static unsigned getScavSlotsNumForRVV(MachineFunction &MF)
This file declares the machine register scavenger class.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:484
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
BitVector & reset()
Reset all bits in the bitvector.
Definition BitVector.h:409
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
iterator_range< const_set_bits_iterator > set_bits() const
Definition BitVector.h:159
Helper class for creating CFI instructions and inserting them into MIR.
void buildEscape(StringRef Bytes, StringRef Comment="") const
void buildDefCFAOffset(int64_t Offset, MCSymbol *Label=nullptr) const
void buildRestore(MCRegister Reg) const
void buildDefCFARegister(MCRegister Reg) const
void buildOffset(MCRegister Reg, int64_t Offset) const
void insertCFIInst(const MCCFIInstruction &CFIInst) const
void buildDefCFA(MCRegister Reg, int64_t Offset) const
void setInsertPoint(MachineBasicBlock::iterator IP)
The CalleeSavedInfo class tracks the information need to locate where a callee saved register is in t...
MCRegister getReg() const
A debug info location.
Definition DebugLoc.h:126
Diagnostic information for unsupported feature in backend.
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:765
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
bool hasOptNone() const
Do not optimize this function (-O0).
Definition Function.h:686
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:356
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:730
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
A set of physical registers with utility functions to track liveness when walking backward/forward th...
static MCCFIInstruction createEscape(MCSymbol *L, StringRef Vals, SMLoc Loc={}, StringRef Comment="")
.cfi_escape Allows the user to add arbitrary bytes to the unwind info.
Definition MCDwarf.h:756
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
constexpr unsigned id() const
Definition MCRegister.h:82
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
LLVM_ABI MachineBasicBlock * getFallThrough(bool JumpToFallThrough=true)
Return the fallthrough block if the block can implicitly transfer control to the block after it by fa...
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
bool isReturnBlock() const
Convenience function that returns true if the block ends in a return instruction.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing function and deletes it.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
bool adjustsStack() const
Return true if this function adjusts the stack – e.g., when calling another function.
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
LLVM_ABI void ensureMaxAlignment(Align Alignment)
Make sure the function's frame is at least Align bytes aligned.
bool isFrameAddressTaken() const
This method may be called any time after instruction selection is complete to determine if there is a...
Align getMaxAlign() const
Return alignment of this function's frame.
void setObjectOffset(int ObjectIdx, int64_t SPOffset)
Set the stack frame offset of the specified object.
uint64_t getMaxCallFrameSize() const
Return the maximum size of a call frame that must be allocated for an outgoing function call.
int64_t getOffsetAdjustment() const
Return the correction for frame offsets.
LLVM_ABI uint64_t estimateStackSize(const MachineFunction &MF) const
Estimate and return the size of the stack frame.
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
bool isMaxCallFrameSizeComputed() const
LLVM_ABI int CreateSpillStackObject(uint64_t Size, Align Alignment, TargetStackID::Value StackID=TargetStackID::Default)
Create a new statically sized stack object that represents a spill slot, returning a nonnegative iden...
const std::vector< CalleeSavedInfo > & getCalleeSavedInfo() const
Returns a reference to call saved info vector for the current function.
int getObjectIndexEnd() const
Return one past the maximum frame object index.
uint8_t getStackID(int ObjectIdx) const
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
void setStackSize(uint64_t Size)
Set the size of the stack.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
bool isDeadObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a dead object.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
bool needsFrameMoves() const
True if this function needs frame moves for debug or exceptions.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
bool disableFramePointerElim() const
Returns true if frame pointer elimination should be disabled for this function.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const MachineInstrBuilder & addExternalSymbol(const char *FnName, unsigned TargetFlags=0) const
const MachineInstrBuilder & addUse(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
Representation of each machine instruction.
LLVM_ABI void copyImplicitOps(MachineFunction &MF, const MachineInstr &MI)
Copy implicit register operands from specified instruction to this instruction.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const BitVector & getUsedPhysRegsMask() const
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
bool def_empty(Register RegNo) const
def_empty - Return true if there are no instructions defining the specified register (it may be live-...
LLVM_ABI const MCPhysReg * getCalleeSavedRegs() const
Returns list of callee saved registers.
LLVM_ABI void setCalleeSavedRegs(ArrayRef< MCPhysReg > CSRs)
Sets the updated Callee Saved Registers list.
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
bool assignCalleeSavedSpillSlots(MachineFunction &MF, const TargetRegisterInfo *TRI, std::vector< CalleeSavedInfo > &CSI) const override
assignCalleeSavedSpillSlots - Allows target to override spill slot assignment logic.
void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const override
emitProlog/emitEpilog - These methods insert prolog and epilog code into the function.
uint64_t getFirstSPAdjustAmount(const MachineFunction &MF) const
bool enableShrinkWrapping(const MachineFunction &MF) const override
Returns true if the target will correctly handle shrink wrapping.
uint64_t getStackThreshold() const override
getStackThreshold - Return the maximum stack size
bool spillCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, ArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const override
spillCalleeSavedRegisters - Issues instruction(s) to spill all callee saved registers and returns tru...
bool hasBP(const MachineFunction &MF) const
void allocateStack(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, MachineFunction &MF, uint64_t Offset, uint64_t RealStackSize, bool EmitCFI, bool NeedProbe, uint64_t ProbeSize, bool DynAllocation, MachineInstr::MIFlag Flag) const
bool canUseAsEpilogue(const MachineBasicBlock &MBB) const override
Check whether or not the given MBB can be used as a epilogue for the target.
bool hasFPImpl(const MachineFunction &MF) const override
Register findScratchNonCalleeSaveRegister(MachineBasicBlock *MBB, Register PreferredReg, Register DontUseReg=Register()) const
bool restoreCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, MutableArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const override
restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee saved registers and returns...
bool hasReservedCallFrame(const MachineFunction &MF) const override
hasReservedCallFrame - Under normal circumstances, when a frame pointer is not required,...
Register getInitialCFARegister(const MachineFunction &MF) const override
Return initial CFA register value i.e.
const RISCVSubtarget & STI
StackOffset getFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg) const override
getFrameIndexReference - This method should return the base register and offset used to reference a f...
bool isSupportedStackID(TargetStackID::Value ID) const override
void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS) const override
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const override
TargetStackID::Value getStackIDForScalableVectors() const override
Returns the StackID that scalable vectors should be associated with.
int getInitialCFAOffset(const MachineFunction &MF) const override
Return initial CFA offset value i.e.
void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS) const override
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
MachineBasicBlock::iterator eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const override
This method is called during prolog/epilog code insertion to eliminate call frame setup and destroy p...
bool canUseAsPrologue(const MachineBasicBlock &MBB) const override
Check whether or not the given MBB can be used as a prologue for the target.
RISCVFrameLowering(const RISCVSubtarget &STI)
uint64_t getStackSizeWithRVVPadding(const MachineFunction &MF) const
RISCVMachineFunctionInfo - This class is derived from MachineFunctionInfo and contains private RISCV-...
bool isPushable(const MachineFunction &MF) const
InterruptStackKind getInterruptStackKind(const MachineFunction &MF) const
bool useSiFiveInterrupt(const MachineFunction &MF) const
bool isSiFivePreemptibleInterrupt(const MachineFunction &MF) const
PushPopKind getPushPopKind(const MachineFunction &MF) const
bool useSaveRestoreLibCalls(const MachineFunction &MF) const
bool useQCIInterrupt(const MachineFunction &MF) const
TargetRegisterClass const * getLargestFPRegClass() const
bool hasVInstructions() const
const RISCVRegisterInfo * getRegisterInfo() const override
const RISCVInstrInfo * getInstrInfo() const override
bool hasInlineStackProbe(const MachineFunction &MF) const override
True if stack clash protection is enabled for this functions.
unsigned getStackProbeSize(const MachineFunction &MF, Align StackAlign) const
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:112
Represents a location in source code.
Definition SMLoc.h:22
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
bool contains(const T &V) const
Check if the SmallSet contains the given element.
Definition SmallSet.h:229
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:68
StringRef str() const
Explicit conversion to StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StackOffset holds a fixed and a scalable offset in bytes.
Definition TypeSize.h:30
int64_t getFixed() const
Returns the fixed component of the stack.
Definition TypeSize.h:46
int64_t getScalable() const
Returns the scalable component of the stack.
Definition TypeSize.h:49
static StackOffset get(int64_t Fixed, int64_t Scalable)
Definition TypeSize.h:41
static StackOffset getScalable(int64_t Scalable)
Definition TypeSize.h:40
static StackOffset getFixed(int64_t Fixed)
Definition TypeSize.h:39
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool hasFP(const MachineFunction &MF) const
hasFP - Return true if the specified function should have a dedicated frame pointer register.
virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
int getOffsetOfLocalArea() const
getOffsetOfLocalArea - This method returns the offset of the local area from the stack pointer on ent...
TargetFrameLowering(StackDirection D, Align StackAl, int LAO, Align TransAl=Align(1), bool StackReal=true)
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
int alignSPAdjust(int SPAdj) const
alignSPAdjust - This method aligns the stack adjustment to the correct alignment.
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
bool hasStackRealignment(const MachineFunction &MF) const
True if stack realignment is required and still possible.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
self_iterator getIterator()
Definition ilist_node.h:123
A raw_ostream that writes to an std::string.
#define INT64_MAX
Definition DataTypes.h:71
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
MCRegister getBPReg()
MCRegister getSCSPReg()
static VLMUL encodeLMUL(unsigned LMUL, bool Fractional)
LLVM_ABI unsigned encodeVTYPE(VLMUL VLMUL, unsigned SEW, bool TailAgnostic, bool MaskAgnostic, bool AltFmt=false)
static unsigned encodeRegListNumRegs(unsigned NumRegs)
static constexpr unsigned RVVBitsPerBlock
bool isRVVSpill(const MachineInstr &MI)
static constexpr unsigned RVVBytesPerBlock
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
Definition SFrame.h:77
This is an optimization pass for GlobalISel generic memory operations.
IterT next_nodbg(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It, then continue incrementing it while it points to a debug instruction.
@ Offset
Definition DWP.cpp:577
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Kill
The last use of a register.
@ Define
Register definition.
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:541
LLVM_ABI void reportFatalInternalError(Error Err)
Report a fatal error that indicates a bug in LLVM.
Definition Error.cpp:173
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1415
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
uint64_t offsetToAlignment(uint64_t Value, Align Alignment)
Returns the offset to the next integer (mod 2**64) that is greater than or equal to Value and is a mu...
Definition Alignment.h:186
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
void appendLEB128(SmallVectorImpl< U > &Buffer, T Value)
Definition LEB128.h:280
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:197
void fullyRecomputeLiveIns(ArrayRef< MachineBasicBlock * > MBBs)
Convenience function for recomputing live-in's for a set of MBBs until the computation converges.
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
static bool isRVVRegClass(const TargetRegisterClass *RC)
void adjustReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator II, const DebugLoc &DL, Register DestReg, Register SrcReg, StackOffset Offset, MachineInstr::MIFlag Flag, MaybeAlign RequiredAlign) const