xref: /freebsd/contrib/llvm-project/llvm/lib/Target/RISCV/RISCVFrameLowering.cpp (revision 77013d11e6483b970af25e13c9b892075742f7e5)
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   // Set Max Call Frame Size
246   uint64_t MaxCallSize = alignTo(MFI.getMaxCallFrameSize(), StackAlign);
247   MFI.setMaxCallFrameSize(MaxCallSize);
248 
249   // Make sure the frame is aligned.
250   FrameSize = alignTo(FrameSize, StackAlign);
251 
252   // Update frame info.
253   MFI.setStackSize(FrameSize);
254 }
255 
256 void RISCVFrameLowering::adjustReg(MachineBasicBlock &MBB,
257                                    MachineBasicBlock::iterator MBBI,
258                                    const DebugLoc &DL, Register DestReg,
259                                    Register SrcReg, int64_t Val,
260                                    MachineInstr::MIFlag Flag) const {
261   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
262   const RISCVInstrInfo *TII = STI.getInstrInfo();
263 
264   if (DestReg == SrcReg && Val == 0)
265     return;
266 
267   if (isInt<12>(Val)) {
268     BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), DestReg)
269         .addReg(SrcReg)
270         .addImm(Val)
271         .setMIFlag(Flag);
272   } else {
273     unsigned Opc = RISCV::ADD;
274     bool isSub = Val < 0;
275     if (isSub) {
276       Val = -Val;
277       Opc = RISCV::SUB;
278     }
279 
280     Register ScratchReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
281     TII->movImm(MBB, MBBI, DL, ScratchReg, Val, Flag);
282     BuildMI(MBB, MBBI, DL, TII->get(Opc), DestReg)
283         .addReg(SrcReg)
284         .addReg(ScratchReg, RegState::Kill)
285         .setMIFlag(Flag);
286   }
287 }
288 
289 // Returns the register used to hold the frame pointer.
290 static Register getFPReg(const RISCVSubtarget &STI) { return RISCV::X8; }
291 
292 // Returns the register used to hold the stack pointer.
293 static Register getSPReg(const RISCVSubtarget &STI) { return RISCV::X2; }
294 
295 static SmallVector<CalleeSavedInfo, 8>
296 getNonLibcallCSI(const std::vector<CalleeSavedInfo> &CSI) {
297   SmallVector<CalleeSavedInfo, 8> NonLibcallCSI;
298 
299   for (auto &CS : CSI)
300     if (CS.getFrameIdx() >= 0)
301       NonLibcallCSI.push_back(CS);
302 
303   return NonLibcallCSI;
304 }
305 
306 void RISCVFrameLowering::emitPrologue(MachineFunction &MF,
307                                       MachineBasicBlock &MBB) const {
308   MachineFrameInfo &MFI = MF.getFrameInfo();
309   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
310   const RISCVRegisterInfo *RI = STI.getRegisterInfo();
311   const RISCVInstrInfo *TII = STI.getInstrInfo();
312   MachineBasicBlock::iterator MBBI = MBB.begin();
313 
314   Register FPReg = getFPReg(STI);
315   Register SPReg = getSPReg(STI);
316   Register BPReg = RISCVABI::getBPReg();
317 
318   // Debug location must be unknown since the first debug location is used
319   // to determine the end of the prologue.
320   DebugLoc DL;
321 
322   // All calls are tail calls in GHC calling conv, and functions have no
323   // prologue/epilogue.
324   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
325     return;
326 
327   // Emit prologue for shadow call stack.
328   emitSCSPrologue(MF, MBB, MBBI, DL);
329 
330   // Since spillCalleeSavedRegisters may have inserted a libcall, skip past
331   // any instructions marked as FrameSetup
332   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
333     ++MBBI;
334 
335   // Determine the correct frame layout
336   determineFrameLayout(MF);
337 
338   // If libcalls are used to spill and restore callee-saved registers, the frame
339   // has two sections; the opaque section managed by the libcalls, and the
340   // section managed by MachineFrameInfo which can also hold callee saved
341   // registers in fixed stack slots, both of which have negative frame indices.
342   // This gets even more complicated when incoming arguments are passed via the
343   // stack, as these too have negative frame indices. An example is detailed
344   // below:
345   //
346   //  | incoming arg | <- FI[-3]
347   //  | libcallspill |
348   //  | calleespill  | <- FI[-2]
349   //  | calleespill  | <- FI[-1]
350   //  | this_frame   | <- FI[0]
351   //
352   // For negative frame indices, the offset from the frame pointer will differ
353   // depending on which of these groups the frame index applies to.
354   // The following calculates the correct offset knowing the number of callee
355   // saved registers spilt by the two methods.
356   if (int LibCallRegs = getLibCallID(MF, MFI.getCalleeSavedInfo()) + 1) {
357     // Calculate the size of the frame managed by the libcall. The libcalls are
358     // implemented such that the stack will always be 16 byte aligned.
359     unsigned LibCallFrameSize = alignTo((STI.getXLen() / 8) * LibCallRegs, 16);
360     RVFI->setLibCallStackSize(LibCallFrameSize);
361   }
362 
363   // FIXME (note copied from Lanai): This appears to be overallocating.  Needs
364   // investigation. Get the number of bytes to allocate from the FrameInfo.
365   uint64_t StackSize = MFI.getStackSize();
366   uint64_t RealStackSize = StackSize + RVFI->getLibCallStackSize();
367 
368   // Early exit if there is no need to allocate on the stack
369   if (RealStackSize == 0 && !MFI.adjustsStack())
370     return;
371 
372   // If the stack pointer has been marked as reserved, then produce an error if
373   // the frame requires stack allocation
374   if (STI.isRegisterReservedByUser(SPReg))
375     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
376         MF.getFunction(), "Stack pointer required, but has been reserved."});
377 
378   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
379   // Split the SP adjustment to reduce the offsets of callee saved spill.
380   if (FirstSPAdjustAmount) {
381     StackSize = FirstSPAdjustAmount;
382     RealStackSize = FirstSPAdjustAmount;
383   }
384 
385   // Allocate space on the stack if necessary.
386   adjustReg(MBB, MBBI, DL, SPReg, SPReg, -StackSize, MachineInstr::FrameSetup);
387 
388   // Emit ".cfi_def_cfa_offset RealStackSize"
389   unsigned CFIIndex = MF.addFrameInst(
390       MCCFIInstruction::cfiDefCfaOffset(nullptr, RealStackSize));
391   BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
392       .addCFIIndex(CFIIndex);
393 
394   const auto &CSI = MFI.getCalleeSavedInfo();
395 
396   // The frame pointer is callee-saved, and code has been generated for us to
397   // save it to the stack. We need to skip over the storing of callee-saved
398   // registers as the frame pointer must be modified after it has been saved
399   // to the stack, not before.
400   // FIXME: assumes exactly one instruction is used to save each callee-saved
401   // register.
402   std::advance(MBBI, getNonLibcallCSI(CSI).size());
403 
404   // Iterate over list of callee-saved registers and emit .cfi_offset
405   // directives.
406   for (const auto &Entry : CSI) {
407     int FrameIdx = Entry.getFrameIdx();
408     int64_t Offset;
409     // Offsets for objects with fixed locations (IE: those saved by libcall) are
410     // simply calculated from the frame index.
411     if (FrameIdx < 0)
412       Offset = FrameIdx * (int64_t) STI.getXLen() / 8;
413     else
414       Offset = MFI.getObjectOffset(Entry.getFrameIdx()) -
415                RVFI->getLibCallStackSize();
416     Register Reg = Entry.getReg();
417     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
418         nullptr, RI->getDwarfRegNum(Reg, true), Offset));
419     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
420         .addCFIIndex(CFIIndex);
421   }
422 
423   // Generate new FP.
424   if (hasFP(MF)) {
425     if (STI.isRegisterReservedByUser(FPReg))
426       MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
427           MF.getFunction(), "Frame pointer required, but has been reserved."});
428 
429     adjustReg(MBB, MBBI, DL, FPReg, SPReg,
430               RealStackSize - RVFI->getVarArgsSaveSize(),
431               MachineInstr::FrameSetup);
432 
433     // Emit ".cfi_def_cfa $fp, RVFI->getVarArgsSaveSize()"
434     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(
435         nullptr, RI->getDwarfRegNum(FPReg, true), RVFI->getVarArgsSaveSize()));
436     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
437         .addCFIIndex(CFIIndex);
438   }
439 
440   // Emit the second SP adjustment after saving callee saved registers.
441   if (FirstSPAdjustAmount) {
442     uint64_t SecondSPAdjustAmount = MFI.getStackSize() - FirstSPAdjustAmount;
443     assert(SecondSPAdjustAmount > 0 &&
444            "SecondSPAdjustAmount should be greater than zero");
445     adjustReg(MBB, MBBI, DL, SPReg, SPReg, -SecondSPAdjustAmount,
446               MachineInstr::FrameSetup);
447 
448     // If we are using a frame-pointer, and thus emitted ".cfi_def_cfa fp, 0",
449     // don't emit an sp-based .cfi_def_cfa_offset
450     if (!hasFP(MF)) {
451       // Emit ".cfi_def_cfa_offset StackSize"
452       unsigned CFIIndex = MF.addFrameInst(
453           MCCFIInstruction::cfiDefCfaOffset(nullptr, MFI.getStackSize()));
454       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
455           .addCFIIndex(CFIIndex);
456     }
457   }
458 
459   if (hasFP(MF)) {
460     // Realign Stack
461     const RISCVRegisterInfo *RI = STI.getRegisterInfo();
462     if (RI->needsStackRealignment(MF)) {
463       Align MaxAlignment = MFI.getMaxAlign();
464 
465       const RISCVInstrInfo *TII = STI.getInstrInfo();
466       if (isInt<12>(-(int)MaxAlignment.value())) {
467         BuildMI(MBB, MBBI, DL, TII->get(RISCV::ANDI), SPReg)
468             .addReg(SPReg)
469             .addImm(-(int)MaxAlignment.value());
470       } else {
471         unsigned ShiftAmount = Log2(MaxAlignment);
472         Register VR =
473             MF.getRegInfo().createVirtualRegister(&RISCV::GPRRegClass);
474         BuildMI(MBB, MBBI, DL, TII->get(RISCV::SRLI), VR)
475             .addReg(SPReg)
476             .addImm(ShiftAmount);
477         BuildMI(MBB, MBBI, DL, TII->get(RISCV::SLLI), SPReg)
478             .addReg(VR)
479             .addImm(ShiftAmount);
480       }
481       // FP will be used to restore the frame in the epilogue, so we need
482       // another base register BP to record SP after re-alignment. SP will
483       // track the current stack after allocating variable sized objects.
484       if (hasBP(MF)) {
485         // move BP, SP
486         BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), BPReg)
487             .addReg(SPReg)
488             .addImm(0);
489       }
490     }
491   }
492 }
493 
494 void RISCVFrameLowering::emitEpilogue(MachineFunction &MF,
495                                       MachineBasicBlock &MBB) const {
496   const RISCVRegisterInfo *RI = STI.getRegisterInfo();
497   MachineFrameInfo &MFI = MF.getFrameInfo();
498   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
499   Register FPReg = getFPReg(STI);
500   Register SPReg = getSPReg(STI);
501 
502   // All calls are tail calls in GHC calling conv, and functions have no
503   // prologue/epilogue.
504   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
505     return;
506 
507   // Get the insert location for the epilogue. If there were no terminators in
508   // the block, get the last instruction.
509   MachineBasicBlock::iterator MBBI = MBB.end();
510   DebugLoc DL;
511   if (!MBB.empty()) {
512     MBBI = MBB.getFirstTerminator();
513     if (MBBI == MBB.end())
514       MBBI = MBB.getLastNonDebugInstr();
515     DL = MBBI->getDebugLoc();
516 
517     // If this is not a terminator, the actual insert location should be after the
518     // last instruction.
519     if (!MBBI->isTerminator())
520       MBBI = std::next(MBBI);
521 
522     // If callee-saved registers are saved via libcall, place stack adjustment
523     // before this call.
524     while (MBBI != MBB.begin() &&
525            std::prev(MBBI)->getFlag(MachineInstr::FrameDestroy))
526       --MBBI;
527   }
528 
529   const auto &CSI = getNonLibcallCSI(MFI.getCalleeSavedInfo());
530 
531   // Skip to before the restores of callee-saved registers
532   // FIXME: assumes exactly one instruction is used to restore each
533   // callee-saved register.
534   auto LastFrameDestroy = MBBI;
535   if (!CSI.empty())
536     LastFrameDestroy = std::prev(MBBI, CSI.size());
537 
538   uint64_t StackSize = MFI.getStackSize();
539   uint64_t RealStackSize = StackSize + RVFI->getLibCallStackSize();
540   uint64_t FPOffset = RealStackSize - RVFI->getVarArgsSaveSize();
541 
542   // Restore the stack pointer using the value of the frame pointer. Only
543   // necessary if the stack pointer was modified, meaning the stack size is
544   // unknown.
545   if (RI->needsStackRealignment(MF) || MFI.hasVarSizedObjects()) {
546     assert(hasFP(MF) && "frame pointer should not have been eliminated");
547     adjustReg(MBB, LastFrameDestroy, DL, SPReg, FPReg, -FPOffset,
548               MachineInstr::FrameDestroy);
549   }
550 
551   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
552   if (FirstSPAdjustAmount) {
553     uint64_t SecondSPAdjustAmount = MFI.getStackSize() - FirstSPAdjustAmount;
554     assert(SecondSPAdjustAmount > 0 &&
555            "SecondSPAdjustAmount should be greater than zero");
556 
557     adjustReg(MBB, LastFrameDestroy, DL, SPReg, SPReg, SecondSPAdjustAmount,
558               MachineInstr::FrameDestroy);
559   }
560 
561   if (FirstSPAdjustAmount)
562     StackSize = FirstSPAdjustAmount;
563 
564   // Deallocate stack
565   adjustReg(MBB, MBBI, DL, SPReg, SPReg, StackSize, MachineInstr::FrameDestroy);
566 
567   // Emit epilogue for shadow call stack.
568   emitSCSEpilogue(MF, MBB, MBBI, DL);
569 }
570 
571 StackOffset
572 RISCVFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
573                                            Register &FrameReg) const {
574   const MachineFrameInfo &MFI = MF.getFrameInfo();
575   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
576   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
577 
578   // Callee-saved registers should be referenced relative to the stack
579   // pointer (positive offset), otherwise use the frame pointer (negative
580   // offset).
581   const auto &CSI = getNonLibcallCSI(MFI.getCalleeSavedInfo());
582   int MinCSFI = 0;
583   int MaxCSFI = -1;
584 
585   int Offset = MFI.getObjectOffset(FI) - getOffsetOfLocalArea() +
586                MFI.getOffsetAdjustment();
587 
588   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
589 
590   if (CSI.size()) {
591     MinCSFI = CSI[0].getFrameIdx();
592     MaxCSFI = CSI[CSI.size() - 1].getFrameIdx();
593   }
594 
595   if (FI >= MinCSFI && FI <= MaxCSFI) {
596     FrameReg = RISCV::X2;
597 
598     if (FirstSPAdjustAmount)
599       Offset += FirstSPAdjustAmount;
600     else
601       Offset += MFI.getStackSize();
602   } else if (RI->needsStackRealignment(MF) && !MFI.isFixedObjectIndex(FI)) {
603     // If the stack was realigned, the frame pointer is set in order to allow
604     // SP to be restored, so we need another base register to record the stack
605     // after realignment.
606     if (hasBP(MF))
607       FrameReg = RISCVABI::getBPReg();
608     else
609       FrameReg = RISCV::X2;
610     Offset += MFI.getStackSize();
611     if (FI < 0)
612       Offset += RVFI->getLibCallStackSize();
613   } else {
614     FrameReg = RI->getFrameRegister(MF);
615     if (hasFP(MF)) {
616       Offset += RVFI->getVarArgsSaveSize();
617       if (FI >= 0)
618         Offset -= RVFI->getLibCallStackSize();
619     } else {
620       Offset += MFI.getStackSize();
621       if (FI < 0)
622         Offset += RVFI->getLibCallStackSize();
623     }
624   }
625   return StackOffset::getFixed(Offset);
626 }
627 
628 void RISCVFrameLowering::determineCalleeSaves(MachineFunction &MF,
629                                               BitVector &SavedRegs,
630                                               RegScavenger *RS) const {
631   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
632   // Unconditionally spill RA and FP only if the function uses a frame
633   // pointer.
634   if (hasFP(MF)) {
635     SavedRegs.set(RISCV::X1);
636     SavedRegs.set(RISCV::X8);
637   }
638   // Mark BP as used if function has dedicated base pointer.
639   if (hasBP(MF))
640     SavedRegs.set(RISCVABI::getBPReg());
641 
642   // If interrupt is enabled and there are calls in the handler,
643   // unconditionally save all Caller-saved registers and
644   // all FP registers, regardless whether they are used.
645   MachineFrameInfo &MFI = MF.getFrameInfo();
646 
647   if (MF.getFunction().hasFnAttribute("interrupt") && MFI.hasCalls()) {
648 
649     static const MCPhysReg CSRegs[] = { RISCV::X1,      /* ra */
650       RISCV::X5, RISCV::X6, RISCV::X7,                  /* t0-t2 */
651       RISCV::X10, RISCV::X11,                           /* a0-a1, a2-a7 */
652       RISCV::X12, RISCV::X13, RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17,
653       RISCV::X28, RISCV::X29, RISCV::X30, RISCV::X31, 0 /* t3-t6 */
654     };
655 
656     for (unsigned i = 0; CSRegs[i]; ++i)
657       SavedRegs.set(CSRegs[i]);
658 
659     if (MF.getSubtarget<RISCVSubtarget>().hasStdExtF()) {
660 
661       // If interrupt is enabled, this list contains all FP registers.
662       const MCPhysReg * Regs = MF.getRegInfo().getCalleeSavedRegs();
663 
664       for (unsigned i = 0; Regs[i]; ++i)
665         if (RISCV::FPR16RegClass.contains(Regs[i]) ||
666             RISCV::FPR32RegClass.contains(Regs[i]) ||
667             RISCV::FPR64RegClass.contains(Regs[i]))
668           SavedRegs.set(Regs[i]);
669     }
670   }
671 }
672 
673 void RISCVFrameLowering::processFunctionBeforeFrameFinalized(
674     MachineFunction &MF, RegScavenger *RS) const {
675   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
676   MachineFrameInfo &MFI = MF.getFrameInfo();
677   const TargetRegisterClass *RC = &RISCV::GPRRegClass;
678   // estimateStackSize has been observed to under-estimate the final stack
679   // size, so give ourselves wiggle-room by checking for stack size
680   // representable an 11-bit signed field rather than 12-bits.
681   // FIXME: It may be possible to craft a function with a small stack that
682   // still needs an emergency spill slot for branch relaxation. This case
683   // would currently be missed.
684   if (!isInt<11>(MFI.estimateStackSize(MF))) {
685     int RegScavFI = MFI.CreateStackObject(RegInfo->getSpillSize(*RC),
686                                           RegInfo->getSpillAlign(*RC), false);
687     RS->addScavengingFrameIndex(RegScavFI);
688   }
689 }
690 
691 // Not preserve stack space within prologue for outgoing variables when the
692 // function contains variable size objects and let eliminateCallFramePseudoInstr
693 // preserve stack space for it.
694 bool RISCVFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
695   return !MF.getFrameInfo().hasVarSizedObjects();
696 }
697 
698 // Eliminate ADJCALLSTACKDOWN, ADJCALLSTACKUP pseudo instructions.
699 MachineBasicBlock::iterator RISCVFrameLowering::eliminateCallFramePseudoInstr(
700     MachineFunction &MF, MachineBasicBlock &MBB,
701     MachineBasicBlock::iterator MI) const {
702   Register SPReg = RISCV::X2;
703   DebugLoc DL = MI->getDebugLoc();
704 
705   if (!hasReservedCallFrame(MF)) {
706     // If space has not been reserved for a call frame, ADJCALLSTACKDOWN and
707     // ADJCALLSTACKUP must be converted to instructions manipulating the stack
708     // pointer. This is necessary when there is a variable length stack
709     // allocation (e.g. alloca), which means it's not possible to allocate
710     // space for outgoing arguments from within the function prologue.
711     int64_t Amount = MI->getOperand(0).getImm();
712 
713     if (Amount != 0) {
714       // Ensure the stack remains aligned after adjustment.
715       Amount = alignSPAdjust(Amount);
716 
717       if (MI->getOpcode() == RISCV::ADJCALLSTACKDOWN)
718         Amount = -Amount;
719 
720       adjustReg(MBB, MI, DL, SPReg, SPReg, Amount, MachineInstr::NoFlags);
721     }
722   }
723 
724   return MBB.erase(MI);
725 }
726 
727 // We would like to split the SP adjustment to reduce prologue/epilogue
728 // as following instructions. In this way, the offset of the callee saved
729 // register could fit in a single store.
730 //   add     sp,sp,-2032
731 //   sw      ra,2028(sp)
732 //   sw      s0,2024(sp)
733 //   sw      s1,2020(sp)
734 //   sw      s3,2012(sp)
735 //   sw      s4,2008(sp)
736 //   add     sp,sp,-64
737 uint64_t
738 RISCVFrameLowering::getFirstSPAdjustAmount(const MachineFunction &MF) const {
739   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
740   const MachineFrameInfo &MFI = MF.getFrameInfo();
741   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
742   uint64_t StackSize = MFI.getStackSize();
743 
744   // Disable SplitSPAdjust if save-restore libcall used. The callee saved
745   // registers will be pushed by the save-restore libcalls, so we don't have to
746   // split the SP adjustment in this case.
747   if (RVFI->getLibCallStackSize())
748     return 0;
749 
750   // Return the FirstSPAdjustAmount if the StackSize can not fit in signed
751   // 12-bit and there exists a callee saved register need to be pushed.
752   if (!isInt<12>(StackSize) && (CSI.size() > 0)) {
753     // FirstSPAdjustAmount is choosed as (2048 - StackAlign)
754     // because 2048 will cause sp = sp + 2048 in epilogue split into
755     // multi-instructions. The offset smaller than 2048 can fit in signle
756     // load/store instruction and we have to stick with the stack alignment.
757     // 2048 is 16-byte alignment. The stack alignment for RV32 and RV64 is 16,
758     // for RV32E is 4. So (2048 - StackAlign) will satisfy the stack alignment.
759     return 2048 - getStackAlign().value();
760   }
761   return 0;
762 }
763 
764 bool RISCVFrameLowering::spillCalleeSavedRegisters(
765     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
766     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
767   if (CSI.empty())
768     return true;
769 
770   MachineFunction *MF = MBB.getParent();
771   const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
772   DebugLoc DL;
773   if (MI != MBB.end() && !MI->isDebugInstr())
774     DL = MI->getDebugLoc();
775 
776   const char *SpillLibCall = getSpillLibCallName(*MF, CSI);
777   if (SpillLibCall) {
778     // Add spill libcall via non-callee-saved register t0.
779     BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoCALLReg), RISCV::X5)
780         .addExternalSymbol(SpillLibCall, RISCVII::MO_CALL)
781         .setMIFlag(MachineInstr::FrameSetup);
782 
783     // Add registers spilled in libcall as liveins.
784     for (auto &CS : CSI)
785       MBB.addLiveIn(CS.getReg());
786   }
787 
788   // Manually spill values not spilled by libcall.
789   const auto &NonLibcallCSI = getNonLibcallCSI(CSI);
790   for (auto &CS : NonLibcallCSI) {
791     // Insert the spill to the stack frame.
792     Register Reg = CS.getReg();
793     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
794     TII.storeRegToStackSlot(MBB, MI, Reg, true, CS.getFrameIdx(), RC, TRI);
795   }
796 
797   return true;
798 }
799 
800 bool RISCVFrameLowering::restoreCalleeSavedRegisters(
801     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
802     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
803   if (CSI.empty())
804     return true;
805 
806   MachineFunction *MF = MBB.getParent();
807   const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
808   DebugLoc DL;
809   if (MI != MBB.end() && !MI->isDebugInstr())
810     DL = MI->getDebugLoc();
811 
812   // Manually restore values not restored by libcall. Insert in reverse order.
813   // loadRegFromStackSlot can insert multiple instructions.
814   const auto &NonLibcallCSI = getNonLibcallCSI(CSI);
815   for (auto &CS : reverse(NonLibcallCSI)) {
816     Register Reg = CS.getReg();
817     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
818     TII.loadRegFromStackSlot(MBB, MI, Reg, CS.getFrameIdx(), RC, TRI);
819     assert(MI != MBB.begin() && "loadRegFromStackSlot didn't insert any code!");
820   }
821 
822   const char *RestoreLibCall = getRestoreLibCallName(*MF, CSI);
823   if (RestoreLibCall) {
824     // Add restore libcall via tail call.
825     MachineBasicBlock::iterator NewMI =
826         BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoTAIL))
827             .addExternalSymbol(RestoreLibCall, RISCVII::MO_CALL)
828             .setMIFlag(MachineInstr::FrameDestroy);
829 
830     // Remove trailing returns, since the terminator is now a tail call to the
831     // restore function.
832     if (MI != MBB.end() && MI->getOpcode() == RISCV::PseudoRET) {
833       NewMI->copyImplicitOps(*MF, *MI);
834       MI->eraseFromParent();
835     }
836   }
837 
838   return true;
839 }
840 
841 bool RISCVFrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const {
842   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
843   const MachineFunction *MF = MBB.getParent();
844   const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
845 
846   if (!RVFI->useSaveRestoreLibCalls(*MF))
847     return true;
848 
849   // Inserting a call to a __riscv_save libcall requires the use of the register
850   // t0 (X5) to hold the return address. Therefore if this register is already
851   // used we can't insert the call.
852 
853   RegScavenger RS;
854   RS.enterBasicBlock(*TmpMBB);
855   return !RS.isRegUsed(RISCV::X5);
856 }
857 
858 bool RISCVFrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
859   const MachineFunction *MF = MBB.getParent();
860   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
861   const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
862 
863   if (!RVFI->useSaveRestoreLibCalls(*MF))
864     return true;
865 
866   // Using the __riscv_restore libcalls to restore CSRs requires a tail call.
867   // This means if we still need to continue executing code within this function
868   // the restore cannot take place in this basic block.
869 
870   if (MBB.succ_size() > 1)
871     return false;
872 
873   MachineBasicBlock *SuccMBB =
874       MBB.succ_empty() ? TmpMBB->getFallThrough() : *MBB.succ_begin();
875 
876   // Doing a tail call should be safe if there are no successors, because either
877   // we have a returning block or the end of the block is unreachable, so the
878   // restore will be eliminated regardless.
879   if (!SuccMBB)
880     return true;
881 
882   // The successor can only contain a return, since we would effectively be
883   // replacing the successor with our own tail return at the end of our block.
884   return SuccMBB->isReturnBlock() && SuccMBB->size() == 1;
885 }
886