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