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