18971842fSAlex Bradbury //===-- RISCVFrameLowering.cpp - RISCV Frame Information ------------------===//
28971842fSAlex Bradbury //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
68971842fSAlex Bradbury //
78971842fSAlex Bradbury //===----------------------------------------------------------------------===//
88971842fSAlex Bradbury //
98971842fSAlex Bradbury // This file contains the RISCV implementation of TargetFrameLowering class.
108971842fSAlex Bradbury //
118971842fSAlex Bradbury //===----------------------------------------------------------------------===//
128971842fSAlex Bradbury 
138971842fSAlex Bradbury #include "RISCVFrameLowering.h"
14c85be0deSAlex Bradbury #include "RISCVMachineFunctionInfo.h"
158971842fSAlex Bradbury #include "RISCVSubtarget.h"
168971842fSAlex Bradbury #include "llvm/CodeGen/MachineFrameInfo.h"
178971842fSAlex Bradbury #include "llvm/CodeGen/MachineFunction.h"
188971842fSAlex Bradbury #include "llvm/CodeGen/MachineInstrBuilder.h"
198971842fSAlex Bradbury #include "llvm/CodeGen/MachineRegisterInfo.h"
200715d35eSAlex Bradbury #include "llvm/CodeGen/RegisterScavenging.h"
21aed9d6d6SSimon Cook #include "llvm/IR/DiagnosticInfo.h"
2204ddf39bSHsiangkai Wang #include "llvm/MC/MCDwarf.h"
238971842fSAlex Bradbury 
248971842fSAlex Bradbury using namespace llvm;
258971842fSAlex Bradbury 
2607f7c002Slewis-revill // Get the ID of the libcall used for spilling and restoring callee saved
2707f7c002Slewis-revill // registers. The ID is representative of the number of registers saved or
2807f7c002Slewis-revill // restored by the libcall, except it is zero-indexed - ID 0 corresponds to a
2907f7c002Slewis-revill // single register.
3007f7c002Slewis-revill static int getLibCallID(const MachineFunction &MF,
3107f7c002Slewis-revill                         const std::vector<CalleeSavedInfo> &CSI) {
3207f7c002Slewis-revill   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
3307f7c002Slewis-revill 
3407f7c002Slewis-revill   if (CSI.empty() || !RVFI->useSaveRestoreLibCalls())
3507f7c002Slewis-revill     return -1;
3607f7c002Slewis-revill 
3707f7c002Slewis-revill   Register MaxReg = RISCV::NoRegister;
3807f7c002Slewis-revill   for (auto &CS : CSI)
3907f7c002Slewis-revill     // RISCVRegisterInfo::hasReservedSpillSlot assigns negative frame indexes to
4007f7c002Slewis-revill     // registers which can be saved by libcall.
4107f7c002Slewis-revill     if (CS.getFrameIdx() < 0)
4207f7c002Slewis-revill       MaxReg = std::max(MaxReg.id(), CS.getReg());
4307f7c002Slewis-revill 
4407f7c002Slewis-revill   if (MaxReg == RISCV::NoRegister)
4507f7c002Slewis-revill     return -1;
4607f7c002Slewis-revill 
4707f7c002Slewis-revill   switch (MaxReg) {
4807f7c002Slewis-revill   default:
4907f7c002Slewis-revill     llvm_unreachable("Something has gone wrong!");
5007f7c002Slewis-revill   case /*s11*/ RISCV::X27: return 12;
5107f7c002Slewis-revill   case /*s10*/ RISCV::X26: return 11;
5207f7c002Slewis-revill   case /*s9*/  RISCV::X25: return 10;
5307f7c002Slewis-revill   case /*s8*/  RISCV::X24: return 9;
5407f7c002Slewis-revill   case /*s7*/  RISCV::X23: return 8;
5507f7c002Slewis-revill   case /*s6*/  RISCV::X22: return 7;
5607f7c002Slewis-revill   case /*s5*/  RISCV::X21: return 6;
5707f7c002Slewis-revill   case /*s4*/  RISCV::X20: return 5;
5807f7c002Slewis-revill   case /*s3*/  RISCV::X19: return 4;
5907f7c002Slewis-revill   case /*s2*/  RISCV::X18: return 3;
6007f7c002Slewis-revill   case /*s1*/  RISCV::X9:  return 2;
6107f7c002Slewis-revill   case /*s0*/  RISCV::X8:  return 1;
6207f7c002Slewis-revill   case /*ra*/  RISCV::X1:  return 0;
6307f7c002Slewis-revill   }
6407f7c002Slewis-revill }
6507f7c002Slewis-revill 
6607f7c002Slewis-revill // Get the name of the libcall used for spilling callee saved registers.
6707f7c002Slewis-revill // If this function will not use save/restore libcalls, then return a nullptr.
6807f7c002Slewis-revill static const char *
6907f7c002Slewis-revill getSpillLibCallName(const MachineFunction &MF,
7007f7c002Slewis-revill                     const std::vector<CalleeSavedInfo> &CSI) {
7107f7c002Slewis-revill   static const char *const SpillLibCalls[] = {
7207f7c002Slewis-revill     "__riscv_save_0",
7307f7c002Slewis-revill     "__riscv_save_1",
7407f7c002Slewis-revill     "__riscv_save_2",
7507f7c002Slewis-revill     "__riscv_save_3",
7607f7c002Slewis-revill     "__riscv_save_4",
7707f7c002Slewis-revill     "__riscv_save_5",
7807f7c002Slewis-revill     "__riscv_save_6",
7907f7c002Slewis-revill     "__riscv_save_7",
8007f7c002Slewis-revill     "__riscv_save_8",
8107f7c002Slewis-revill     "__riscv_save_9",
8207f7c002Slewis-revill     "__riscv_save_10",
8307f7c002Slewis-revill     "__riscv_save_11",
8407f7c002Slewis-revill     "__riscv_save_12"
8507f7c002Slewis-revill   };
8607f7c002Slewis-revill 
8707f7c002Slewis-revill   int LibCallID = getLibCallID(MF, CSI);
8807f7c002Slewis-revill   if (LibCallID == -1)
8907f7c002Slewis-revill     return nullptr;
9007f7c002Slewis-revill   return SpillLibCalls[LibCallID];
9107f7c002Slewis-revill }
9207f7c002Slewis-revill 
9307f7c002Slewis-revill // Get the name of the libcall used for restoring callee saved registers.
9407f7c002Slewis-revill // If this function will not use save/restore libcalls, then return a nullptr.
9507f7c002Slewis-revill static const char *
9607f7c002Slewis-revill getRestoreLibCallName(const MachineFunction &MF,
9707f7c002Slewis-revill                       const std::vector<CalleeSavedInfo> &CSI) {
9807f7c002Slewis-revill   static const char *const RestoreLibCalls[] = {
9907f7c002Slewis-revill     "__riscv_restore_0",
10007f7c002Slewis-revill     "__riscv_restore_1",
10107f7c002Slewis-revill     "__riscv_restore_2",
10207f7c002Slewis-revill     "__riscv_restore_3",
10307f7c002Slewis-revill     "__riscv_restore_4",
10407f7c002Slewis-revill     "__riscv_restore_5",
10507f7c002Slewis-revill     "__riscv_restore_6",
10607f7c002Slewis-revill     "__riscv_restore_7",
10707f7c002Slewis-revill     "__riscv_restore_8",
10807f7c002Slewis-revill     "__riscv_restore_9",
10907f7c002Slewis-revill     "__riscv_restore_10",
11007f7c002Slewis-revill     "__riscv_restore_11",
11107f7c002Slewis-revill     "__riscv_restore_12"
11207f7c002Slewis-revill   };
11307f7c002Slewis-revill 
11407f7c002Slewis-revill   int LibCallID = getLibCallID(MF, CSI);
11507f7c002Slewis-revill   if (LibCallID == -1)
11607f7c002Slewis-revill     return nullptr;
11707f7c002Slewis-revill   return RestoreLibCalls[LibCallID];
11807f7c002Slewis-revill }
11907f7c002Slewis-revill 
1207d6aa1f7SAlex Bradbury bool RISCVFrameLowering::hasFP(const MachineFunction &MF) const {
1217d6aa1f7SAlex Bradbury   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
1227d6aa1f7SAlex Bradbury 
1237d6aa1f7SAlex Bradbury   const MachineFrameInfo &MFI = MF.getFrameInfo();
1247d6aa1f7SAlex Bradbury   return MF.getTarget().Options.DisableFramePointerElim(MF) ||
1257d6aa1f7SAlex Bradbury          RegInfo->needsStackRealignment(MF) || MFI.hasVarSizedObjects() ||
1267d6aa1f7SAlex Bradbury          MFI.isFrameAddressTaken();
1277d6aa1f7SAlex Bradbury }
1288971842fSAlex Bradbury 
129cf6cf0cdSShiva Chen bool RISCVFrameLowering::hasBP(const MachineFunction &MF) const {
130cf6cf0cdSShiva Chen   const MachineFrameInfo &MFI = MF.getFrameInfo();
131cf6cf0cdSShiva Chen   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
132cf6cf0cdSShiva Chen 
133cf6cf0cdSShiva Chen   return MFI.hasVarSizedObjects() && TRI->needsStackRealignment(MF);
134cf6cf0cdSShiva Chen }
135cf6cf0cdSShiva Chen 
136b014e3deSAlex Bradbury // Determines the size of the frame and maximum call frame size.
137b014e3deSAlex Bradbury void RISCVFrameLowering::determineFrameLayout(MachineFunction &MF) const {
138b014e3deSAlex Bradbury   MachineFrameInfo &MFI = MF.getFrameInfo();
139b014e3deSAlex Bradbury   const RISCVRegisterInfo *RI = STI.getRegisterInfo();
140b014e3deSAlex Bradbury 
141b014e3deSAlex Bradbury   // Get the number of bytes to allocate from the FrameInfo.
142b014e3deSAlex Bradbury   uint64_t FrameSize = MFI.getStackSize();
143b014e3deSAlex Bradbury 
144b014e3deSAlex Bradbury   // Get the alignment.
145d000655aSGuillaume Chatelet   Align StackAlign = getStackAlign();
146cd44aee3SSam Elliott   if (RI->needsStackRealignment(MF)) {
147d000655aSGuillaume Chatelet     Align MaxStackAlign = std::max(StackAlign, MFI.getMaxAlign());
148d000655aSGuillaume Chatelet     FrameSize += (MaxStackAlign.value() - StackAlign.value());
149cd44aee3SSam Elliott     StackAlign = MaxStackAlign;
150cd44aee3SSam Elliott   }
151cd44aee3SSam Elliott 
152cd44aee3SSam Elliott   // Set Max Call Frame Size
153cd44aee3SSam Elliott   uint64_t MaxCallSize = alignTo(MFI.getMaxCallFrameSize(), StackAlign);
154cd44aee3SSam Elliott   MFI.setMaxCallFrameSize(MaxCallSize);
155b014e3deSAlex Bradbury 
156b014e3deSAlex Bradbury   // Make sure the frame is aligned.
157b014e3deSAlex Bradbury   FrameSize = alignTo(FrameSize, StackAlign);
158b014e3deSAlex Bradbury 
159b014e3deSAlex Bradbury   // Update frame info.
160b014e3deSAlex Bradbury   MFI.setStackSize(FrameSize);
161b014e3deSAlex Bradbury }
162b014e3deSAlex Bradbury 
163b014e3deSAlex Bradbury void RISCVFrameLowering::adjustReg(MachineBasicBlock &MBB,
164b014e3deSAlex Bradbury                                    MachineBasicBlock::iterator MBBI,
165fa06e958SLuis Marques                                    const DebugLoc &DL, Register DestReg,
166fa06e958SLuis Marques                                    Register SrcReg, int64_t Val,
167b014e3deSAlex Bradbury                                    MachineInstr::MIFlag Flag) const {
1689fea4881SAlex Bradbury   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
169b014e3deSAlex Bradbury   const RISCVInstrInfo *TII = STI.getInstrInfo();
170b014e3deSAlex Bradbury 
171b014e3deSAlex Bradbury   if (DestReg == SrcReg && Val == 0)
172b014e3deSAlex Bradbury     return;
173b014e3deSAlex Bradbury 
1749fea4881SAlex Bradbury   if (isInt<12>(Val)) {
175b014e3deSAlex Bradbury     BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), DestReg)
176b014e3deSAlex Bradbury         .addReg(SrcReg)
177b014e3deSAlex Bradbury         .addImm(Val)
178b014e3deSAlex Bradbury         .setMIFlag(Flag);
179a49a16ddSShiva Chen   } else {
1809fea4881SAlex Bradbury     unsigned Opc = RISCV::ADD;
1819fea4881SAlex Bradbury     bool isSub = Val < 0;
1829fea4881SAlex Bradbury     if (isSub) {
1839fea4881SAlex Bradbury       Val = -Val;
1849fea4881SAlex Bradbury       Opc = RISCV::SUB;
1859fea4881SAlex Bradbury     }
1869fea4881SAlex Bradbury 
1873836874dSDaniel Sanders     Register ScratchReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
188a49a16ddSShiva Chen     TII->movImm(MBB, MBBI, DL, ScratchReg, Val, Flag);
1899fea4881SAlex Bradbury     BuildMI(MBB, MBBI, DL, TII->get(Opc), DestReg)
1909fea4881SAlex Bradbury         .addReg(SrcReg)
1919fea4881SAlex Bradbury         .addReg(ScratchReg, RegState::Kill)
1929fea4881SAlex Bradbury         .setMIFlag(Flag);
1939fea4881SAlex Bradbury   }
194b014e3deSAlex Bradbury }
195b014e3deSAlex Bradbury 
196b014e3deSAlex Bradbury // Returns the register used to hold the frame pointer.
197fa06e958SLuis Marques static Register getFPReg(const RISCVSubtarget &STI) { return RISCV::X8; }
198b014e3deSAlex Bradbury 
199b014e3deSAlex Bradbury // Returns the register used to hold the stack pointer.
200fa06e958SLuis Marques static Register getSPReg(const RISCVSubtarget &STI) { return RISCV::X2; }
201b014e3deSAlex Bradbury 
20207f7c002Slewis-revill static SmallVector<CalleeSavedInfo, 8>
20307f7c002Slewis-revill getNonLibcallCSI(const std::vector<CalleeSavedInfo> &CSI) {
20407f7c002Slewis-revill   SmallVector<CalleeSavedInfo, 8> NonLibcallCSI;
20507f7c002Slewis-revill 
20607f7c002Slewis-revill   for (auto &CS : CSI)
20707f7c002Slewis-revill     if (CS.getFrameIdx() >= 0)
20807f7c002Slewis-revill       NonLibcallCSI.push_back(CS);
20907f7c002Slewis-revill 
21007f7c002Slewis-revill   return NonLibcallCSI;
21107f7c002Slewis-revill }
21207f7c002Slewis-revill 
2138971842fSAlex Bradbury void RISCVFrameLowering::emitPrologue(MachineFunction &MF,
214b014e3deSAlex Bradbury                                       MachineBasicBlock &MBB) const {
215b014e3deSAlex Bradbury   MachineFrameInfo &MFI = MF.getFrameInfo();
216c85be0deSAlex Bradbury   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
21704ddf39bSHsiangkai Wang   const RISCVRegisterInfo *RI = STI.getRegisterInfo();
21804ddf39bSHsiangkai Wang   const RISCVInstrInfo *TII = STI.getInstrInfo();
219b014e3deSAlex Bradbury   MachineBasicBlock::iterator MBBI = MBB.begin();
220b014e3deSAlex Bradbury 
221fa06e958SLuis Marques   Register FPReg = getFPReg(STI);
222fa06e958SLuis Marques   Register SPReg = getSPReg(STI);
223cf6cf0cdSShiva Chen   Register BPReg = RISCVABI::getBPReg();
224b014e3deSAlex Bradbury 
22507f7c002Slewis-revill   // Since spillCalleeSavedRegisters may have inserted a libcall, skip past
22607f7c002Slewis-revill   // any instructions marked as FrameSetup
22707f7c002Slewis-revill   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
22807f7c002Slewis-revill     ++MBBI;
22907f7c002Slewis-revill 
230b014e3deSAlex Bradbury   // Debug location must be unknown since the first debug location is used
231b014e3deSAlex Bradbury   // to determine the end of the prologue.
232b014e3deSAlex Bradbury   DebugLoc DL;
233b014e3deSAlex Bradbury 
234b014e3deSAlex Bradbury   // Determine the correct frame layout
235b014e3deSAlex Bradbury   determineFrameLayout(MF);
236b014e3deSAlex Bradbury 
23707f7c002Slewis-revill   // If libcalls are used to spill and restore callee-saved registers, the frame
23807f7c002Slewis-revill   // has two sections; the opaque section managed by the libcalls, and the
23907f7c002Slewis-revill   // section managed by MachineFrameInfo which can also hold callee saved
24007f7c002Slewis-revill   // registers in fixed stack slots, both of which have negative frame indices.
24107f7c002Slewis-revill   // This gets even more complicated when incoming arguments are passed via the
24207f7c002Slewis-revill   // stack, as these too have negative frame indices. An example is detailed
24307f7c002Slewis-revill   // below:
24407f7c002Slewis-revill   //
24507f7c002Slewis-revill   //  | incoming arg | <- FI[-3]
24607f7c002Slewis-revill   //  | libcallspill |
24707f7c002Slewis-revill   //  | calleespill  | <- FI[-2]
24807f7c002Slewis-revill   //  | calleespill  | <- FI[-1]
24907f7c002Slewis-revill   //  | this_frame   | <- FI[0]
25007f7c002Slewis-revill   //
25107f7c002Slewis-revill   // For negative frame indices, the offset from the frame pointer will differ
25207f7c002Slewis-revill   // depending on which of these groups the frame index applies to.
25307f7c002Slewis-revill   // The following calculates the correct offset knowing the number of callee
25407f7c002Slewis-revill   // saved registers spilt by the two methods.
25507f7c002Slewis-revill   if (int LibCallRegs = getLibCallID(MF, MFI.getCalleeSavedInfo()) + 1) {
25607f7c002Slewis-revill     // Calculate the size of the frame managed by the libcall. The libcalls are
25707f7c002Slewis-revill     // implemented such that the stack will always be 16 byte aligned.
25807f7c002Slewis-revill     unsigned LibCallFrameSize = alignTo((STI.getXLen() / 8) * LibCallRegs, 16);
25907f7c002Slewis-revill     RVFI->setLibCallStackSize(LibCallFrameSize);
26007f7c002Slewis-revill   }
26107f7c002Slewis-revill 
262b014e3deSAlex Bradbury   // FIXME (note copied from Lanai): This appears to be overallocating.  Needs
263b014e3deSAlex Bradbury   // investigation. Get the number of bytes to allocate from the FrameInfo.
264b014e3deSAlex Bradbury   uint64_t StackSize = MFI.getStackSize();
26507f7c002Slewis-revill   uint64_t RealStackSize = StackSize + RVFI->getLibCallStackSize();
266b014e3deSAlex Bradbury 
267b014e3deSAlex Bradbury   // Early exit if there is no need to allocate on the stack
26807f7c002Slewis-revill   if (RealStackSize == 0 && !MFI.adjustsStack())
269b014e3deSAlex Bradbury     return;
270b014e3deSAlex Bradbury 
271aed9d6d6SSimon Cook   // If the stack pointer has been marked as reserved, then produce an error if
272aed9d6d6SSimon Cook   // the frame requires stack allocation
273aed9d6d6SSimon Cook   if (STI.isRegisterReservedByUser(SPReg))
274aed9d6d6SSimon Cook     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
275aed9d6d6SSimon Cook         MF.getFunction(), "Stack pointer required, but has been reserved."});
276aed9d6d6SSimon Cook 
277ff55e2e0SShiva Chen   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
278ff55e2e0SShiva Chen   // Split the SP adjustment to reduce the offsets of callee saved spill.
27907f7c002Slewis-revill   if (FirstSPAdjustAmount) {
280ff55e2e0SShiva Chen     StackSize = FirstSPAdjustAmount;
28107f7c002Slewis-revill     RealStackSize = FirstSPAdjustAmount;
28207f7c002Slewis-revill   }
283ff55e2e0SShiva Chen 
284b014e3deSAlex Bradbury   // Allocate space on the stack if necessary.
285b014e3deSAlex Bradbury   adjustReg(MBB, MBBI, DL, SPReg, SPReg, -StackSize, MachineInstr::FrameSetup);
286b014e3deSAlex Bradbury 
28707f7c002Slewis-revill   // Emit ".cfi_def_cfa_offset RealStackSize"
28804ddf39bSHsiangkai Wang   unsigned CFIIndex = MF.addFrameInst(
28907f7c002Slewis-revill       MCCFIInstruction::createDefCfaOffset(nullptr, -RealStackSize));
29004ddf39bSHsiangkai Wang   BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
29104ddf39bSHsiangkai Wang       .addCFIIndex(CFIIndex);
29204ddf39bSHsiangkai Wang 
29307f7c002Slewis-revill   const auto &CSI = MFI.getCalleeSavedInfo();
29407f7c002Slewis-revill 
295b014e3deSAlex Bradbury   // The frame pointer is callee-saved, and code has been generated for us to
296b014e3deSAlex Bradbury   // save it to the stack. We need to skip over the storing of callee-saved
297b014e3deSAlex Bradbury   // registers as the frame pointer must be modified after it has been saved
298b014e3deSAlex Bradbury   // to the stack, not before.
299b014e3deSAlex Bradbury   // FIXME: assumes exactly one instruction is used to save each callee-saved
300b014e3deSAlex Bradbury   // register.
30107f7c002Slewis-revill   std::advance(MBBI, getNonLibcallCSI(CSI).size());
302b014e3deSAlex Bradbury 
30304ddf39bSHsiangkai Wang   // Iterate over list of callee-saved registers and emit .cfi_offset
30404ddf39bSHsiangkai Wang   // directives.
30504ddf39bSHsiangkai Wang   for (const auto &Entry : CSI) {
30607f7c002Slewis-revill     int FrameIdx = Entry.getFrameIdx();
30707f7c002Slewis-revill     int64_t Offset;
30807f7c002Slewis-revill     // Offsets for objects with fixed locations (IE: those saved by libcall) are
30907f7c002Slewis-revill     // simply calculated from the frame index.
31007f7c002Slewis-revill     if (FrameIdx < 0)
31107f7c002Slewis-revill       Offset = FrameIdx * (int64_t) STI.getXLen() / 8;
31207f7c002Slewis-revill     else
31307f7c002Slewis-revill       Offset = MFI.getObjectOffset(Entry.getFrameIdx()) -
31407f7c002Slewis-revill                RVFI->getLibCallStackSize();
315fa06e958SLuis Marques     Register Reg = Entry.getReg();
31604ddf39bSHsiangkai Wang     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
31704ddf39bSHsiangkai Wang         nullptr, RI->getDwarfRegNum(Reg, true), Offset));
31804ddf39bSHsiangkai Wang     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
31904ddf39bSHsiangkai Wang         .addCFIIndex(CFIIndex);
32004ddf39bSHsiangkai Wang   }
32104ddf39bSHsiangkai Wang 
322b014e3deSAlex Bradbury   // Generate new FP.
32304ddf39bSHsiangkai Wang   if (hasFP(MF)) {
324aed9d6d6SSimon Cook     if (STI.isRegisterReservedByUser(FPReg))
325aed9d6d6SSimon Cook       MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
326aed9d6d6SSimon Cook           MF.getFunction(), "Frame pointer required, but has been reserved."});
327aed9d6d6SSimon Cook 
3287d6aa1f7SAlex Bradbury     adjustReg(MBB, MBBI, DL, FPReg, SPReg,
32907f7c002Slewis-revill               RealStackSize - RVFI->getVarArgsSaveSize(),
33007f7c002Slewis-revill               MachineInstr::FrameSetup);
33104ddf39bSHsiangkai Wang 
33264f41720SShiva Chen     // Emit ".cfi_def_cfa $fp, -RVFI->getVarArgsSaveSize()"
33304ddf39bSHsiangkai Wang     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa(
33464f41720SShiva Chen         nullptr, RI->getDwarfRegNum(FPReg, true), -RVFI->getVarArgsSaveSize()));
33504ddf39bSHsiangkai Wang     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
33604ddf39bSHsiangkai Wang         .addCFIIndex(CFIIndex);
337ff55e2e0SShiva Chen   }
338cd44aee3SSam Elliott 
339ff55e2e0SShiva Chen   // Emit the second SP adjustment after saving callee saved registers.
340ff55e2e0SShiva Chen   if (FirstSPAdjustAmount) {
341ff55e2e0SShiva Chen     uint64_t SecondSPAdjustAmount = MFI.getStackSize() - FirstSPAdjustAmount;
342ff55e2e0SShiva Chen     assert(SecondSPAdjustAmount > 0 &&
343ff55e2e0SShiva Chen            "SecondSPAdjustAmount should be greater than zero");
344ff55e2e0SShiva Chen     adjustReg(MBB, MBBI, DL, SPReg, SPReg, -SecondSPAdjustAmount,
345ff55e2e0SShiva Chen               MachineInstr::FrameSetup);
3461c737f54SLuís Marques 
3471c737f54SLuís Marques     // If we are using a frame-pointer, and thus emitted ".cfi_def_cfa fp, 0",
3481c737f54SLuís Marques     // don't emit an sp-based .cfi_def_cfa_offset
3491c737f54SLuís Marques     if (!hasFP(MF)) {
350ff55e2e0SShiva Chen       // Emit ".cfi_def_cfa_offset StackSize"
351ff55e2e0SShiva Chen       unsigned CFIIndex = MF.addFrameInst(
352ff55e2e0SShiva Chen           MCCFIInstruction::createDefCfaOffset(nullptr, -MFI.getStackSize()));
353ff55e2e0SShiva Chen       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
354ff55e2e0SShiva Chen           .addCFIIndex(CFIIndex);
355ff55e2e0SShiva Chen     }
3561c737f54SLuís Marques   }
357ff55e2e0SShiva Chen 
358ff55e2e0SShiva Chen   if (hasFP(MF)) {
359cd44aee3SSam Elliott     // Realign Stack
360cd44aee3SSam Elliott     const RISCVRegisterInfo *RI = STI.getRegisterInfo();
361cd44aee3SSam Elliott     if (RI->needsStackRealignment(MF)) {
362d000655aSGuillaume Chatelet       Align MaxAlignment = MFI.getMaxAlign();
363cd44aee3SSam Elliott 
364cd44aee3SSam Elliott       const RISCVInstrInfo *TII = STI.getInstrInfo();
365d000655aSGuillaume Chatelet       if (isInt<12>(-(int)MaxAlignment.value())) {
366cd44aee3SSam Elliott         BuildMI(MBB, MBBI, DL, TII->get(RISCV::ANDI), SPReg)
367cd44aee3SSam Elliott             .addReg(SPReg)
368d000655aSGuillaume Chatelet             .addImm(-(int)MaxAlignment.value());
369cd44aee3SSam Elliott       } else {
370d000655aSGuillaume Chatelet         unsigned ShiftAmount = Log2(MaxAlignment);
371fa06e958SLuis Marques         Register VR =
372cd44aee3SSam Elliott             MF.getRegInfo().createVirtualRegister(&RISCV::GPRRegClass);
373cd44aee3SSam Elliott         BuildMI(MBB, MBBI, DL, TII->get(RISCV::SRLI), VR)
374cd44aee3SSam Elliott             .addReg(SPReg)
375cd44aee3SSam Elliott             .addImm(ShiftAmount);
376cd44aee3SSam Elliott         BuildMI(MBB, MBBI, DL, TII->get(RISCV::SLLI), SPReg)
377cd44aee3SSam Elliott             .addReg(VR)
378cd44aee3SSam Elliott             .addImm(ShiftAmount);
379cd44aee3SSam Elliott       }
380cf6cf0cdSShiva Chen       // FP will be used to restore the frame in the epilogue, so we need
381cf6cf0cdSShiva Chen       // another base register BP to record SP after re-alignment. SP will
382cf6cf0cdSShiva Chen       // track the current stack after allocating variable sized objects.
383cf6cf0cdSShiva Chen       if (hasBP(MF)) {
384cf6cf0cdSShiva Chen         // move BP, SP
385cf6cf0cdSShiva Chen         BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), BPReg)
386cf6cf0cdSShiva Chen             .addReg(SPReg)
387cf6cf0cdSShiva Chen             .addImm(0);
388cf6cf0cdSShiva Chen       }
389cd44aee3SSam Elliott     }
39004ddf39bSHsiangkai Wang   }
391b014e3deSAlex Bradbury }
3928971842fSAlex Bradbury 
3938971842fSAlex Bradbury void RISCVFrameLowering::emitEpilogue(MachineFunction &MF,
394b014e3deSAlex Bradbury                                       MachineBasicBlock &MBB) const {
395b014e3deSAlex Bradbury   const RISCVRegisterInfo *RI = STI.getRegisterInfo();
396b014e3deSAlex Bradbury   MachineFrameInfo &MFI = MF.getFrameInfo();
397c85be0deSAlex Bradbury   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
398fa06e958SLuis Marques   Register FPReg = getFPReg(STI);
399fa06e958SLuis Marques   Register SPReg = getSPReg(STI);
400b014e3deSAlex Bradbury 
401cd800f3bSlewis-revill   // Get the insert location for the epilogue. If there were no terminators in
402cd800f3bSlewis-revill   // the block, get the last instruction.
403cd800f3bSlewis-revill   MachineBasicBlock::iterator MBBI = MBB.end();
404cd800f3bSlewis-revill   DebugLoc DL;
405cd800f3bSlewis-revill   if (!MBB.empty()) {
406cd800f3bSlewis-revill     MBBI = MBB.getFirstTerminator();
407cd800f3bSlewis-revill     if (MBBI == MBB.end())
408cd800f3bSlewis-revill       MBBI = MBB.getLastNonDebugInstr();
409cd800f3bSlewis-revill     DL = MBBI->getDebugLoc();
410cd800f3bSlewis-revill 
411cd800f3bSlewis-revill     // If this is not a terminator, the actual insert location should be after the
412cd800f3bSlewis-revill     // last instruction.
413cd800f3bSlewis-revill     if (!MBBI->isTerminator())
414cd800f3bSlewis-revill       MBBI = std::next(MBBI);
41507f7c002Slewis-revill 
41607f7c002Slewis-revill     // If callee-saved registers are saved via libcall, place stack adjustment
41707f7c002Slewis-revill     // before this call.
41807f7c002Slewis-revill     while (MBBI != MBB.begin() &&
41907f7c002Slewis-revill            std::prev(MBBI)->getFlag(MachineInstr::FrameDestroy))
42007f7c002Slewis-revill       --MBBI;
421cd800f3bSlewis-revill   }
422cd800f3bSlewis-revill 
42307f7c002Slewis-revill   const auto &CSI = getNonLibcallCSI(MFI.getCalleeSavedInfo());
42407f7c002Slewis-revill 
425b014e3deSAlex Bradbury   // Skip to before the restores of callee-saved registers
426b014e3deSAlex Bradbury   // FIXME: assumes exactly one instruction is used to restore each
427b014e3deSAlex Bradbury   // callee-saved register.
42807f7c002Slewis-revill   auto LastFrameDestroy = MBBI;
42907f7c002Slewis-revill   if (!CSI.empty())
43007f7c002Slewis-revill     LastFrameDestroy = std::prev(MBBI, CSI.size());
431b014e3deSAlex Bradbury 
432b014e3deSAlex Bradbury   uint64_t StackSize = MFI.getStackSize();
43307f7c002Slewis-revill   uint64_t RealStackSize = StackSize + RVFI->getLibCallStackSize();
43407f7c002Slewis-revill   uint64_t FPOffset = RealStackSize - RVFI->getVarArgsSaveSize();
435b014e3deSAlex Bradbury 
436b014e3deSAlex Bradbury   // Restore the stack pointer using the value of the frame pointer. Only
437b014e3deSAlex Bradbury   // necessary if the stack pointer was modified, meaning the stack size is
438b014e3deSAlex Bradbury   // unknown.
439b014e3deSAlex Bradbury   if (RI->needsStackRealignment(MF) || MFI.hasVarSizedObjects()) {
4407d6aa1f7SAlex Bradbury     assert(hasFP(MF) && "frame pointer should not have been eliminated");
44104ddf39bSHsiangkai Wang     adjustReg(MBB, LastFrameDestroy, DL, SPReg, FPReg, -FPOffset,
442b014e3deSAlex Bradbury               MachineInstr::FrameDestroy);
443b014e3deSAlex Bradbury   }
444b014e3deSAlex Bradbury 
445ff55e2e0SShiva Chen   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
446ff55e2e0SShiva Chen   if (FirstSPAdjustAmount) {
447ff55e2e0SShiva Chen     uint64_t SecondSPAdjustAmount = MFI.getStackSize() - FirstSPAdjustAmount;
448ff55e2e0SShiva Chen     assert(SecondSPAdjustAmount > 0 &&
449ff55e2e0SShiva Chen            "SecondSPAdjustAmount should be greater than zero");
450ff55e2e0SShiva Chen 
451ff55e2e0SShiva Chen     adjustReg(MBB, LastFrameDestroy, DL, SPReg, SPReg, SecondSPAdjustAmount,
452ff55e2e0SShiva Chen               MachineInstr::FrameDestroy);
45304ddf39bSHsiangkai Wang   }
45404ddf39bSHsiangkai Wang 
455ff55e2e0SShiva Chen   if (FirstSPAdjustAmount)
456ff55e2e0SShiva Chen     StackSize = FirstSPAdjustAmount;
457ff55e2e0SShiva Chen 
458b014e3deSAlex Bradbury   // Deallocate stack
459b014e3deSAlex Bradbury   adjustReg(MBB, MBBI, DL, SPReg, SPReg, StackSize, MachineInstr::FrameDestroy);
460b014e3deSAlex Bradbury }
461660bccecSAlex Bradbury 
462660bccecSAlex Bradbury int RISCVFrameLowering::getFrameIndexReference(const MachineFunction &MF,
463660bccecSAlex Bradbury                                                int FI,
464660bccecSAlex Bradbury                                                unsigned &FrameReg) const {
465660bccecSAlex Bradbury   const MachineFrameInfo &MFI = MF.getFrameInfo();
466660bccecSAlex Bradbury   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
467c85be0deSAlex Bradbury   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
468660bccecSAlex Bradbury 
469660bccecSAlex Bradbury   // Callee-saved registers should be referenced relative to the stack
470660bccecSAlex Bradbury   // pointer (positive offset), otherwise use the frame pointer (negative
471660bccecSAlex Bradbury   // offset).
47207f7c002Slewis-revill   const auto &CSI = getNonLibcallCSI(MFI.getCalleeSavedInfo());
473660bccecSAlex Bradbury   int MinCSFI = 0;
474660bccecSAlex Bradbury   int MaxCSFI = -1;
475660bccecSAlex Bradbury 
476660bccecSAlex Bradbury   int Offset = MFI.getObjectOffset(FI) - getOffsetOfLocalArea() +
477660bccecSAlex Bradbury                MFI.getOffsetAdjustment();
478660bccecSAlex Bradbury 
479ff55e2e0SShiva Chen   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
480ff55e2e0SShiva Chen 
481660bccecSAlex Bradbury   if (CSI.size()) {
482660bccecSAlex Bradbury     MinCSFI = CSI[0].getFrameIdx();
483660bccecSAlex Bradbury     MaxCSFI = CSI[CSI.size() - 1].getFrameIdx();
484660bccecSAlex Bradbury   }
485660bccecSAlex Bradbury 
486660bccecSAlex Bradbury   if (FI >= MinCSFI && FI <= MaxCSFI) {
487660bccecSAlex Bradbury     FrameReg = RISCV::X2;
488ff55e2e0SShiva Chen 
489ff55e2e0SShiva Chen     if (FirstSPAdjustAmount)
490ff55e2e0SShiva Chen       Offset += FirstSPAdjustAmount;
491ff55e2e0SShiva Chen     else
49207f7c002Slewis-revill       Offset += MFI.getStackSize();
493cf6cf0cdSShiva Chen   } else if (RI->needsStackRealignment(MF) && !MFI.isFixedObjectIndex(FI)) {
494cd44aee3SSam Elliott     // If the stack was realigned, the frame pointer is set in order to allow
495cf6cf0cdSShiva Chen     // SP to be restored, so we need another base register to record the stack
496cf6cf0cdSShiva Chen     // after realignment.
497cf6cf0cdSShiva Chen     if (hasBP(MF))
498cf6cf0cdSShiva Chen       FrameReg = RISCVABI::getBPReg();
499cf6cf0cdSShiva Chen     else
500cd44aee3SSam Elliott       FrameReg = RISCV::X2;
50107f7c002Slewis-revill     Offset += MFI.getStackSize();
50207f7c002Slewis-revill     if (FI < 0)
50307f7c002Slewis-revill       Offset += RVFI->getLibCallStackSize();
504c85be0deSAlex Bradbury   } else {
505c85be0deSAlex Bradbury     FrameReg = RI->getFrameRegister(MF);
50607f7c002Slewis-revill     if (hasFP(MF)) {
507c85be0deSAlex Bradbury       Offset += RVFI->getVarArgsSaveSize();
50807f7c002Slewis-revill       if (FI >= 0)
50907f7c002Slewis-revill         Offset -= RVFI->getLibCallStackSize();
51007f7c002Slewis-revill     } else {
51107f7c002Slewis-revill       Offset += MFI.getStackSize();
51207f7c002Slewis-revill       if (FI < 0)
51307f7c002Slewis-revill         Offset += RVFI->getLibCallStackSize();
51407f7c002Slewis-revill     }
515660bccecSAlex Bradbury   }
516660bccecSAlex Bradbury   return Offset;
517660bccecSAlex Bradbury }
518b014e3deSAlex Bradbury 
519b014e3deSAlex Bradbury void RISCVFrameLowering::determineCalleeSaves(MachineFunction &MF,
520b014e3deSAlex Bradbury                                               BitVector &SavedRegs,
521b014e3deSAlex Bradbury                                               RegScavenger *RS) const {
522b014e3deSAlex Bradbury   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
5237d6aa1f7SAlex Bradbury   // Unconditionally spill RA and FP only if the function uses a frame
5247d6aa1f7SAlex Bradbury   // pointer.
5257d6aa1f7SAlex Bradbury   if (hasFP(MF)) {
526b014e3deSAlex Bradbury     SavedRegs.set(RISCV::X1);
527b014e3deSAlex Bradbury     SavedRegs.set(RISCV::X8);
528b014e3deSAlex Bradbury   }
529cf6cf0cdSShiva Chen   // Mark BP as used if function has dedicated base pointer.
530cf6cf0cdSShiva Chen   if (hasBP(MF))
531cf6cf0cdSShiva Chen     SavedRegs.set(RISCVABI::getBPReg());
5322e4106b7SAna Pazos 
5332e4106b7SAna Pazos   // If interrupt is enabled and there are calls in the handler,
5342e4106b7SAna Pazos   // unconditionally save all Caller-saved registers and
5352e4106b7SAna Pazos   // all FP registers, regardless whether they are used.
5362e4106b7SAna Pazos   MachineFrameInfo &MFI = MF.getFrameInfo();
5372e4106b7SAna Pazos 
5382e4106b7SAna Pazos   if (MF.getFunction().hasFnAttribute("interrupt") && MFI.hasCalls()) {
5392e4106b7SAna Pazos 
5402e4106b7SAna Pazos     static const MCPhysReg CSRegs[] = { RISCV::X1,      /* ra */
5412e4106b7SAna Pazos       RISCV::X5, RISCV::X6, RISCV::X7,                  /* t0-t2 */
5422e4106b7SAna Pazos       RISCV::X10, RISCV::X11,                           /* a0-a1, a2-a7 */
5432e4106b7SAna Pazos       RISCV::X12, RISCV::X13, RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17,
5442e4106b7SAna Pazos       RISCV::X28, RISCV::X29, RISCV::X30, RISCV::X31, 0 /* t3-t6 */
5452e4106b7SAna Pazos     };
5462e4106b7SAna Pazos 
5472e4106b7SAna Pazos     for (unsigned i = 0; CSRegs[i]; ++i)
5482e4106b7SAna Pazos       SavedRegs.set(CSRegs[i]);
5492e4106b7SAna Pazos 
5502e4106b7SAna Pazos     if (MF.getSubtarget<RISCVSubtarget>().hasStdExtD() ||
5512e4106b7SAna Pazos         MF.getSubtarget<RISCVSubtarget>().hasStdExtF()) {
5522e4106b7SAna Pazos 
5532e4106b7SAna Pazos       // If interrupt is enabled, this list contains all FP registers.
5542e4106b7SAna Pazos       const MCPhysReg * Regs = MF.getRegInfo().getCalleeSavedRegs();
5552e4106b7SAna Pazos 
5562e4106b7SAna Pazos       for (unsigned i = 0; Regs[i]; ++i)
5572e4106b7SAna Pazos         if (RISCV::FPR32RegClass.contains(Regs[i]) ||
5582e4106b7SAna Pazos             RISCV::FPR64RegClass.contains(Regs[i]))
5592e4106b7SAna Pazos           SavedRegs.set(Regs[i]);
5602e4106b7SAna Pazos     }
5612e4106b7SAna Pazos   }
5627d6aa1f7SAlex Bradbury }
5630715d35eSAlex Bradbury 
5640715d35eSAlex Bradbury void RISCVFrameLowering::processFunctionBeforeFrameFinalized(
5650715d35eSAlex Bradbury     MachineFunction &MF, RegScavenger *RS) const {
5660715d35eSAlex Bradbury   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
5670715d35eSAlex Bradbury   MachineFrameInfo &MFI = MF.getFrameInfo();
5680715d35eSAlex Bradbury   const TargetRegisterClass *RC = &RISCV::GPRRegClass;
5690715d35eSAlex Bradbury   // estimateStackSize has been observed to under-estimate the final stack
5700715d35eSAlex Bradbury   // size, so give ourselves wiggle-room by checking for stack size
5710715d35eSAlex Bradbury   // representable an 11-bit signed field rather than 12-bits.
5720715d35eSAlex Bradbury   // FIXME: It may be possible to craft a function with a small stack that
5730715d35eSAlex Bradbury   // still needs an emergency spill slot for branch relaxation. This case
5740715d35eSAlex Bradbury   // would currently be missed.
5750715d35eSAlex Bradbury   if (!isInt<11>(MFI.estimateStackSize(MF))) {
5760715d35eSAlex Bradbury     int RegScavFI = MFI.CreateStackObject(
5770715d35eSAlex Bradbury         RegInfo->getSpillSize(*RC), RegInfo->getSpillAlignment(*RC), false);
5780715d35eSAlex Bradbury     RS->addScavengingFrameIndex(RegScavFI);
5790715d35eSAlex Bradbury   }
5800715d35eSAlex Bradbury }
581cbd498acSShiva Chen 
582cbd498acSShiva Chen // Not preserve stack space within prologue for outgoing variables when the
583cbd498acSShiva Chen // function contains variable size objects and let eliminateCallFramePseudoInstr
584cbd498acSShiva Chen // preserve stack space for it.
585cbd498acSShiva Chen bool RISCVFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
586cbd498acSShiva Chen   return !MF.getFrameInfo().hasVarSizedObjects();
587cbd498acSShiva Chen }
588cbd498acSShiva Chen 
589cbd498acSShiva Chen // Eliminate ADJCALLSTACKDOWN, ADJCALLSTACKUP pseudo instructions.
590cbd498acSShiva Chen MachineBasicBlock::iterator RISCVFrameLowering::eliminateCallFramePseudoInstr(
591cbd498acSShiva Chen     MachineFunction &MF, MachineBasicBlock &MBB,
592cbd498acSShiva Chen     MachineBasicBlock::iterator MI) const {
593fa06e958SLuis Marques   Register SPReg = RISCV::X2;
594cbd498acSShiva Chen   DebugLoc DL = MI->getDebugLoc();
595cbd498acSShiva Chen 
596cbd498acSShiva Chen   if (!hasReservedCallFrame(MF)) {
597cbd498acSShiva Chen     // If space has not been reserved for a call frame, ADJCALLSTACKDOWN and
598cbd498acSShiva Chen     // ADJCALLSTACKUP must be converted to instructions manipulating the stack
599cbd498acSShiva Chen     // pointer. This is necessary when there is a variable length stack
600cbd498acSShiva Chen     // allocation (e.g. alloca), which means it's not possible to allocate
601cbd498acSShiva Chen     // space for outgoing arguments from within the function prologue.
602cbd498acSShiva Chen     int64_t Amount = MI->getOperand(0).getImm();
603cbd498acSShiva Chen 
604cbd498acSShiva Chen     if (Amount != 0) {
605cbd498acSShiva Chen       // Ensure the stack remains aligned after adjustment.
606cbd498acSShiva Chen       Amount = alignSPAdjust(Amount);
607cbd498acSShiva Chen 
608cbd498acSShiva Chen       if (MI->getOpcode() == RISCV::ADJCALLSTACKDOWN)
609cbd498acSShiva Chen         Amount = -Amount;
610cbd498acSShiva Chen 
611cbd498acSShiva Chen       adjustReg(MBB, MI, DL, SPReg, SPReg, Amount, MachineInstr::NoFlags);
612cbd498acSShiva Chen     }
613cbd498acSShiva Chen   }
614cbd498acSShiva Chen 
615cbd498acSShiva Chen   return MBB.erase(MI);
616cbd498acSShiva Chen }
617ff55e2e0SShiva Chen 
618ff55e2e0SShiva Chen // We would like to split the SP adjustment to reduce prologue/epilogue
619ff55e2e0SShiva Chen // as following instructions. In this way, the offset of the callee saved
620ff55e2e0SShiva Chen // register could fit in a single store.
621ff55e2e0SShiva Chen //   add     sp,sp,-2032
622ff55e2e0SShiva Chen //   sw      ra,2028(sp)
623ff55e2e0SShiva Chen //   sw      s0,2024(sp)
624ff55e2e0SShiva Chen //   sw      s1,2020(sp)
625ff55e2e0SShiva Chen //   sw      s3,2012(sp)
626ff55e2e0SShiva Chen //   sw      s4,2008(sp)
627ff55e2e0SShiva Chen //   add     sp,sp,-64
628ff55e2e0SShiva Chen uint64_t
629ff55e2e0SShiva Chen RISCVFrameLowering::getFirstSPAdjustAmount(const MachineFunction &MF) const {
63007f7c002Slewis-revill   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
631ff55e2e0SShiva Chen   const MachineFrameInfo &MFI = MF.getFrameInfo();
632ff55e2e0SShiva Chen   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
633ff55e2e0SShiva Chen   uint64_t StackSize = MFI.getStackSize();
634ff55e2e0SShiva Chen 
63507f7c002Slewis-revill   // Disable SplitSPAdjust if save-restore libcall used. The callee saved
63607f7c002Slewis-revill   // registers will be pushed by the save-restore libcalls, so we don't have to
63707f7c002Slewis-revill   // split the SP adjustment in this case.
63807f7c002Slewis-revill   if (RVFI->getLibCallStackSize())
63907f7c002Slewis-revill     return 0;
64007f7c002Slewis-revill 
641ff55e2e0SShiva Chen   // Return the FirstSPAdjustAmount if the StackSize can not fit in signed
642ff55e2e0SShiva Chen   // 12-bit and there exists a callee saved register need to be pushed.
643ff55e2e0SShiva Chen   if (!isInt<12>(StackSize) && (CSI.size() > 0)) {
644ff55e2e0SShiva Chen     // FirstSPAdjustAmount is choosed as (2048 - StackAlign)
645ff55e2e0SShiva Chen     // because 2048 will cause sp = sp + 2048 in epilogue split into
646ff55e2e0SShiva Chen     // multi-instructions. The offset smaller than 2048 can fit in signle
647ff55e2e0SShiva Chen     // load/store instruction and we have to stick with the stack alignment.
648ff55e2e0SShiva Chen     // 2048 is 16-byte alignment. The stack alignment for RV32 and RV64 is 16,
649ff55e2e0SShiva Chen     // for RV32E is 4. So (2048 - StackAlign) will satisfy the stack alignment.
650*3ba550a0SGuillaume Chatelet     return 2048 - getStackAlign().value();
651ff55e2e0SShiva Chen   }
652ff55e2e0SShiva Chen   return 0;
653ff55e2e0SShiva Chen }
65407f7c002Slewis-revill 
65507f7c002Slewis-revill bool RISCVFrameLowering::spillCalleeSavedRegisters(
65607f7c002Slewis-revill     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
65707f7c002Slewis-revill     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
65807f7c002Slewis-revill   if (CSI.empty())
65907f7c002Slewis-revill     return true;
66007f7c002Slewis-revill 
66107f7c002Slewis-revill   MachineFunction *MF = MBB.getParent();
66207f7c002Slewis-revill   const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
66307f7c002Slewis-revill   DebugLoc DL;
66407f7c002Slewis-revill   if (MI != MBB.end() && !MI->isDebugInstr())
66507f7c002Slewis-revill     DL = MI->getDebugLoc();
66607f7c002Slewis-revill 
66707f7c002Slewis-revill   const char *SpillLibCall = getSpillLibCallName(*MF, CSI);
66807f7c002Slewis-revill   if (SpillLibCall) {
66907f7c002Slewis-revill     // Add spill libcall via non-callee-saved register t0.
67007f7c002Slewis-revill     BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoCALLReg), RISCV::X5)
67107f7c002Slewis-revill         .addExternalSymbol(SpillLibCall, RISCVII::MO_CALL)
67207f7c002Slewis-revill         .setMIFlag(MachineInstr::FrameSetup);
67307f7c002Slewis-revill 
67407f7c002Slewis-revill     // Add registers spilled in libcall as liveins.
67507f7c002Slewis-revill     for (auto &CS : CSI)
67607f7c002Slewis-revill       MBB.addLiveIn(CS.getReg());
67707f7c002Slewis-revill   }
67807f7c002Slewis-revill 
67907f7c002Slewis-revill   // Manually spill values not spilled by libcall.
68007f7c002Slewis-revill   const auto &NonLibcallCSI = getNonLibcallCSI(CSI);
68107f7c002Slewis-revill   for (auto &CS : NonLibcallCSI) {
68207f7c002Slewis-revill     // Insert the spill to the stack frame.
68307f7c002Slewis-revill     Register Reg = CS.getReg();
68407f7c002Slewis-revill     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
68507f7c002Slewis-revill     TII.storeRegToStackSlot(MBB, MI, Reg, true, CS.getFrameIdx(), RC, TRI);
68607f7c002Slewis-revill   }
68707f7c002Slewis-revill 
68807f7c002Slewis-revill   return true;
68907f7c002Slewis-revill }
69007f7c002Slewis-revill 
69107f7c002Slewis-revill bool RISCVFrameLowering::restoreCalleeSavedRegisters(
69207f7c002Slewis-revill     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
693186dd631SBenjamin Kramer     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
69407f7c002Slewis-revill   if (CSI.empty())
69507f7c002Slewis-revill     return true;
69607f7c002Slewis-revill 
69707f7c002Slewis-revill   MachineFunction *MF = MBB.getParent();
69807f7c002Slewis-revill   const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
69907f7c002Slewis-revill   DebugLoc DL;
70007f7c002Slewis-revill   if (MI != MBB.end() && !MI->isDebugInstr())
70107f7c002Slewis-revill     DL = MI->getDebugLoc();
70207f7c002Slewis-revill 
70307f7c002Slewis-revill   // Manually restore values not restored by libcall. Insert in reverse order.
70407f7c002Slewis-revill   // loadRegFromStackSlot can insert multiple instructions.
70507f7c002Slewis-revill   const auto &NonLibcallCSI = getNonLibcallCSI(CSI);
70607f7c002Slewis-revill   for (auto &CS : reverse(NonLibcallCSI)) {
70707f7c002Slewis-revill     Register Reg = CS.getReg();
70807f7c002Slewis-revill     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
70907f7c002Slewis-revill     TII.loadRegFromStackSlot(MBB, MI, Reg, CS.getFrameIdx(), RC, TRI);
71007f7c002Slewis-revill     assert(MI != MBB.begin() && "loadRegFromStackSlot didn't insert any code!");
71107f7c002Slewis-revill   }
71207f7c002Slewis-revill 
71307f7c002Slewis-revill   const char *RestoreLibCall = getRestoreLibCallName(*MF, CSI);
71407f7c002Slewis-revill   if (RestoreLibCall) {
71507f7c002Slewis-revill     // Add restore libcall via tail call.
71607f7c002Slewis-revill     MachineBasicBlock::iterator NewMI =
71707f7c002Slewis-revill         BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoTAIL))
71807f7c002Slewis-revill             .addExternalSymbol(RestoreLibCall, RISCVII::MO_CALL)
71907f7c002Slewis-revill             .setMIFlag(MachineInstr::FrameDestroy);
72007f7c002Slewis-revill 
72107f7c002Slewis-revill     // Remove trailing returns, since the terminator is now a tail call to the
72207f7c002Slewis-revill     // restore function.
72307f7c002Slewis-revill     if (MI != MBB.end() && MI->getOpcode() == RISCV::PseudoRET) {
72407f7c002Slewis-revill       NewMI->copyImplicitOps(*MF, *MI);
72507f7c002Slewis-revill       MI->eraseFromParent();
72607f7c002Slewis-revill     }
72707f7c002Slewis-revill   }
72807f7c002Slewis-revill 
72907f7c002Slewis-revill   return true;
73007f7c002Slewis-revill }
73107f7c002Slewis-revill 
73207f7c002Slewis-revill bool RISCVFrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const {
73307f7c002Slewis-revill   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
73407f7c002Slewis-revill   const auto *RVFI = MBB.getParent()->getInfo<RISCVMachineFunctionInfo>();
73507f7c002Slewis-revill 
73607f7c002Slewis-revill   if (!RVFI->useSaveRestoreLibCalls())
73707f7c002Slewis-revill     return true;
73807f7c002Slewis-revill 
73907f7c002Slewis-revill   // Inserting a call to a __riscv_save libcall requires the use of the register
74007f7c002Slewis-revill   // t0 (X5) to hold the return address. Therefore if this register is already
74107f7c002Slewis-revill   // used we can't insert the call.
74207f7c002Slewis-revill 
74307f7c002Slewis-revill   RegScavenger RS;
74407f7c002Slewis-revill   RS.enterBasicBlock(*TmpMBB);
74507f7c002Slewis-revill   return !RS.isRegUsed(RISCV::X5);
74607f7c002Slewis-revill }
74707f7c002Slewis-revill 
74807f7c002Slewis-revill bool RISCVFrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
74907f7c002Slewis-revill   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
75007f7c002Slewis-revill   const auto *RVFI = MBB.getParent()->getInfo<RISCVMachineFunctionInfo>();
75107f7c002Slewis-revill 
75207f7c002Slewis-revill   if (!RVFI->useSaveRestoreLibCalls())
75307f7c002Slewis-revill     return true;
75407f7c002Slewis-revill 
75507f7c002Slewis-revill   // Using the __riscv_restore libcalls to restore CSRs requires a tail call.
75607f7c002Slewis-revill   // This means if we still need to continue executing code within this function
75707f7c002Slewis-revill   // the restore cannot take place in this basic block.
75807f7c002Slewis-revill 
75907f7c002Slewis-revill   if (MBB.succ_size() > 1)
76007f7c002Slewis-revill     return false;
76107f7c002Slewis-revill 
76207f7c002Slewis-revill   MachineBasicBlock *SuccMBB =
76307f7c002Slewis-revill       MBB.succ_empty() ? TmpMBB->getFallThrough() : *MBB.succ_begin();
76407f7c002Slewis-revill 
76507f7c002Slewis-revill   // Doing a tail call should be safe if there are no successors, because either
76607f7c002Slewis-revill   // we have a returning block or the end of the block is unreachable, so the
76707f7c002Slewis-revill   // restore will be eliminated regardless.
76807f7c002Slewis-revill   if (!SuccMBB)
76907f7c002Slewis-revill     return true;
77007f7c002Slewis-revill 
77107f7c002Slewis-revill   // The successor can only contain a return, since we would effectively be
77207f7c002Slewis-revill   // replacing the successor with our own tail return at the end of our block.
77307f7c002Slewis-revill   return SuccMBB->isReturnBlock() && SuccMBB->size() == 1;
77407f7c002Slewis-revill }
775