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