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