xref: /freebsd/contrib/llvm-project/llvm/lib/Target/RISCV/RISCVFrameLowering.cpp (revision 5956d97f4b3204318ceb6aa9c77bd0bc6ea87a41)
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   // If we do not reserve stack space for outgoing arguments in prologue,
241   // we will adjust the stack pointer before call instruction. After the
242   // adjustment, we can not use SP to access the stack objects for the
243   // arguments. Instead, use BP to access these stack objects.
244   return (MFI.hasVarSizedObjects() ||
245           (!hasReservedCallFrame(MF) && (!MFI.isMaxCallFrameSizeComputed() ||
246                                          MFI.getMaxCallFrameSize() != 0))) &&
247          TRI->hasStackRealignment(MF);
248 }
249 
250 // Determines the size of the frame and maximum call frame size.
251 void RISCVFrameLowering::determineFrameLayout(MachineFunction &MF) const {
252   MachineFrameInfo &MFI = MF.getFrameInfo();
253 
254   // Get the number of bytes to allocate from the FrameInfo.
255   uint64_t FrameSize = MFI.getStackSize();
256 
257   // Get the alignment.
258   Align StackAlign = getStackAlign();
259 
260   // Make sure the frame is aligned.
261   FrameSize = alignTo(FrameSize, StackAlign);
262 
263   // Update frame info.
264   MFI.setStackSize(FrameSize);
265 }
266 
267 void RISCVFrameLowering::adjustReg(MachineBasicBlock &MBB,
268                                    MachineBasicBlock::iterator MBBI,
269                                    const DebugLoc &DL, Register DestReg,
270                                    Register SrcReg, int64_t Val,
271                                    MachineInstr::MIFlag Flag) const {
272   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
273   const RISCVInstrInfo *TII = STI.getInstrInfo();
274 
275   if (DestReg == SrcReg && Val == 0)
276     return;
277 
278   if (isInt<12>(Val)) {
279     BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), DestReg)
280         .addReg(SrcReg)
281         .addImm(Val)
282         .setMIFlag(Flag);
283   } else {
284     unsigned Opc = RISCV::ADD;
285     bool isSub = Val < 0;
286     if (isSub) {
287       Val = -Val;
288       Opc = RISCV::SUB;
289     }
290 
291     Register ScratchReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
292     TII->movImm(MBB, MBBI, DL, ScratchReg, Val, Flag);
293     BuildMI(MBB, MBBI, DL, TII->get(Opc), DestReg)
294         .addReg(SrcReg)
295         .addReg(ScratchReg, RegState::Kill)
296         .setMIFlag(Flag);
297   }
298 }
299 
300 // Returns the register used to hold the frame pointer.
301 static Register getFPReg(const RISCVSubtarget &STI) { return RISCV::X8; }
302 
303 // Returns the register used to hold the stack pointer.
304 static Register getSPReg(const RISCVSubtarget &STI) { return RISCV::X2; }
305 
306 static SmallVector<CalleeSavedInfo, 8>
307 getNonLibcallCSI(const MachineFunction &MF,
308                  const std::vector<CalleeSavedInfo> &CSI) {
309   const MachineFrameInfo &MFI = MF.getFrameInfo();
310   SmallVector<CalleeSavedInfo, 8> NonLibcallCSI;
311 
312   for (auto &CS : CSI) {
313     int FI = CS.getFrameIdx();
314     if (FI >= 0 && MFI.getStackID(FI) == TargetStackID::Default)
315       NonLibcallCSI.push_back(CS);
316   }
317 
318   return NonLibcallCSI;
319 }
320 
321 void RISCVFrameLowering::adjustStackForRVV(MachineFunction &MF,
322                                            MachineBasicBlock &MBB,
323                                            MachineBasicBlock::iterator MBBI,
324                                            const DebugLoc &DL, int64_t Amount,
325                                            MachineInstr::MIFlag Flag) const {
326   assert(Amount != 0 && "Did not need to adjust stack pointer for RVV.");
327 
328   const RISCVInstrInfo *TII = STI.getInstrInfo();
329   Register SPReg = getSPReg(STI);
330   unsigned Opc = RISCV::ADD;
331   if (Amount < 0) {
332     Amount = -Amount;
333     Opc = RISCV::SUB;
334   }
335   // 1. Multiply the number of v-slots to the length of registers
336   Register FactorRegister =
337       TII->getVLENFactoredAmount(MF, MBB, MBBI, DL, Amount, Flag);
338   // 2. SP = SP - RVV stack size
339   BuildMI(MBB, MBBI, DL, TII->get(Opc), SPReg)
340       .addReg(SPReg)
341       .addReg(FactorRegister, RegState::Kill)
342       .setMIFlag(Flag);
343 }
344 
345 void RISCVFrameLowering::emitPrologue(MachineFunction &MF,
346                                       MachineBasicBlock &MBB) const {
347   MachineFrameInfo &MFI = MF.getFrameInfo();
348   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
349   const RISCVRegisterInfo *RI = STI.getRegisterInfo();
350   const RISCVInstrInfo *TII = STI.getInstrInfo();
351   MachineBasicBlock::iterator MBBI = MBB.begin();
352 
353   Register FPReg = getFPReg(STI);
354   Register SPReg = getSPReg(STI);
355   Register BPReg = RISCVABI::getBPReg();
356 
357   // Debug location must be unknown since the first debug location is used
358   // to determine the end of the prologue.
359   DebugLoc DL;
360 
361   // All calls are tail calls in GHC calling conv, and functions have no
362   // prologue/epilogue.
363   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
364     return;
365 
366   // Emit prologue for shadow call stack.
367   emitSCSPrologue(MF, MBB, MBBI, DL);
368 
369   // Since spillCalleeSavedRegisters may have inserted a libcall, skip past
370   // any instructions marked as FrameSetup
371   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
372     ++MBBI;
373 
374   // Determine the correct frame layout
375   determineFrameLayout(MF);
376 
377   // If libcalls are used to spill and restore callee-saved registers, the frame
378   // has two sections; the opaque section managed by the libcalls, and the
379   // section managed by MachineFrameInfo which can also hold callee saved
380   // registers in fixed stack slots, both of which have negative frame indices.
381   // This gets even more complicated when incoming arguments are passed via the
382   // stack, as these too have negative frame indices. An example is detailed
383   // below:
384   //
385   //  | incoming arg | <- FI[-3]
386   //  | libcallspill |
387   //  | calleespill  | <- FI[-2]
388   //  | calleespill  | <- FI[-1]
389   //  | this_frame   | <- FI[0]
390   //
391   // For negative frame indices, the offset from the frame pointer will differ
392   // depending on which of these groups the frame index applies to.
393   // The following calculates the correct offset knowing the number of callee
394   // saved registers spilt by the two methods.
395   if (int LibCallRegs = getLibCallID(MF, MFI.getCalleeSavedInfo()) + 1) {
396     // Calculate the size of the frame managed by the libcall. The libcalls are
397     // implemented such that the stack will always be 16 byte aligned.
398     unsigned LibCallFrameSize = alignTo((STI.getXLen() / 8) * LibCallRegs, 16);
399     RVFI->setLibCallStackSize(LibCallFrameSize);
400   }
401 
402   // FIXME (note copied from Lanai): This appears to be overallocating.  Needs
403   // investigation. Get the number of bytes to allocate from the FrameInfo.
404   uint64_t StackSize = MFI.getStackSize() + RVFI->getRVVPadding();
405   uint64_t RealStackSize = StackSize + RVFI->getLibCallStackSize();
406   uint64_t RVVStackSize = RVFI->getRVVStackSize();
407 
408   // Early exit if there is no need to allocate on the stack
409   if (RealStackSize == 0 && !MFI.adjustsStack() && RVVStackSize == 0)
410     return;
411 
412   // If the stack pointer has been marked as reserved, then produce an error if
413   // the frame requires stack allocation
414   if (STI.isRegisterReservedByUser(SPReg))
415     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
416         MF.getFunction(), "Stack pointer required, but has been reserved."});
417 
418   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
419   // Split the SP adjustment to reduce the offsets of callee saved spill.
420   if (FirstSPAdjustAmount) {
421     StackSize = FirstSPAdjustAmount;
422     RealStackSize = FirstSPAdjustAmount;
423   }
424 
425   // Allocate space on the stack if necessary.
426   adjustReg(MBB, MBBI, DL, SPReg, SPReg, -StackSize, MachineInstr::FrameSetup);
427 
428   // Emit ".cfi_def_cfa_offset RealStackSize"
429   unsigned CFIIndex = MF.addFrameInst(
430       MCCFIInstruction::cfiDefCfaOffset(nullptr, RealStackSize));
431   BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
432       .addCFIIndex(CFIIndex)
433       .setMIFlag(MachineInstr::FrameSetup);
434 
435   const auto &CSI = MFI.getCalleeSavedInfo();
436 
437   // The frame pointer is callee-saved, and code has been generated for us to
438   // save it to the stack. We need to skip over the storing of callee-saved
439   // registers as the frame pointer must be modified after it has been saved
440   // to the stack, not before.
441   // FIXME: assumes exactly one instruction is used to save each callee-saved
442   // register.
443   std::advance(MBBI, getNonLibcallCSI(MF, CSI).size());
444 
445   // Iterate over list of callee-saved registers and emit .cfi_offset
446   // directives.
447   for (const auto &Entry : CSI) {
448     int FrameIdx = Entry.getFrameIdx();
449     int64_t Offset;
450     // Offsets for objects with fixed locations (IE: those saved by libcall) are
451     // simply calculated from the frame index.
452     if (FrameIdx < 0)
453       Offset = FrameIdx * (int64_t) STI.getXLen() / 8;
454     else
455       Offset = MFI.getObjectOffset(Entry.getFrameIdx()) -
456                RVFI->getLibCallStackSize();
457     Register Reg = Entry.getReg();
458     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
459         nullptr, RI->getDwarfRegNum(Reg, true), Offset));
460     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
461         .addCFIIndex(CFIIndex)
462         .setMIFlag(MachineInstr::FrameSetup);
463   }
464 
465   // Generate new FP.
466   if (hasFP(MF)) {
467     if (STI.isRegisterReservedByUser(FPReg))
468       MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
469           MF.getFunction(), "Frame pointer required, but has been reserved."});
470 
471     adjustReg(MBB, MBBI, DL, FPReg, SPReg,
472               RealStackSize - RVFI->getVarArgsSaveSize(),
473               MachineInstr::FrameSetup);
474 
475     // Emit ".cfi_def_cfa $fp, RVFI->getVarArgsSaveSize()"
476     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(
477         nullptr, RI->getDwarfRegNum(FPReg, true), RVFI->getVarArgsSaveSize()));
478     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
479         .addCFIIndex(CFIIndex)
480         .setMIFlag(MachineInstr::FrameSetup);
481   }
482 
483   // Emit the second SP adjustment after saving callee saved registers.
484   if (FirstSPAdjustAmount) {
485     uint64_t SecondSPAdjustAmount = MFI.getStackSize() - FirstSPAdjustAmount;
486     assert(SecondSPAdjustAmount > 0 &&
487            "SecondSPAdjustAmount should be greater than zero");
488     adjustReg(MBB, MBBI, DL, SPReg, SPReg, -SecondSPAdjustAmount,
489               MachineInstr::FrameSetup);
490 
491     // If we are using a frame-pointer, and thus emitted ".cfi_def_cfa fp, 0",
492     // don't emit an sp-based .cfi_def_cfa_offset
493     if (!hasFP(MF)) {
494       // Emit ".cfi_def_cfa_offset StackSize"
495       unsigned CFIIndex = MF.addFrameInst(
496           MCCFIInstruction::cfiDefCfaOffset(nullptr, MFI.getStackSize()));
497       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
498           .addCFIIndex(CFIIndex)
499           .setMIFlag(MachineInstr::FrameSetup);
500     }
501   }
502 
503   if (RVVStackSize)
504     adjustStackForRVV(MF, MBB, MBBI, DL, -RVVStackSize,
505                       MachineInstr::FrameSetup);
506 
507   if (hasFP(MF)) {
508     // Realign Stack
509     const RISCVRegisterInfo *RI = STI.getRegisterInfo();
510     if (RI->hasStackRealignment(MF)) {
511       Align MaxAlignment = MFI.getMaxAlign();
512 
513       const RISCVInstrInfo *TII = STI.getInstrInfo();
514       if (isInt<12>(-(int)MaxAlignment.value())) {
515         BuildMI(MBB, MBBI, DL, TII->get(RISCV::ANDI), SPReg)
516             .addReg(SPReg)
517             .addImm(-(int)MaxAlignment.value())
518             .setMIFlag(MachineInstr::FrameSetup);
519       } else {
520         unsigned ShiftAmount = Log2(MaxAlignment);
521         Register VR =
522             MF.getRegInfo().createVirtualRegister(&RISCV::GPRRegClass);
523         BuildMI(MBB, MBBI, DL, TII->get(RISCV::SRLI), VR)
524             .addReg(SPReg)
525             .addImm(ShiftAmount)
526             .setMIFlag(MachineInstr::FrameSetup);
527         BuildMI(MBB, MBBI, DL, TII->get(RISCV::SLLI), SPReg)
528             .addReg(VR)
529             .addImm(ShiftAmount)
530             .setMIFlag(MachineInstr::FrameSetup);
531       }
532       // FP will be used to restore the frame in the epilogue, so we need
533       // another base register BP to record SP after re-alignment. SP will
534       // track the current stack after allocating variable sized objects.
535       if (hasBP(MF)) {
536         // move BP, SP
537         BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), BPReg)
538             .addReg(SPReg)
539             .addImm(0)
540             .setMIFlag(MachineInstr::FrameSetup);
541       }
542     }
543   }
544 }
545 
546 void RISCVFrameLowering::emitEpilogue(MachineFunction &MF,
547                                       MachineBasicBlock &MBB) const {
548   const RISCVRegisterInfo *RI = STI.getRegisterInfo();
549   MachineFrameInfo &MFI = MF.getFrameInfo();
550   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
551   Register FPReg = getFPReg(STI);
552   Register SPReg = getSPReg(STI);
553 
554   // All calls are tail calls in GHC calling conv, and functions have no
555   // prologue/epilogue.
556   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
557     return;
558 
559   // Get the insert location for the epilogue. If there were no terminators in
560   // the block, get the last instruction.
561   MachineBasicBlock::iterator MBBI = MBB.end();
562   DebugLoc DL;
563   if (!MBB.empty()) {
564     MBBI = MBB.getFirstTerminator();
565     if (MBBI == MBB.end())
566       MBBI = MBB.getLastNonDebugInstr();
567     DL = MBBI->getDebugLoc();
568 
569     // If this is not a terminator, the actual insert location should be after the
570     // last instruction.
571     if (!MBBI->isTerminator())
572       MBBI = std::next(MBBI);
573 
574     // If callee-saved registers are saved via libcall, place stack adjustment
575     // before this call.
576     while (MBBI != MBB.begin() &&
577            std::prev(MBBI)->getFlag(MachineInstr::FrameDestroy))
578       --MBBI;
579   }
580 
581   const auto &CSI = getNonLibcallCSI(MF, MFI.getCalleeSavedInfo());
582 
583   // Skip to before the restores of callee-saved registers
584   // FIXME: assumes exactly one instruction is used to restore each
585   // callee-saved register.
586   auto LastFrameDestroy = MBBI;
587   if (!CSI.empty())
588     LastFrameDestroy = std::prev(MBBI, CSI.size());
589 
590   uint64_t StackSize = MFI.getStackSize() + RVFI->getRVVPadding();
591   uint64_t RealStackSize = StackSize + RVFI->getLibCallStackSize();
592   uint64_t FPOffset = RealStackSize - RVFI->getVarArgsSaveSize();
593   uint64_t RVVStackSize = RVFI->getRVVStackSize();
594 
595   // Restore the stack pointer using the value of the frame pointer. Only
596   // necessary if the stack pointer was modified, meaning the stack size is
597   // unknown.
598   if (RI->hasStackRealignment(MF) || MFI.hasVarSizedObjects()) {
599     assert(hasFP(MF) && "frame pointer should not have been eliminated");
600     adjustReg(MBB, LastFrameDestroy, DL, SPReg, FPReg, -FPOffset,
601               MachineInstr::FrameDestroy);
602   } else {
603     if (RVVStackSize)
604       adjustStackForRVV(MF, MBB, LastFrameDestroy, DL, RVVStackSize,
605                         MachineInstr::FrameDestroy);
606   }
607 
608   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
609   if (FirstSPAdjustAmount) {
610     uint64_t SecondSPAdjustAmount = MFI.getStackSize() - FirstSPAdjustAmount;
611     assert(SecondSPAdjustAmount > 0 &&
612            "SecondSPAdjustAmount should be greater than zero");
613 
614     adjustReg(MBB, LastFrameDestroy, DL, SPReg, SPReg, SecondSPAdjustAmount,
615               MachineInstr::FrameDestroy);
616   }
617 
618   if (FirstSPAdjustAmount)
619     StackSize = FirstSPAdjustAmount;
620 
621   // Deallocate stack
622   adjustReg(MBB, MBBI, DL, SPReg, SPReg, StackSize, MachineInstr::FrameDestroy);
623 
624   // Emit epilogue for shadow call stack.
625   emitSCSEpilogue(MF, MBB, MBBI, DL);
626 }
627 
628 StackOffset
629 RISCVFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
630                                            Register &FrameReg) const {
631   const MachineFrameInfo &MFI = MF.getFrameInfo();
632   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
633   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
634 
635   // Callee-saved registers should be referenced relative to the stack
636   // pointer (positive offset), otherwise use the frame pointer (negative
637   // offset).
638   const auto &CSI = getNonLibcallCSI(MF, MFI.getCalleeSavedInfo());
639   int MinCSFI = 0;
640   int MaxCSFI = -1;
641   StackOffset Offset;
642   auto StackID = MFI.getStackID(FI);
643 
644   assert((StackID == TargetStackID::Default ||
645           StackID == TargetStackID::ScalableVector) &&
646          "Unexpected stack ID for the frame object.");
647   if (StackID == TargetStackID::Default) {
648     Offset =
649         StackOffset::getFixed(MFI.getObjectOffset(FI) - getOffsetOfLocalArea() +
650                               MFI.getOffsetAdjustment());
651   } else if (StackID == TargetStackID::ScalableVector) {
652     Offset = StackOffset::getScalable(MFI.getObjectOffset(FI));
653   }
654 
655   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
656 
657   if (CSI.size()) {
658     MinCSFI = CSI[0].getFrameIdx();
659     MaxCSFI = CSI[CSI.size() - 1].getFrameIdx();
660   }
661 
662   if (FI >= MinCSFI && FI <= MaxCSFI) {
663     FrameReg = RISCV::X2;
664 
665     if (FirstSPAdjustAmount)
666       Offset += StackOffset::getFixed(FirstSPAdjustAmount);
667     else
668       Offset +=
669           StackOffset::getFixed(MFI.getStackSize() + RVFI->getRVVPadding());
670   } else if (RI->hasStackRealignment(MF) && !MFI.isFixedObjectIndex(FI)) {
671     // If the stack was realigned, the frame pointer is set in order to allow
672     // SP to be restored, so we need another base register to record the stack
673     // after realignment.
674     if (hasBP(MF)) {
675       FrameReg = RISCVABI::getBPReg();
676       // |--------------------------| -- <-- FP
677       // | callee-allocated save    | | <----|
678       // | area for register varargs| |      |
679       // |--------------------------| |      |
680       // | callee-saved registers   | |      |
681       // |--------------------------| --     |
682       // | realignment (the size of | |      |
683       // | this area is not counted | |      |
684       // | in MFI.getStackSize())   | |      |
685       // |--------------------------| --     |
686       // | Padding after RVV        | |      |
687       // | (not counted in          | |      |
688       // | MFI.getStackSize())      | |      |
689       // |--------------------------| --     |-- MFI.getStackSize()
690       // | RVV objects              | |      |
691       // | (not counted in          | |      |
692       // | MFI.getStackSize())      | |      |
693       // |--------------------------| --     |
694       // | Padding before RVV       | |      |
695       // | (not counted in          | |      |
696       // | MFI.getStackSize())      | |      |
697       // |--------------------------| --     |
698       // | scalar local variables   | | <----'
699       // |--------------------------| -- <-- BP
700       // | VarSize objects          | |
701       // |--------------------------| -- <-- SP
702     } else {
703       FrameReg = RISCV::X2;
704       // |--------------------------| -- <-- FP
705       // | callee-allocated save    | | <----|
706       // | area for register varargs| |      |
707       // |--------------------------| |      |
708       // | callee-saved registers   | |      |
709       // |--------------------------| --     |
710       // | realignment (the size of | |      |
711       // | this area is not counted | |      |
712       // | in MFI.getStackSize())   | |      |
713       // |--------------------------| --     |
714       // | Padding after RVV        | |      |
715       // | (not counted in          | |      |
716       // | MFI.getStackSize())      | |      |
717       // |--------------------------| --     |-- MFI.getStackSize()
718       // | RVV objects              | |      |
719       // | (not counted in          | |      |
720       // | MFI.getStackSize())      | |      |
721       // |--------------------------| --     |
722       // | Padding before RVV       | |      |
723       // | (not counted in          | |      |
724       // | MFI.getStackSize())      | |      |
725       // |--------------------------| --     |
726       // | scalar local variables   | | <----'
727       // |--------------------------| -- <-- SP
728     }
729     // The total amount of padding surrounding RVV objects is described by
730     // RVV->getRVVPadding() and it can be zero. It allows us to align the RVV
731     // objects to 8 bytes.
732     if (MFI.getStackID(FI) == TargetStackID::Default) {
733       Offset += StackOffset::getFixed(MFI.getStackSize());
734       if (FI < 0)
735         Offset += StackOffset::getFixed(RVFI->getLibCallStackSize());
736     } else if (MFI.getStackID(FI) == TargetStackID::ScalableVector) {
737       Offset += StackOffset::get(
738           alignTo(MFI.getStackSize() - RVFI->getCalleeSavedStackSize(), 8),
739           RVFI->getRVVStackSize());
740     }
741   } else {
742     FrameReg = RI->getFrameRegister(MF);
743     if (hasFP(MF)) {
744       Offset += StackOffset::getFixed(RVFI->getVarArgsSaveSize());
745       if (FI >= 0)
746         Offset -= StackOffset::getFixed(RVFI->getLibCallStackSize());
747       // When using FP to access scalable vector objects, we need to minus
748       // the frame size.
749       //
750       // |--------------------------| -- <-- FP
751       // | callee-allocated save    | |
752       // | area for register varargs| |
753       // |--------------------------| |
754       // | callee-saved registers   | |
755       // |--------------------------| | MFI.getStackSize()
756       // | scalar local variables   | |
757       // |--------------------------| -- (Offset of RVV objects is from here.)
758       // | RVV objects              |
759       // |--------------------------|
760       // | VarSize objects          |
761       // |--------------------------| <-- SP
762       if (MFI.getStackID(FI) == TargetStackID::ScalableVector)
763         Offset -= StackOffset::getFixed(MFI.getStackSize());
764     } else {
765       // When using SP to access frame objects, we need to add RVV stack size.
766       //
767       // |--------------------------| -- <-- FP
768       // | callee-allocated save    | | <----|
769       // | area for register varargs| |      |
770       // |--------------------------| |      |
771       // | callee-saved registers   | |      |
772       // |--------------------------| --     |
773       // | Padding after RVV        | |      |
774       // | (not counted in          | |      |
775       // | MFI.getStackSize())      | |      |
776       // |--------------------------| --     |
777       // | RVV objects              | |      |-- MFI.getStackSize()
778       // | (not counted in          | |      |
779       // | MFI.getStackSize())      | |      |
780       // |--------------------------| --     |
781       // | Padding before RVV       | |      |
782       // | (not counted in          | |      |
783       // | MFI.getStackSize())      | |      |
784       // |--------------------------| --     |
785       // | scalar local variables   | | <----'
786       // |--------------------------| -- <-- SP
787       //
788       // The total amount of padding surrounding RVV objects is described by
789       // RVV->getRVVPadding() and it can be zero. It allows us to align the RVV
790       // objects to 8 bytes.
791       if (MFI.getStackID(FI) == TargetStackID::Default) {
792         if (MFI.isFixedObjectIndex(FI)) {
793           Offset +=
794               StackOffset::get(MFI.getStackSize() + RVFI->getRVVPadding() +
795                                    RVFI->getLibCallStackSize(),
796                                RVFI->getRVVStackSize());
797         } else {
798           Offset += StackOffset::getFixed(MFI.getStackSize());
799         }
800       } else if (MFI.getStackID(FI) == TargetStackID::ScalableVector) {
801         int ScalarLocalVarSize = MFI.getStackSize() -
802                                  RVFI->getCalleeSavedStackSize() -
803                                  RVFI->getVarArgsSaveSize();
804         Offset += StackOffset::get(
805             alignTo(ScalarLocalVarSize, 8),
806             RVFI->getRVVStackSize());
807       }
808     }
809   }
810 
811   return Offset;
812 }
813 
814 void RISCVFrameLowering::determineCalleeSaves(MachineFunction &MF,
815                                               BitVector &SavedRegs,
816                                               RegScavenger *RS) const {
817   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
818   // Unconditionally spill RA and FP only if the function uses a frame
819   // pointer.
820   if (hasFP(MF)) {
821     SavedRegs.set(RISCV::X1);
822     SavedRegs.set(RISCV::X8);
823   }
824   // Mark BP as used if function has dedicated base pointer.
825   if (hasBP(MF))
826     SavedRegs.set(RISCVABI::getBPReg());
827 
828   // If interrupt is enabled and there are calls in the handler,
829   // unconditionally save all Caller-saved registers and
830   // all FP registers, regardless whether they are used.
831   MachineFrameInfo &MFI = MF.getFrameInfo();
832 
833   if (MF.getFunction().hasFnAttribute("interrupt") && MFI.hasCalls()) {
834 
835     static const MCPhysReg CSRegs[] = { RISCV::X1,      /* ra */
836       RISCV::X5, RISCV::X6, RISCV::X7,                  /* t0-t2 */
837       RISCV::X10, RISCV::X11,                           /* a0-a1, a2-a7 */
838       RISCV::X12, RISCV::X13, RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17,
839       RISCV::X28, RISCV::X29, RISCV::X30, RISCV::X31, 0 /* t3-t6 */
840     };
841 
842     for (unsigned i = 0; CSRegs[i]; ++i)
843       SavedRegs.set(CSRegs[i]);
844 
845     if (MF.getSubtarget<RISCVSubtarget>().hasStdExtF()) {
846 
847       // If interrupt is enabled, this list contains all FP registers.
848       const MCPhysReg * Regs = MF.getRegInfo().getCalleeSavedRegs();
849 
850       for (unsigned i = 0; Regs[i]; ++i)
851         if (RISCV::FPR16RegClass.contains(Regs[i]) ||
852             RISCV::FPR32RegClass.contains(Regs[i]) ||
853             RISCV::FPR64RegClass.contains(Regs[i]))
854           SavedRegs.set(Regs[i]);
855     }
856   }
857 }
858 
859 int64_t
860 RISCVFrameLowering::assignRVVStackObjectOffsets(MachineFrameInfo &MFI) const {
861   int64_t Offset = 0;
862   // Create a buffer of RVV objects to allocate.
863   SmallVector<int, 8> ObjectsToAllocate;
864   for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
865     unsigned StackID = MFI.getStackID(I);
866     if (StackID != TargetStackID::ScalableVector)
867       continue;
868     if (MFI.isDeadObjectIndex(I))
869       continue;
870 
871     ObjectsToAllocate.push_back(I);
872   }
873 
874   // Allocate all RVV locals and spills
875   for (int FI : ObjectsToAllocate) {
876     // ObjectSize in bytes.
877     int64_t ObjectSize = MFI.getObjectSize(FI);
878     // If the data type is the fractional vector type, reserve one vector
879     // register for it.
880     if (ObjectSize < 8)
881       ObjectSize = 8;
882     // Currently, all scalable vector types are aligned to 8 bytes.
883     Offset = alignTo(Offset + ObjectSize, 8);
884     MFI.setObjectOffset(FI, -Offset);
885   }
886 
887   return Offset;
888 }
889 
890 static bool hasRVVSpillWithFIs(MachineFunction &MF, const RISCVInstrInfo &TII) {
891   if (!MF.getSubtarget<RISCVSubtarget>().hasVInstructions())
892     return false;
893   return any_of(MF, [&TII](const MachineBasicBlock &MBB) {
894     return any_of(MBB, [&TII](const MachineInstr &MI) {
895       return TII.isRVVSpill(MI, /*CheckFIs*/ true);
896     });
897   });
898 }
899 
900 void RISCVFrameLowering::processFunctionBeforeFrameFinalized(
901     MachineFunction &MF, RegScavenger *RS) const {
902   const RISCVRegisterInfo *RegInfo =
903       MF.getSubtarget<RISCVSubtarget>().getRegisterInfo();
904   MachineFrameInfo &MFI = MF.getFrameInfo();
905   const TargetRegisterClass *RC = &RISCV::GPRRegClass;
906   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
907 
908   int64_t RVVStackSize = assignRVVStackObjectOffsets(MFI);
909   RVFI->setRVVStackSize(RVVStackSize);
910   const RISCVInstrInfo &TII = *MF.getSubtarget<RISCVSubtarget>().getInstrInfo();
911 
912   // estimateStackSize has been observed to under-estimate the final stack
913   // size, so give ourselves wiggle-room by checking for stack size
914   // representable an 11-bit signed field rather than 12-bits.
915   // FIXME: It may be possible to craft a function with a small stack that
916   // still needs an emergency spill slot for branch relaxation. This case
917   // would currently be missed.
918   // RVV loads & stores have no capacity to hold the immediate address offsets
919   // so we must always reserve an emergency spill slot if the MachineFunction
920   // contains any RVV spills.
921   if (!isInt<11>(MFI.estimateStackSize(MF)) || hasRVVSpillWithFIs(MF, TII)) {
922     int RegScavFI = MFI.CreateStackObject(RegInfo->getSpillSize(*RC),
923                                           RegInfo->getSpillAlign(*RC), false);
924     RS->addScavengingFrameIndex(RegScavFI);
925     // For RVV, scalable stack offsets require up to two scratch registers to
926     // compute the final offset. Reserve an additional emergency spill slot.
927     if (RVVStackSize != 0) {
928       int RVVRegScavFI = MFI.CreateStackObject(
929           RegInfo->getSpillSize(*RC), RegInfo->getSpillAlign(*RC), false);
930       RS->addScavengingFrameIndex(RVVRegScavFI);
931     }
932   }
933 
934   if (MFI.getCalleeSavedInfo().empty() || RVFI->useSaveRestoreLibCalls(MF)) {
935     RVFI->setCalleeSavedStackSize(0);
936     return;
937   }
938 
939   unsigned Size = 0;
940   for (const auto &Info : MFI.getCalleeSavedInfo()) {
941     int FrameIdx = Info.getFrameIdx();
942     if (MFI.getStackID(FrameIdx) != TargetStackID::Default)
943       continue;
944 
945     Size += MFI.getObjectSize(FrameIdx);
946   }
947   RVFI->setCalleeSavedStackSize(Size);
948 
949   // Padding required to keep the RVV stack aligned to 8 bytes
950   // within the main stack. We only need this when not using FP.
951   if (RVVStackSize && !hasFP(MF) && Size % 8 != 0) {
952     // Because we add the padding to the size of the stack, adding
953     // getStackAlign() will keep it aligned.
954     RVFI->setRVVPadding(getStackAlign().value());
955   }
956 }
957 
958 static bool hasRVVFrameObject(const MachineFunction &MF) {
959   // Originally, the function will scan all the stack objects to check whether
960   // if there is any scalable vector object on the stack or not. However, it
961   // causes errors in the register allocator. In issue 53016, it returns false
962   // before RA because there is no RVV stack objects. After RA, it returns true
963   // because there are spilling slots for RVV values during RA. It will not
964   // reserve BP during register allocation and generate BP access in the PEI
965   // pass due to the inconsistent behavior of the function.
966   //
967   // The function is changed to use hasVInstructions() as the return value. It
968   // is not precise, but it can make the register allocation correct.
969   //
970   // FIXME: Find a better way to make the decision or revisit the solution in
971   // D103622.
972   //
973   // Refer to https://github.com/llvm/llvm-project/issues/53016.
974   return MF.getSubtarget<RISCVSubtarget>().hasVInstructions();
975 }
976 
977 // Not preserve stack space within prologue for outgoing variables when the
978 // function contains variable size objects or there are vector objects accessed
979 // by the frame pointer.
980 // Let eliminateCallFramePseudoInstr preserve stack space for it.
981 bool RISCVFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
982   return !MF.getFrameInfo().hasVarSizedObjects() &&
983          !(hasFP(MF) && hasRVVFrameObject(MF));
984 }
985 
986 // Eliminate ADJCALLSTACKDOWN, ADJCALLSTACKUP pseudo instructions.
987 MachineBasicBlock::iterator RISCVFrameLowering::eliminateCallFramePseudoInstr(
988     MachineFunction &MF, MachineBasicBlock &MBB,
989     MachineBasicBlock::iterator MI) const {
990   Register SPReg = RISCV::X2;
991   DebugLoc DL = MI->getDebugLoc();
992 
993   if (!hasReservedCallFrame(MF)) {
994     // If space has not been reserved for a call frame, ADJCALLSTACKDOWN and
995     // ADJCALLSTACKUP must be converted to instructions manipulating the stack
996     // pointer. This is necessary when there is a variable length stack
997     // allocation (e.g. alloca), which means it's not possible to allocate
998     // space for outgoing arguments from within the function prologue.
999     int64_t Amount = MI->getOperand(0).getImm();
1000 
1001     if (Amount != 0) {
1002       // Ensure the stack remains aligned after adjustment.
1003       Amount = alignSPAdjust(Amount);
1004 
1005       if (MI->getOpcode() == RISCV::ADJCALLSTACKDOWN)
1006         Amount = -Amount;
1007 
1008       adjustReg(MBB, MI, DL, SPReg, SPReg, Amount, MachineInstr::NoFlags);
1009     }
1010   }
1011 
1012   return MBB.erase(MI);
1013 }
1014 
1015 // We would like to split the SP adjustment to reduce prologue/epilogue
1016 // as following instructions. In this way, the offset of the callee saved
1017 // register could fit in a single store.
1018 //   add     sp,sp,-2032
1019 //   sw      ra,2028(sp)
1020 //   sw      s0,2024(sp)
1021 //   sw      s1,2020(sp)
1022 //   sw      s3,2012(sp)
1023 //   sw      s4,2008(sp)
1024 //   add     sp,sp,-64
1025 uint64_t
1026 RISCVFrameLowering::getFirstSPAdjustAmount(const MachineFunction &MF) const {
1027   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1028   const MachineFrameInfo &MFI = MF.getFrameInfo();
1029   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
1030   uint64_t StackSize = MFI.getStackSize();
1031 
1032   // Disable SplitSPAdjust if save-restore libcall used. The callee saved
1033   // registers will be pushed by the save-restore libcalls, so we don't have to
1034   // split the SP adjustment in this case.
1035   if (RVFI->getLibCallStackSize())
1036     return 0;
1037 
1038   // Return the FirstSPAdjustAmount if the StackSize can not fit in signed
1039   // 12-bit and there exists a callee saved register need to be pushed.
1040   if (!isInt<12>(StackSize) && (CSI.size() > 0)) {
1041     // FirstSPAdjustAmount is choosed as (2048 - StackAlign)
1042     // because 2048 will cause sp = sp + 2048 in epilogue split into
1043     // multi-instructions. The offset smaller than 2048 can fit in signle
1044     // load/store instruction and we have to stick with the stack alignment.
1045     // 2048 is 16-byte alignment. The stack alignment for RV32 and RV64 is 16,
1046     // for RV32E is 4. So (2048 - StackAlign) will satisfy the stack alignment.
1047     return 2048 - getStackAlign().value();
1048   }
1049   return 0;
1050 }
1051 
1052 bool RISCVFrameLowering::spillCalleeSavedRegisters(
1053     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1054     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
1055   if (CSI.empty())
1056     return true;
1057 
1058   MachineFunction *MF = MBB.getParent();
1059   const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
1060   DebugLoc DL;
1061   if (MI != MBB.end() && !MI->isDebugInstr())
1062     DL = MI->getDebugLoc();
1063 
1064   const char *SpillLibCall = getSpillLibCallName(*MF, CSI);
1065   if (SpillLibCall) {
1066     // Add spill libcall via non-callee-saved register t0.
1067     BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoCALLReg), RISCV::X5)
1068         .addExternalSymbol(SpillLibCall, RISCVII::MO_CALL)
1069         .setMIFlag(MachineInstr::FrameSetup);
1070 
1071     // Add registers spilled in libcall as liveins.
1072     for (auto &CS : CSI)
1073       MBB.addLiveIn(CS.getReg());
1074   }
1075 
1076   // Manually spill values not spilled by libcall.
1077   const auto &NonLibcallCSI = getNonLibcallCSI(*MF, CSI);
1078   for (auto &CS : NonLibcallCSI) {
1079     // Insert the spill to the stack frame.
1080     Register Reg = CS.getReg();
1081     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1082     TII.storeRegToStackSlot(MBB, MI, Reg, !MBB.isLiveIn(Reg), CS.getFrameIdx(),
1083                             RC, TRI);
1084   }
1085 
1086   return true;
1087 }
1088 
1089 bool RISCVFrameLowering::restoreCalleeSavedRegisters(
1090     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1091     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
1092   if (CSI.empty())
1093     return true;
1094 
1095   MachineFunction *MF = MBB.getParent();
1096   const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
1097   DebugLoc DL;
1098   if (MI != MBB.end() && !MI->isDebugInstr())
1099     DL = MI->getDebugLoc();
1100 
1101   // Manually restore values not restored by libcall.
1102   // Keep the same order as in the prologue. There is no need to reverse the
1103   // order in the epilogue. In addition, the return address will be restored
1104   // first in the epilogue. It increases the opportunity to avoid the
1105   // load-to-use data hazard between loading RA and return by RA.
1106   // loadRegFromStackSlot can insert multiple instructions.
1107   const auto &NonLibcallCSI = getNonLibcallCSI(*MF, CSI);
1108   for (auto &CS : NonLibcallCSI) {
1109     Register Reg = CS.getReg();
1110     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1111     TII.loadRegFromStackSlot(MBB, MI, Reg, CS.getFrameIdx(), RC, TRI);
1112     assert(MI != MBB.begin() && "loadRegFromStackSlot didn't insert any code!");
1113   }
1114 
1115   const char *RestoreLibCall = getRestoreLibCallName(*MF, CSI);
1116   if (RestoreLibCall) {
1117     // Add restore libcall via tail call.
1118     MachineBasicBlock::iterator NewMI =
1119         BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoTAIL))
1120             .addExternalSymbol(RestoreLibCall, RISCVII::MO_CALL)
1121             .setMIFlag(MachineInstr::FrameDestroy);
1122 
1123     // Remove trailing returns, since the terminator is now a tail call to the
1124     // restore function.
1125     if (MI != MBB.end() && MI->getOpcode() == RISCV::PseudoRET) {
1126       NewMI->copyImplicitOps(*MF, *MI);
1127       MI->eraseFromParent();
1128     }
1129   }
1130 
1131   return true;
1132 }
1133 
1134 bool RISCVFrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const {
1135   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
1136   const MachineFunction *MF = MBB.getParent();
1137   const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
1138 
1139   if (!RVFI->useSaveRestoreLibCalls(*MF))
1140     return true;
1141 
1142   // Inserting a call to a __riscv_save libcall requires the use of the register
1143   // t0 (X5) to hold the return address. Therefore if this register is already
1144   // used we can't insert the call.
1145 
1146   RegScavenger RS;
1147   RS.enterBasicBlock(*TmpMBB);
1148   return !RS.isRegUsed(RISCV::X5);
1149 }
1150 
1151 bool RISCVFrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
1152   const MachineFunction *MF = MBB.getParent();
1153   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
1154   const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
1155 
1156   if (!RVFI->useSaveRestoreLibCalls(*MF))
1157     return true;
1158 
1159   // Using the __riscv_restore libcalls to restore CSRs requires a tail call.
1160   // This means if we still need to continue executing code within this function
1161   // the restore cannot take place in this basic block.
1162 
1163   if (MBB.succ_size() > 1)
1164     return false;
1165 
1166   MachineBasicBlock *SuccMBB =
1167       MBB.succ_empty() ? TmpMBB->getFallThrough() : *MBB.succ_begin();
1168 
1169   // Doing a tail call should be safe if there are no successors, because either
1170   // we have a returning block or the end of the block is unreachable, so the
1171   // restore will be eliminated regardless.
1172   if (!SuccMBB)
1173     return true;
1174 
1175   // The successor can only contain a return, since we would effectively be
1176   // replacing the successor with our own tail return at the end of our block.
1177   return SuccMBB->isReturnBlock() && SuccMBB->size() == 1;
1178 }
1179 
1180 bool RISCVFrameLowering::isSupportedStackID(TargetStackID::Value ID) const {
1181   switch (ID) {
1182   case TargetStackID::Default:
1183   case TargetStackID::ScalableVector:
1184     return true;
1185   case TargetStackID::NoAlloc:
1186   case TargetStackID::SGPRSpill:
1187   case TargetStackID::WasmLocal:
1188     return false;
1189   }
1190   llvm_unreachable("Invalid TargetStackID::Value");
1191 }
1192 
1193 TargetStackID::Value RISCVFrameLowering::getStackIDForScalableVectors() const {
1194   return TargetStackID::ScalableVector;
1195 }
1196