xref: /freebsd/contrib/llvm-project/llvm/lib/Target/RISCV/RISCVFrameLowering.cpp (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
1 //===-- RISCVFrameLowering.cpp - RISCV 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 RISCV implementation of TargetFrameLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "RISCVFrameLowering.h"
14 #include "RISCVMachineFunctionInfo.h"
15 #include "RISCVSubtarget.h"
16 #include "llvm/CodeGen/MachineFrameInfo.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/MachineInstrBuilder.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/CodeGen/RegisterScavenging.h"
21 #include "llvm/IR/DiagnosticInfo.h"
22 #include "llvm/MC/MCDwarf.h"
23 
24 using namespace llvm;
25 
26 // For now we use x18, a.k.a s2, as pointer to shadow call stack.
27 // User should explicitly set -ffixed-x18 and not use x18 in their asm.
28 static void emitSCSPrologue(MachineFunction &MF, MachineBasicBlock &MBB,
29                             MachineBasicBlock::iterator MI,
30                             const DebugLoc &DL) {
31   if (!MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack))
32     return;
33 
34   const auto &STI = MF.getSubtarget<RISCVSubtarget>();
35   Register RAReg = STI.getRegisterInfo()->getRARegister();
36 
37   // Do not save RA to the SCS if it's not saved to the regular stack,
38   // i.e. RA is not at risk of being overwritten.
39   std::vector<CalleeSavedInfo> &CSI = MF.getFrameInfo().getCalleeSavedInfo();
40   if (std::none_of(CSI.begin(), CSI.end(),
41                    [&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
42     return;
43 
44   Register SCSPReg = RISCVABI::getSCSPReg();
45 
46   auto &Ctx = MF.getFunction().getContext();
47   if (!STI.isRegisterReservedByUser(SCSPReg)) {
48     Ctx.diagnose(DiagnosticInfoUnsupported{
49         MF.getFunction(), "x18 not reserved by user for Shadow Call Stack."});
50     return;
51   }
52 
53   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
54   if (RVFI->useSaveRestoreLibCalls(MF)) {
55     Ctx.diagnose(DiagnosticInfoUnsupported{
56         MF.getFunction(),
57         "Shadow Call Stack cannot be combined with Save/Restore LibCalls."});
58     return;
59   }
60 
61   const RISCVInstrInfo *TII = STI.getInstrInfo();
62   bool IsRV64 = STI.hasFeature(RISCV::Feature64Bit);
63   int64_t SlotSize = STI.getXLen() / 8;
64   // Store return address to shadow call stack
65   // s[w|d]  ra, 0(s2)
66   // addi    s2, s2, [4|8]
67   BuildMI(MBB, MI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
68       .addReg(RAReg)
69       .addReg(SCSPReg)
70       .addImm(0)
71       .setMIFlag(MachineInstr::FrameSetup);
72   BuildMI(MBB, MI, DL, TII->get(RISCV::ADDI))
73       .addReg(SCSPReg, RegState::Define)
74       .addReg(SCSPReg)
75       .addImm(SlotSize)
76       .setMIFlag(MachineInstr::FrameSetup);
77 }
78 
79 static void emitSCSEpilogue(MachineFunction &MF, MachineBasicBlock &MBB,
80                             MachineBasicBlock::iterator MI,
81                             const DebugLoc &DL) {
82   if (!MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack))
83     return;
84 
85   const auto &STI = MF.getSubtarget<RISCVSubtarget>();
86   Register RAReg = STI.getRegisterInfo()->getRARegister();
87 
88   // See emitSCSPrologue() above.
89   std::vector<CalleeSavedInfo> &CSI = MF.getFrameInfo().getCalleeSavedInfo();
90   if (std::none_of(CSI.begin(), CSI.end(),
91                    [&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
92     return;
93 
94   Register SCSPReg = RISCVABI::getSCSPReg();
95 
96   auto &Ctx = MF.getFunction().getContext();
97   if (!STI.isRegisterReservedByUser(SCSPReg)) {
98     Ctx.diagnose(DiagnosticInfoUnsupported{
99         MF.getFunction(), "x18 not reserved by user for Shadow Call Stack."});
100     return;
101   }
102 
103   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
104   if (RVFI->useSaveRestoreLibCalls(MF)) {
105     Ctx.diagnose(DiagnosticInfoUnsupported{
106         MF.getFunction(),
107         "Shadow Call Stack cannot be combined with Save/Restore LibCalls."});
108     return;
109   }
110 
111   const RISCVInstrInfo *TII = STI.getInstrInfo();
112   bool IsRV64 = STI.hasFeature(RISCV::Feature64Bit);
113   int64_t SlotSize = STI.getXLen() / 8;
114   // Load return address from shadow call stack
115   // l[w|d]  ra, -[4|8](s2)
116   // addi    s2, s2, -[4|8]
117   BuildMI(MBB, MI, DL, TII->get(IsRV64 ? RISCV::LD : RISCV::LW))
118       .addReg(RAReg, RegState::Define)
119       .addReg(SCSPReg)
120       .addImm(-SlotSize)
121       .setMIFlag(MachineInstr::FrameDestroy);
122   BuildMI(MBB, MI, DL, TII->get(RISCV::ADDI))
123       .addReg(SCSPReg, RegState::Define)
124       .addReg(SCSPReg)
125       .addImm(-SlotSize)
126       .setMIFlag(MachineInstr::FrameDestroy);
127 }
128 
129 // Get the ID of the libcall used for spilling and restoring callee saved
130 // registers. The ID is representative of the number of registers saved or
131 // restored by the libcall, except it is zero-indexed - ID 0 corresponds to a
132 // single register.
133 static int getLibCallID(const MachineFunction &MF,
134                         const std::vector<CalleeSavedInfo> &CSI) {
135   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
136 
137   if (CSI.empty() || !RVFI->useSaveRestoreLibCalls(MF))
138     return -1;
139 
140   Register MaxReg = RISCV::NoRegister;
141   for (auto &CS : CSI)
142     // RISCVRegisterInfo::hasReservedSpillSlot assigns negative frame indexes to
143     // registers which can be saved by libcall.
144     if (CS.getFrameIdx() < 0)
145       MaxReg = std::max(MaxReg.id(), CS.getReg().id());
146 
147   if (MaxReg == RISCV::NoRegister)
148     return -1;
149 
150   switch (MaxReg) {
151   default:
152     llvm_unreachable("Something has gone wrong!");
153   case /*s11*/ RISCV::X27: return 12;
154   case /*s10*/ RISCV::X26: return 11;
155   case /*s9*/  RISCV::X25: return 10;
156   case /*s8*/  RISCV::X24: return 9;
157   case /*s7*/  RISCV::X23: return 8;
158   case /*s6*/  RISCV::X22: return 7;
159   case /*s5*/  RISCV::X21: return 6;
160   case /*s4*/  RISCV::X20: return 5;
161   case /*s3*/  RISCV::X19: return 4;
162   case /*s2*/  RISCV::X18: return 3;
163   case /*s1*/  RISCV::X9:  return 2;
164   case /*s0*/  RISCV::X8:  return 1;
165   case /*ra*/  RISCV::X1:  return 0;
166   }
167 }
168 
169 // Get the name of the libcall used for spilling callee saved registers.
170 // If this function will not use save/restore libcalls, then return a nullptr.
171 static const char *
172 getSpillLibCallName(const MachineFunction &MF,
173                     const std::vector<CalleeSavedInfo> &CSI) {
174   static const char *const SpillLibCalls[] = {
175     "__riscv_save_0",
176     "__riscv_save_1",
177     "__riscv_save_2",
178     "__riscv_save_3",
179     "__riscv_save_4",
180     "__riscv_save_5",
181     "__riscv_save_6",
182     "__riscv_save_7",
183     "__riscv_save_8",
184     "__riscv_save_9",
185     "__riscv_save_10",
186     "__riscv_save_11",
187     "__riscv_save_12"
188   };
189 
190   int LibCallID = getLibCallID(MF, CSI);
191   if (LibCallID == -1)
192     return nullptr;
193   return SpillLibCalls[LibCallID];
194 }
195 
196 // Get the name of the libcall used for restoring callee saved registers.
197 // If this function will not use save/restore libcalls, then return a nullptr.
198 static const char *
199 getRestoreLibCallName(const MachineFunction &MF,
200                       const std::vector<CalleeSavedInfo> &CSI) {
201   static const char *const RestoreLibCalls[] = {
202     "__riscv_restore_0",
203     "__riscv_restore_1",
204     "__riscv_restore_2",
205     "__riscv_restore_3",
206     "__riscv_restore_4",
207     "__riscv_restore_5",
208     "__riscv_restore_6",
209     "__riscv_restore_7",
210     "__riscv_restore_8",
211     "__riscv_restore_9",
212     "__riscv_restore_10",
213     "__riscv_restore_11",
214     "__riscv_restore_12"
215   };
216 
217   int LibCallID = getLibCallID(MF, CSI);
218   if (LibCallID == -1)
219     return nullptr;
220   return RestoreLibCalls[LibCallID];
221 }
222 
223 // Return true if the specified function should have a dedicated frame
224 // pointer register.  This is true if frame pointer elimination is
225 // disabled, if it needs dynamic stack realignment, if the function has
226 // variable sized allocas, or if the frame address is taken.
227 bool RISCVFrameLowering::hasFP(const MachineFunction &MF) const {
228   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
229 
230   const MachineFrameInfo &MFI = MF.getFrameInfo();
231   return MF.getTarget().Options.DisableFramePointerElim(MF) ||
232          RegInfo->hasStackRealignment(MF) || MFI.hasVarSizedObjects() ||
233          MFI.isFrameAddressTaken();
234 }
235 
236 bool RISCVFrameLowering::hasBP(const MachineFunction &MF) const {
237   const MachineFrameInfo &MFI = MF.getFrameInfo();
238   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
239 
240   return MFI.hasVarSizedObjects() && TRI->hasStackRealignment(MF);
241 }
242 
243 // Determines the size of the frame and maximum call frame size.
244 void RISCVFrameLowering::determineFrameLayout(MachineFunction &MF) const {
245   MachineFrameInfo &MFI = MF.getFrameInfo();
246 
247   // Get the number of bytes to allocate from the FrameInfo.
248   uint64_t FrameSize = MFI.getStackSize();
249 
250   // Get the alignment.
251   Align StackAlign = getStackAlign();
252 
253   // Make sure the frame is aligned.
254   FrameSize = alignTo(FrameSize, StackAlign);
255 
256   // Update frame info.
257   MFI.setStackSize(FrameSize);
258 }
259 
260 void RISCVFrameLowering::adjustReg(MachineBasicBlock &MBB,
261                                    MachineBasicBlock::iterator MBBI,
262                                    const DebugLoc &DL, Register DestReg,
263                                    Register SrcReg, int64_t Val,
264                                    MachineInstr::MIFlag Flag) const {
265   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
266   const RISCVInstrInfo *TII = STI.getInstrInfo();
267 
268   if (DestReg == SrcReg && Val == 0)
269     return;
270 
271   if (isInt<12>(Val)) {
272     BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), DestReg)
273         .addReg(SrcReg)
274         .addImm(Val)
275         .setMIFlag(Flag);
276   } else {
277     unsigned Opc = RISCV::ADD;
278     bool isSub = Val < 0;
279     if (isSub) {
280       Val = -Val;
281       Opc = RISCV::SUB;
282     }
283 
284     Register ScratchReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
285     TII->movImm(MBB, MBBI, DL, ScratchReg, Val, Flag);
286     BuildMI(MBB, MBBI, DL, TII->get(Opc), DestReg)
287         .addReg(SrcReg)
288         .addReg(ScratchReg, RegState::Kill)
289         .setMIFlag(Flag);
290   }
291 }
292 
293 // Returns the register used to hold the frame pointer.
294 static Register getFPReg(const RISCVSubtarget &STI) { return RISCV::X8; }
295 
296 // Returns the register used to hold the stack pointer.
297 static Register getSPReg(const RISCVSubtarget &STI) { return RISCV::X2; }
298 
299 static SmallVector<CalleeSavedInfo, 8>
300 getNonLibcallCSI(const MachineFunction &MF,
301                  const std::vector<CalleeSavedInfo> &CSI) {
302   const MachineFrameInfo &MFI = MF.getFrameInfo();
303   SmallVector<CalleeSavedInfo, 8> NonLibcallCSI;
304 
305   for (auto &CS : CSI) {
306     int FI = CS.getFrameIdx();
307     if (FI >= 0 && MFI.getStackID(FI) == TargetStackID::Default)
308       NonLibcallCSI.push_back(CS);
309   }
310 
311   return NonLibcallCSI;
312 }
313 
314 void RISCVFrameLowering::adjustStackForRVV(MachineFunction &MF,
315                                            MachineBasicBlock &MBB,
316                                            MachineBasicBlock::iterator MBBI,
317                                            const DebugLoc &DL, int64_t Amount,
318                                            MachineInstr::MIFlag Flag) const {
319   assert(Amount != 0 && "Did not need to adjust stack pointer for RVV.");
320 
321   const RISCVInstrInfo *TII = STI.getInstrInfo();
322   Register SPReg = getSPReg(STI);
323   unsigned Opc = RISCV::ADD;
324   if (Amount < 0) {
325     Amount = -Amount;
326     Opc = RISCV::SUB;
327   }
328   // 1. Multiply the number of v-slots to the length of registers
329   Register FactorRegister =
330       TII->getVLENFactoredAmount(MF, MBB, MBBI, DL, Amount, Flag);
331   // 2. SP = SP - RVV stack size
332   BuildMI(MBB, MBBI, DL, TII->get(Opc), SPReg)
333       .addReg(SPReg)
334       .addReg(FactorRegister, RegState::Kill)
335       .setMIFlag(Flag);
336 }
337 
338 void RISCVFrameLowering::emitPrologue(MachineFunction &MF,
339                                       MachineBasicBlock &MBB) const {
340   MachineFrameInfo &MFI = MF.getFrameInfo();
341   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
342   const RISCVRegisterInfo *RI = STI.getRegisterInfo();
343   const RISCVInstrInfo *TII = STI.getInstrInfo();
344   MachineBasicBlock::iterator MBBI = MBB.begin();
345 
346   Register FPReg = getFPReg(STI);
347   Register SPReg = getSPReg(STI);
348   Register BPReg = RISCVABI::getBPReg();
349 
350   // Debug location must be unknown since the first debug location is used
351   // to determine the end of the prologue.
352   DebugLoc DL;
353 
354   // All calls are tail calls in GHC calling conv, and functions have no
355   // prologue/epilogue.
356   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
357     return;
358 
359   // Emit prologue for shadow call stack.
360   emitSCSPrologue(MF, MBB, MBBI, DL);
361 
362   // Since spillCalleeSavedRegisters may have inserted a libcall, skip past
363   // any instructions marked as FrameSetup
364   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
365     ++MBBI;
366 
367   // Determine the correct frame layout
368   determineFrameLayout(MF);
369 
370   // If libcalls are used to spill and restore callee-saved registers, the frame
371   // has two sections; the opaque section managed by the libcalls, and the
372   // section managed by MachineFrameInfo which can also hold callee saved
373   // registers in fixed stack slots, both of which have negative frame indices.
374   // This gets even more complicated when incoming arguments are passed via the
375   // stack, as these too have negative frame indices. An example is detailed
376   // below:
377   //
378   //  | incoming arg | <- FI[-3]
379   //  | libcallspill |
380   //  | calleespill  | <- FI[-2]
381   //  | calleespill  | <- FI[-1]
382   //  | this_frame   | <- FI[0]
383   //
384   // For negative frame indices, the offset from the frame pointer will differ
385   // depending on which of these groups the frame index applies to.
386   // The following calculates the correct offset knowing the number of callee
387   // saved registers spilt by the two methods.
388   if (int LibCallRegs = getLibCallID(MF, MFI.getCalleeSavedInfo()) + 1) {
389     // Calculate the size of the frame managed by the libcall. The libcalls are
390     // implemented such that the stack will always be 16 byte aligned.
391     unsigned LibCallFrameSize = alignTo((STI.getXLen() / 8) * LibCallRegs, 16);
392     RVFI->setLibCallStackSize(LibCallFrameSize);
393   }
394 
395   // FIXME (note copied from Lanai): This appears to be overallocating.  Needs
396   // investigation. Get the number of bytes to allocate from the FrameInfo.
397   uint64_t StackSize = MFI.getStackSize() + RVFI->getRVVPadding();
398   uint64_t RealStackSize = StackSize + RVFI->getLibCallStackSize();
399   uint64_t RVVStackSize = RVFI->getRVVStackSize();
400 
401   // Early exit if there is no need to allocate on the stack
402   if (RealStackSize == 0 && !MFI.adjustsStack() && RVVStackSize == 0)
403     return;
404 
405   // If the stack pointer has been marked as reserved, then produce an error if
406   // the frame requires stack allocation
407   if (STI.isRegisterReservedByUser(SPReg))
408     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
409         MF.getFunction(), "Stack pointer required, but has been reserved."});
410 
411   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
412   // Split the SP adjustment to reduce the offsets of callee saved spill.
413   if (FirstSPAdjustAmount) {
414     StackSize = FirstSPAdjustAmount;
415     RealStackSize = FirstSPAdjustAmount;
416   }
417 
418   // Allocate space on the stack if necessary.
419   adjustReg(MBB, MBBI, DL, SPReg, SPReg, -StackSize, MachineInstr::FrameSetup);
420 
421   // Emit ".cfi_def_cfa_offset RealStackSize"
422   unsigned CFIIndex = MF.addFrameInst(
423       MCCFIInstruction::cfiDefCfaOffset(nullptr, RealStackSize));
424   BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
425       .addCFIIndex(CFIIndex)
426       .setMIFlag(MachineInstr::FrameSetup);
427 
428   const auto &CSI = MFI.getCalleeSavedInfo();
429 
430   // The frame pointer is callee-saved, and code has been generated for us to
431   // save it to the stack. We need to skip over the storing of callee-saved
432   // registers as the frame pointer must be modified after it has been saved
433   // to the stack, not before.
434   // FIXME: assumes exactly one instruction is used to save each callee-saved
435   // register.
436   std::advance(MBBI, getNonLibcallCSI(MF, CSI).size());
437 
438   // Iterate over list of callee-saved registers and emit .cfi_offset
439   // directives.
440   for (const auto &Entry : CSI) {
441     int FrameIdx = Entry.getFrameIdx();
442     int64_t Offset;
443     // Offsets for objects with fixed locations (IE: those saved by libcall) are
444     // simply calculated from the frame index.
445     if (FrameIdx < 0)
446       Offset = FrameIdx * (int64_t) STI.getXLen() / 8;
447     else
448       Offset = MFI.getObjectOffset(Entry.getFrameIdx()) -
449                RVFI->getLibCallStackSize();
450     Register Reg = Entry.getReg();
451     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
452         nullptr, RI->getDwarfRegNum(Reg, true), Offset));
453     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
454         .addCFIIndex(CFIIndex)
455         .setMIFlag(MachineInstr::FrameSetup);
456   }
457 
458   // Generate new FP.
459   if (hasFP(MF)) {
460     if (STI.isRegisterReservedByUser(FPReg))
461       MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
462           MF.getFunction(), "Frame pointer required, but has been reserved."});
463 
464     adjustReg(MBB, MBBI, DL, FPReg, SPReg,
465               RealStackSize - RVFI->getVarArgsSaveSize(),
466               MachineInstr::FrameSetup);
467 
468     // Emit ".cfi_def_cfa $fp, RVFI->getVarArgsSaveSize()"
469     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(
470         nullptr, RI->getDwarfRegNum(FPReg, true), RVFI->getVarArgsSaveSize()));
471     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
472         .addCFIIndex(CFIIndex)
473         .setMIFlag(MachineInstr::FrameSetup);
474   }
475 
476   // Emit the second SP adjustment after saving callee saved registers.
477   if (FirstSPAdjustAmount) {
478     uint64_t SecondSPAdjustAmount = MFI.getStackSize() - FirstSPAdjustAmount;
479     assert(SecondSPAdjustAmount > 0 &&
480            "SecondSPAdjustAmount should be greater than zero");
481     adjustReg(MBB, MBBI, DL, SPReg, SPReg, -SecondSPAdjustAmount,
482               MachineInstr::FrameSetup);
483 
484     // If we are using a frame-pointer, and thus emitted ".cfi_def_cfa fp, 0",
485     // don't emit an sp-based .cfi_def_cfa_offset
486     if (!hasFP(MF)) {
487       // Emit ".cfi_def_cfa_offset StackSize"
488       unsigned CFIIndex = MF.addFrameInst(
489           MCCFIInstruction::cfiDefCfaOffset(nullptr, MFI.getStackSize()));
490       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
491           .addCFIIndex(CFIIndex)
492           .setMIFlag(MachineInstr::FrameSetup);
493     }
494   }
495 
496   if (RVVStackSize)
497     adjustStackForRVV(MF, MBB, MBBI, DL, -RVVStackSize,
498                       MachineInstr::FrameSetup);
499 
500   if (hasFP(MF)) {
501     // Realign Stack
502     const RISCVRegisterInfo *RI = STI.getRegisterInfo();
503     if (RI->hasStackRealignment(MF)) {
504       Align MaxAlignment = MFI.getMaxAlign();
505 
506       const RISCVInstrInfo *TII = STI.getInstrInfo();
507       if (isInt<12>(-(int)MaxAlignment.value())) {
508         BuildMI(MBB, MBBI, DL, TII->get(RISCV::ANDI), SPReg)
509             .addReg(SPReg)
510             .addImm(-(int)MaxAlignment.value())
511             .setMIFlag(MachineInstr::FrameSetup);
512       } else {
513         unsigned ShiftAmount = Log2(MaxAlignment);
514         Register VR =
515             MF.getRegInfo().createVirtualRegister(&RISCV::GPRRegClass);
516         BuildMI(MBB, MBBI, DL, TII->get(RISCV::SRLI), VR)
517             .addReg(SPReg)
518             .addImm(ShiftAmount)
519             .setMIFlag(MachineInstr::FrameSetup);
520         BuildMI(MBB, MBBI, DL, TII->get(RISCV::SLLI), SPReg)
521             .addReg(VR)
522             .addImm(ShiftAmount)
523             .setMIFlag(MachineInstr::FrameSetup);
524       }
525       // FP will be used to restore the frame in the epilogue, so we need
526       // another base register BP to record SP after re-alignment. SP will
527       // track the current stack after allocating variable sized objects.
528       if (hasBP(MF)) {
529         // move BP, SP
530         BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), BPReg)
531             .addReg(SPReg)
532             .addImm(0)
533             .setMIFlag(MachineInstr::FrameSetup);
534       }
535     }
536   }
537 }
538 
539 void RISCVFrameLowering::emitEpilogue(MachineFunction &MF,
540                                       MachineBasicBlock &MBB) const {
541   const RISCVRegisterInfo *RI = STI.getRegisterInfo();
542   MachineFrameInfo &MFI = MF.getFrameInfo();
543   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
544   Register FPReg = getFPReg(STI);
545   Register SPReg = getSPReg(STI);
546 
547   // All calls are tail calls in GHC calling conv, and functions have no
548   // prologue/epilogue.
549   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
550     return;
551 
552   // Get the insert location for the epilogue. If there were no terminators in
553   // the block, get the last instruction.
554   MachineBasicBlock::iterator MBBI = MBB.end();
555   DebugLoc DL;
556   if (!MBB.empty()) {
557     MBBI = MBB.getFirstTerminator();
558     if (MBBI == MBB.end())
559       MBBI = MBB.getLastNonDebugInstr();
560     DL = MBBI->getDebugLoc();
561 
562     // If this is not a terminator, the actual insert location should be after the
563     // last instruction.
564     if (!MBBI->isTerminator())
565       MBBI = std::next(MBBI);
566 
567     // If callee-saved registers are saved via libcall, place stack adjustment
568     // before this call.
569     while (MBBI != MBB.begin() &&
570            std::prev(MBBI)->getFlag(MachineInstr::FrameDestroy))
571       --MBBI;
572   }
573 
574   const auto &CSI = getNonLibcallCSI(MF, MFI.getCalleeSavedInfo());
575 
576   // Skip to before the restores of callee-saved registers
577   // FIXME: assumes exactly one instruction is used to restore each
578   // callee-saved register.
579   auto LastFrameDestroy = MBBI;
580   if (!CSI.empty())
581     LastFrameDestroy = std::prev(MBBI, CSI.size());
582 
583   uint64_t StackSize = MFI.getStackSize() + RVFI->getRVVPadding();
584   uint64_t RealStackSize = StackSize + RVFI->getLibCallStackSize();
585   uint64_t FPOffset = RealStackSize - RVFI->getVarArgsSaveSize();
586   uint64_t RVVStackSize = RVFI->getRVVStackSize();
587 
588   // Restore the stack pointer using the value of the frame pointer. Only
589   // necessary if the stack pointer was modified, meaning the stack size is
590   // unknown.
591   if (RI->hasStackRealignment(MF) || MFI.hasVarSizedObjects()) {
592     assert(hasFP(MF) && "frame pointer should not have been eliminated");
593     adjustReg(MBB, LastFrameDestroy, DL, SPReg, FPReg, -FPOffset,
594               MachineInstr::FrameDestroy);
595   } else {
596     if (RVVStackSize)
597       adjustStackForRVV(MF, MBB, LastFrameDestroy, DL, RVVStackSize,
598                         MachineInstr::FrameDestroy);
599   }
600 
601   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
602   if (FirstSPAdjustAmount) {
603     uint64_t SecondSPAdjustAmount = MFI.getStackSize() - FirstSPAdjustAmount;
604     assert(SecondSPAdjustAmount > 0 &&
605            "SecondSPAdjustAmount should be greater than zero");
606 
607     adjustReg(MBB, LastFrameDestroy, DL, SPReg, SPReg, SecondSPAdjustAmount,
608               MachineInstr::FrameDestroy);
609   }
610 
611   if (FirstSPAdjustAmount)
612     StackSize = FirstSPAdjustAmount;
613 
614   // Deallocate stack
615   adjustReg(MBB, MBBI, DL, SPReg, SPReg, StackSize, MachineInstr::FrameDestroy);
616 
617   // Emit epilogue for shadow call stack.
618   emitSCSEpilogue(MF, MBB, MBBI, DL);
619 }
620 
621 StackOffset
622 RISCVFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
623                                            Register &FrameReg) const {
624   const MachineFrameInfo &MFI = MF.getFrameInfo();
625   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
626   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
627 
628   // Callee-saved registers should be referenced relative to the stack
629   // pointer (positive offset), otherwise use the frame pointer (negative
630   // offset).
631   const auto &CSI = getNonLibcallCSI(MF, MFI.getCalleeSavedInfo());
632   int MinCSFI = 0;
633   int MaxCSFI = -1;
634   StackOffset Offset;
635   auto StackID = MFI.getStackID(FI);
636 
637   assert((StackID == TargetStackID::Default ||
638           StackID == TargetStackID::ScalableVector) &&
639          "Unexpected stack ID for the frame object.");
640   if (StackID == TargetStackID::Default) {
641     Offset =
642         StackOffset::getFixed(MFI.getObjectOffset(FI) - getOffsetOfLocalArea() +
643                               MFI.getOffsetAdjustment());
644   } else if (StackID == TargetStackID::ScalableVector) {
645     Offset = StackOffset::getScalable(MFI.getObjectOffset(FI));
646   }
647 
648   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
649 
650   if (CSI.size()) {
651     MinCSFI = CSI[0].getFrameIdx();
652     MaxCSFI = CSI[CSI.size() - 1].getFrameIdx();
653   }
654 
655   if (FI >= MinCSFI && FI <= MaxCSFI) {
656     FrameReg = RISCV::X2;
657 
658     if (FirstSPAdjustAmount)
659       Offset += StackOffset::getFixed(FirstSPAdjustAmount);
660     else
661       Offset +=
662           StackOffset::getFixed(MFI.getStackSize() + RVFI->getRVVPadding());
663   } else if (RI->hasStackRealignment(MF) && !MFI.isFixedObjectIndex(FI)) {
664     // If the stack was realigned, the frame pointer is set in order to allow
665     // SP to be restored, so we need another base register to record the stack
666     // after realignment.
667     if (hasBP(MF)) {
668       FrameReg = RISCVABI::getBPReg();
669       // |--------------------------| -- <-- FP
670       // | callee-saved registers   | | <----.
671       // |--------------------------| --     |
672       // | realignment (the size of | |      |
673       // | this area is not counted | |      |
674       // | in MFI.getStackSize())   | |      |
675       // |--------------------------| --     |
676       // | Padding after RVV        | |      |
677       // | (not counted in          | |      |
678       // | MFI.getStackSize())      | |      |
679       // |--------------------------| --     |-- MFI.getStackSize()
680       // | RVV objects              | |      |
681       // | (not counted in          | |      |
682       // | MFI.getStackSize())      | |      |
683       // |--------------------------| --     |
684       // | Padding before RVV       | |      |
685       // | (not counted in          | |      |
686       // | MFI.getStackSize())      | |      |
687       // |--------------------------| --     |
688       // | scalar local variables   | | <----'
689       // |--------------------------| -- <-- BP
690       // | VarSize objects          | |
691       // |--------------------------| -- <-- SP
692     } else {
693       FrameReg = RISCV::X2;
694       // |--------------------------| -- <-- FP
695       // | callee-saved registers   | | <----.
696       // |--------------------------| --     |
697       // | realignment (the size of | |      |
698       // | this area is not counted | |      |
699       // | in MFI.getStackSize())   | |      |
700       // |--------------------------| --     |
701       // | Padding after RVV        | |      |
702       // | (not counted in          | |      |
703       // | MFI.getStackSize())      | |      |
704       // |--------------------------| --     |-- MFI.getStackSize()
705       // | RVV objects              | |      |
706       // | (not counted in          | |      |
707       // | MFI.getStackSize())      | |      |
708       // |--------------------------| --     |
709       // | Padding before RVV       | |      |
710       // | (not counted in          | |      |
711       // | MFI.getStackSize())      | |      |
712       // |--------------------------| --     |
713       // | scalar local variables   | | <----'
714       // |--------------------------| -- <-- SP
715     }
716     // The total amount of padding surrounding RVV objects is described by
717     // RVV->getRVVPadding() and it can be zero. It allows us to align the RVV
718     // objects to 8 bytes.
719     if (MFI.getStackID(FI) == TargetStackID::Default) {
720       Offset += StackOffset::getFixed(MFI.getStackSize());
721       if (FI < 0)
722         Offset += StackOffset::getFixed(RVFI->getLibCallStackSize());
723     } else if (MFI.getStackID(FI) == TargetStackID::ScalableVector) {
724       Offset += StackOffset::get(
725           alignTo(MFI.getStackSize() - RVFI->getCalleeSavedStackSize(), 8),
726           RVFI->getRVVStackSize());
727     }
728   } else {
729     FrameReg = RI->getFrameRegister(MF);
730     if (hasFP(MF)) {
731       Offset += StackOffset::getFixed(RVFI->getVarArgsSaveSize());
732       if (FI >= 0)
733         Offset -= StackOffset::getFixed(RVFI->getLibCallStackSize());
734       // When using FP to access scalable vector objects, we need to minus
735       // the frame size.
736       //
737       // |--------------------------| -- <-- FP
738       // | callee-saved registers   | |
739       // |--------------------------| | MFI.getStackSize()
740       // | scalar local variables   | |
741       // |--------------------------| -- (Offset of RVV objects is from here.)
742       // | RVV objects              |
743       // |--------------------------|
744       // | VarSize objects          |
745       // |--------------------------| <-- SP
746       if (MFI.getStackID(FI) == TargetStackID::ScalableVector)
747         Offset -= StackOffset::getFixed(MFI.getStackSize());
748     } else {
749       // When using SP to access frame objects, we need to add RVV stack size.
750       //
751       // |--------------------------| -- <-- FP
752       // | callee-saved registers   | | <----.
753       // |--------------------------| --     |
754       // | Padding after RVV        | |      |
755       // | (not counted in          | |      |
756       // | MFI.getStackSize())      | |      |
757       // |--------------------------| --     |
758       // | RVV objects              | |      |-- MFI.getStackSize()
759       // | (not counted in          | |      |
760       // | MFI.getStackSize())      | |      |
761       // |--------------------------| --     |
762       // | Padding before RVV       | |      |
763       // | (not counted in          | |      |
764       // | MFI.getStackSize())      | |      |
765       // |--------------------------| --     |
766       // | scalar local variables   | | <----'
767       // |--------------------------| -- <-- SP
768       //
769       // The total amount of padding surrounding RVV objects is described by
770       // RVV->getRVVPadding() and it can be zero. It allows us to align the RVV
771       // objects to 8 bytes.
772       if (MFI.getStackID(FI) == TargetStackID::Default) {
773         if (MFI.isFixedObjectIndex(FI)) {
774           Offset +=
775               StackOffset::get(MFI.getStackSize() + RVFI->getRVVPadding() +
776                                    RVFI->getLibCallStackSize(),
777                                RVFI->getRVVStackSize());
778         } else {
779           Offset += StackOffset::getFixed(MFI.getStackSize());
780         }
781       } else if (MFI.getStackID(FI) == TargetStackID::ScalableVector) {
782         Offset += StackOffset::get(
783             alignTo(MFI.getStackSize() - RVFI->getCalleeSavedStackSize(), 8),
784             RVFI->getRVVStackSize());
785       }
786     }
787   }
788 
789   return Offset;
790 }
791 
792 void RISCVFrameLowering::determineCalleeSaves(MachineFunction &MF,
793                                               BitVector &SavedRegs,
794                                               RegScavenger *RS) const {
795   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
796   // Unconditionally spill RA and FP only if the function uses a frame
797   // pointer.
798   if (hasFP(MF)) {
799     SavedRegs.set(RISCV::X1);
800     SavedRegs.set(RISCV::X8);
801   }
802   // Mark BP as used if function has dedicated base pointer.
803   if (hasBP(MF))
804     SavedRegs.set(RISCVABI::getBPReg());
805 
806   // If interrupt is enabled and there are calls in the handler,
807   // unconditionally save all Caller-saved registers and
808   // all FP registers, regardless whether they are used.
809   MachineFrameInfo &MFI = MF.getFrameInfo();
810 
811   if (MF.getFunction().hasFnAttribute("interrupt") && MFI.hasCalls()) {
812 
813     static const MCPhysReg CSRegs[] = { RISCV::X1,      /* ra */
814       RISCV::X5, RISCV::X6, RISCV::X7,                  /* t0-t2 */
815       RISCV::X10, RISCV::X11,                           /* a0-a1, a2-a7 */
816       RISCV::X12, RISCV::X13, RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17,
817       RISCV::X28, RISCV::X29, RISCV::X30, RISCV::X31, 0 /* t3-t6 */
818     };
819 
820     for (unsigned i = 0; CSRegs[i]; ++i)
821       SavedRegs.set(CSRegs[i]);
822 
823     if (MF.getSubtarget<RISCVSubtarget>().hasStdExtF()) {
824 
825       // If interrupt is enabled, this list contains all FP registers.
826       const MCPhysReg * Regs = MF.getRegInfo().getCalleeSavedRegs();
827 
828       for (unsigned i = 0; Regs[i]; ++i)
829         if (RISCV::FPR16RegClass.contains(Regs[i]) ||
830             RISCV::FPR32RegClass.contains(Regs[i]) ||
831             RISCV::FPR64RegClass.contains(Regs[i]))
832           SavedRegs.set(Regs[i]);
833     }
834   }
835 }
836 
837 int64_t
838 RISCVFrameLowering::assignRVVStackObjectOffsets(MachineFrameInfo &MFI) const {
839   int64_t Offset = 0;
840   // Create a buffer of RVV objects to allocate.
841   SmallVector<int, 8> ObjectsToAllocate;
842   for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
843     unsigned StackID = MFI.getStackID(I);
844     if (StackID != TargetStackID::ScalableVector)
845       continue;
846     if (MFI.isDeadObjectIndex(I))
847       continue;
848 
849     ObjectsToAllocate.push_back(I);
850   }
851 
852   // Allocate all RVV locals and spills
853   for (int FI : ObjectsToAllocate) {
854     // ObjectSize in bytes.
855     int64_t ObjectSize = MFI.getObjectSize(FI);
856     // If the data type is the fractional vector type, reserve one vector
857     // register for it.
858     if (ObjectSize < 8)
859       ObjectSize = 8;
860     // Currently, all scalable vector types are aligned to 8 bytes.
861     Offset = alignTo(Offset + ObjectSize, 8);
862     MFI.setObjectOffset(FI, -Offset);
863   }
864 
865   return Offset;
866 }
867 
868 static bool hasRVVSpillWithFIs(MachineFunction &MF, const RISCVInstrInfo &TII) {
869   if (!MF.getSubtarget<RISCVSubtarget>().hasVInstructions())
870     return false;
871   return any_of(MF, [&TII](const MachineBasicBlock &MBB) {
872     return any_of(MBB, [&TII](const MachineInstr &MI) {
873       return TII.isRVVSpill(MI, /*CheckFIs*/ true);
874     });
875   });
876 }
877 
878 void RISCVFrameLowering::processFunctionBeforeFrameFinalized(
879     MachineFunction &MF, RegScavenger *RS) const {
880   const RISCVRegisterInfo *RegInfo =
881       MF.getSubtarget<RISCVSubtarget>().getRegisterInfo();
882   MachineFrameInfo &MFI = MF.getFrameInfo();
883   const TargetRegisterClass *RC = &RISCV::GPRRegClass;
884   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
885 
886   int64_t RVVStackSize = assignRVVStackObjectOffsets(MFI);
887   RVFI->setRVVStackSize(RVVStackSize);
888   const RISCVInstrInfo &TII = *MF.getSubtarget<RISCVSubtarget>().getInstrInfo();
889 
890   // estimateStackSize has been observed to under-estimate the final stack
891   // size, so give ourselves wiggle-room by checking for stack size
892   // representable an 11-bit signed field rather than 12-bits.
893   // FIXME: It may be possible to craft a function with a small stack that
894   // still needs an emergency spill slot for branch relaxation. This case
895   // would currently be missed.
896   // RVV loads & stores have no capacity to hold the immediate address offsets
897   // so we must always reserve an emergency spill slot if the MachineFunction
898   // contains any RVV spills.
899   if (!isInt<11>(MFI.estimateStackSize(MF)) || hasRVVSpillWithFIs(MF, TII)) {
900     int RegScavFI = MFI.CreateStackObject(RegInfo->getSpillSize(*RC),
901                                           RegInfo->getSpillAlign(*RC), false);
902     RS->addScavengingFrameIndex(RegScavFI);
903     // For RVV, scalable stack offsets require up to two scratch registers to
904     // compute the final offset. Reserve an additional emergency spill slot.
905     if (RVVStackSize != 0) {
906       int RVVRegScavFI = MFI.CreateStackObject(
907           RegInfo->getSpillSize(*RC), RegInfo->getSpillAlign(*RC), false);
908       RS->addScavengingFrameIndex(RVVRegScavFI);
909     }
910   }
911 
912   if (MFI.getCalleeSavedInfo().empty() || RVFI->useSaveRestoreLibCalls(MF)) {
913     RVFI->setCalleeSavedStackSize(0);
914     return;
915   }
916 
917   unsigned Size = 0;
918   for (const auto &Info : MFI.getCalleeSavedInfo()) {
919     int FrameIdx = Info.getFrameIdx();
920     if (MFI.getStackID(FrameIdx) != TargetStackID::Default)
921       continue;
922 
923     Size += MFI.getObjectSize(FrameIdx);
924   }
925   RVFI->setCalleeSavedStackSize(Size);
926 
927   // Padding required to keep the RVV stack aligned to 8 bytes
928   // within the main stack. We only need this when not using FP.
929   if (RVVStackSize && !hasFP(MF) && Size % 8 != 0) {
930     // Because we add the padding to the size of the stack, adding
931     // getStackAlign() will keep it aligned.
932     RVFI->setRVVPadding(getStackAlign().value());
933   }
934 }
935 
936 static bool hasRVVFrameObject(const MachineFunction &MF) {
937   const MachineFrameInfo &MFI = MF.getFrameInfo();
938   for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I)
939     if (MFI.getStackID(I) == TargetStackID::ScalableVector)
940       return true;
941   return false;
942 }
943 
944 // Not preserve stack space within prologue for outgoing variables when the
945 // function contains variable size objects or there are vector objects accessed
946 // by the frame pointer.
947 // Let eliminateCallFramePseudoInstr preserve stack space for it.
948 bool RISCVFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
949   return !MF.getFrameInfo().hasVarSizedObjects() &&
950          !(hasFP(MF) && hasRVVFrameObject(MF));
951 }
952 
953 // Eliminate ADJCALLSTACKDOWN, ADJCALLSTACKUP pseudo instructions.
954 MachineBasicBlock::iterator RISCVFrameLowering::eliminateCallFramePseudoInstr(
955     MachineFunction &MF, MachineBasicBlock &MBB,
956     MachineBasicBlock::iterator MI) const {
957   Register SPReg = RISCV::X2;
958   DebugLoc DL = MI->getDebugLoc();
959 
960   if (!hasReservedCallFrame(MF)) {
961     // If space has not been reserved for a call frame, ADJCALLSTACKDOWN and
962     // ADJCALLSTACKUP must be converted to instructions manipulating the stack
963     // pointer. This is necessary when there is a variable length stack
964     // allocation (e.g. alloca), which means it's not possible to allocate
965     // space for outgoing arguments from within the function prologue.
966     int64_t Amount = MI->getOperand(0).getImm();
967 
968     if (Amount != 0) {
969       // Ensure the stack remains aligned after adjustment.
970       Amount = alignSPAdjust(Amount);
971 
972       if (MI->getOpcode() == RISCV::ADJCALLSTACKDOWN)
973         Amount = -Amount;
974 
975       adjustReg(MBB, MI, DL, SPReg, SPReg, Amount, MachineInstr::NoFlags);
976     }
977   }
978 
979   return MBB.erase(MI);
980 }
981 
982 // We would like to split the SP adjustment to reduce prologue/epilogue
983 // as following instructions. In this way, the offset of the callee saved
984 // register could fit in a single store.
985 //   add     sp,sp,-2032
986 //   sw      ra,2028(sp)
987 //   sw      s0,2024(sp)
988 //   sw      s1,2020(sp)
989 //   sw      s3,2012(sp)
990 //   sw      s4,2008(sp)
991 //   add     sp,sp,-64
992 uint64_t
993 RISCVFrameLowering::getFirstSPAdjustAmount(const MachineFunction &MF) const {
994   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
995   const MachineFrameInfo &MFI = MF.getFrameInfo();
996   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
997   uint64_t StackSize = MFI.getStackSize();
998 
999   // Disable SplitSPAdjust if save-restore libcall used. The callee saved
1000   // registers will be pushed by the save-restore libcalls, so we don't have to
1001   // split the SP adjustment in this case.
1002   if (RVFI->getLibCallStackSize())
1003     return 0;
1004 
1005   // Return the FirstSPAdjustAmount if the StackSize can not fit in signed
1006   // 12-bit and there exists a callee saved register need to be pushed.
1007   if (!isInt<12>(StackSize) && (CSI.size() > 0)) {
1008     // FirstSPAdjustAmount is choosed as (2048 - StackAlign)
1009     // because 2048 will cause sp = sp + 2048 in epilogue split into
1010     // multi-instructions. The offset smaller than 2048 can fit in signle
1011     // load/store instruction and we have to stick with the stack alignment.
1012     // 2048 is 16-byte alignment. The stack alignment for RV32 and RV64 is 16,
1013     // for RV32E is 4. So (2048 - StackAlign) will satisfy the stack alignment.
1014     return 2048 - getStackAlign().value();
1015   }
1016   return 0;
1017 }
1018 
1019 bool RISCVFrameLowering::spillCalleeSavedRegisters(
1020     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1021     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
1022   if (CSI.empty())
1023     return true;
1024 
1025   MachineFunction *MF = MBB.getParent();
1026   const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
1027   DebugLoc DL;
1028   if (MI != MBB.end() && !MI->isDebugInstr())
1029     DL = MI->getDebugLoc();
1030 
1031   const char *SpillLibCall = getSpillLibCallName(*MF, CSI);
1032   if (SpillLibCall) {
1033     // Add spill libcall via non-callee-saved register t0.
1034     BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoCALLReg), RISCV::X5)
1035         .addExternalSymbol(SpillLibCall, RISCVII::MO_CALL)
1036         .setMIFlag(MachineInstr::FrameSetup);
1037 
1038     // Add registers spilled in libcall as liveins.
1039     for (auto &CS : CSI)
1040       MBB.addLiveIn(CS.getReg());
1041   }
1042 
1043   // Manually spill values not spilled by libcall.
1044   const auto &NonLibcallCSI = getNonLibcallCSI(*MF, CSI);
1045   for (auto &CS : NonLibcallCSI) {
1046     // Insert the spill to the stack frame.
1047     Register Reg = CS.getReg();
1048     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1049     TII.storeRegToStackSlot(MBB, MI, Reg, !MBB.isLiveIn(Reg), CS.getFrameIdx(),
1050                             RC, TRI);
1051   }
1052 
1053   return true;
1054 }
1055 
1056 bool RISCVFrameLowering::restoreCalleeSavedRegisters(
1057     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1058     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
1059   if (CSI.empty())
1060     return true;
1061 
1062   MachineFunction *MF = MBB.getParent();
1063   const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
1064   DebugLoc DL;
1065   if (MI != MBB.end() && !MI->isDebugInstr())
1066     DL = MI->getDebugLoc();
1067 
1068   // Manually restore values not restored by libcall. Insert in reverse order.
1069   // loadRegFromStackSlot can insert multiple instructions.
1070   const auto &NonLibcallCSI = getNonLibcallCSI(*MF, CSI);
1071   for (auto &CS : reverse(NonLibcallCSI)) {
1072     Register Reg = CS.getReg();
1073     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1074     TII.loadRegFromStackSlot(MBB, MI, Reg, CS.getFrameIdx(), RC, TRI);
1075     assert(MI != MBB.begin() && "loadRegFromStackSlot didn't insert any code!");
1076   }
1077 
1078   const char *RestoreLibCall = getRestoreLibCallName(*MF, CSI);
1079   if (RestoreLibCall) {
1080     // Add restore libcall via tail call.
1081     MachineBasicBlock::iterator NewMI =
1082         BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoTAIL))
1083             .addExternalSymbol(RestoreLibCall, RISCVII::MO_CALL)
1084             .setMIFlag(MachineInstr::FrameDestroy);
1085 
1086     // Remove trailing returns, since the terminator is now a tail call to the
1087     // restore function.
1088     if (MI != MBB.end() && MI->getOpcode() == RISCV::PseudoRET) {
1089       NewMI->copyImplicitOps(*MF, *MI);
1090       MI->eraseFromParent();
1091     }
1092   }
1093 
1094   return true;
1095 }
1096 
1097 bool RISCVFrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {
1098   // Keep the conventional code flow when not optimizing.
1099   if (MF.getFunction().hasOptNone())
1100     return false;
1101 
1102   return true;
1103 }
1104 
1105 bool RISCVFrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const {
1106   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
1107   const MachineFunction *MF = MBB.getParent();
1108   const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
1109 
1110   if (!RVFI->useSaveRestoreLibCalls(*MF))
1111     return true;
1112 
1113   // Inserting a call to a __riscv_save libcall requires the use of the register
1114   // t0 (X5) to hold the return address. Therefore if this register is already
1115   // used we can't insert the call.
1116 
1117   RegScavenger RS;
1118   RS.enterBasicBlock(*TmpMBB);
1119   return !RS.isRegUsed(RISCV::X5);
1120 }
1121 
1122 bool RISCVFrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
1123   const MachineFunction *MF = MBB.getParent();
1124   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
1125   const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
1126 
1127   if (!RVFI->useSaveRestoreLibCalls(*MF))
1128     return true;
1129 
1130   // Using the __riscv_restore libcalls to restore CSRs requires a tail call.
1131   // This means if we still need to continue executing code within this function
1132   // the restore cannot take place in this basic block.
1133 
1134   if (MBB.succ_size() > 1)
1135     return false;
1136 
1137   MachineBasicBlock *SuccMBB =
1138       MBB.succ_empty() ? TmpMBB->getFallThrough() : *MBB.succ_begin();
1139 
1140   // Doing a tail call should be safe if there are no successors, because either
1141   // we have a returning block or the end of the block is unreachable, so the
1142   // restore will be eliminated regardless.
1143   if (!SuccMBB)
1144     return true;
1145 
1146   // The successor can only contain a return, since we would effectively be
1147   // replacing the successor with our own tail return at the end of our block.
1148   return SuccMBB->isReturnBlock() && SuccMBB->size() == 1;
1149 }
1150 
1151 bool RISCVFrameLowering::isSupportedStackID(TargetStackID::Value ID) const {
1152   switch (ID) {
1153   case TargetStackID::Default:
1154   case TargetStackID::ScalableVector:
1155     return true;
1156   case TargetStackID::NoAlloc:
1157   case TargetStackID::SGPRSpill:
1158   case TargetStackID::WasmLocal:
1159     return false;
1160   }
1161   llvm_unreachable("Invalid TargetStackID::Value");
1162 }
1163 
1164 TargetStackID::Value RISCVFrameLowering::getStackIDForScalableVectors() const {
1165   return TargetStackID::ScalableVector;
1166 }
1167