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 
261c466477SZhaoshi Zheng // For now we use x18, a.k.a s2, as pointer to shadow call stack.
271c466477SZhaoshi Zheng // User should explicitly set -ffixed-x18 and not use x18 in their asm.
281c466477SZhaoshi Zheng static void emitSCSPrologue(MachineFunction &MF, MachineBasicBlock &MBB,
291c466477SZhaoshi Zheng                             MachineBasicBlock::iterator MI,
301c466477SZhaoshi Zheng                             const DebugLoc &DL) {
311c466477SZhaoshi Zheng   if (!MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack))
321c466477SZhaoshi Zheng     return;
331c466477SZhaoshi Zheng 
341c466477SZhaoshi Zheng   const auto &STI = MF.getSubtarget<RISCVSubtarget>();
351c466477SZhaoshi Zheng   Register RAReg = STI.getRegisterInfo()->getRARegister();
361c466477SZhaoshi Zheng 
371c466477SZhaoshi Zheng   // Do not save RA to the SCS if it's not saved to the regular stack,
381c466477SZhaoshi Zheng   // i.e. RA is not at risk of being overwritten.
391c466477SZhaoshi Zheng   std::vector<CalleeSavedInfo> &CSI = MF.getFrameInfo().getCalleeSavedInfo();
401c466477SZhaoshi Zheng   if (std::none_of(CSI.begin(), CSI.end(),
411c466477SZhaoshi Zheng                    [&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
421c466477SZhaoshi Zheng     return;
431c466477SZhaoshi Zheng 
441c466477SZhaoshi Zheng   Register SCSPReg = RISCVABI::getSCSPReg();
451c466477SZhaoshi Zheng 
461c466477SZhaoshi Zheng   auto &Ctx = MF.getFunction().getContext();
471c466477SZhaoshi Zheng   if (!STI.isRegisterReservedByUser(SCSPReg)) {
481c466477SZhaoshi Zheng     Ctx.diagnose(DiagnosticInfoUnsupported{
491c466477SZhaoshi Zheng         MF.getFunction(), "x18 not reserved by user for Shadow Call Stack."});
501c466477SZhaoshi Zheng     return;
511c466477SZhaoshi Zheng   }
521c466477SZhaoshi Zheng 
531c466477SZhaoshi Zheng   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
541c466477SZhaoshi Zheng   if (RVFI->useSaveRestoreLibCalls(MF)) {
551c466477SZhaoshi Zheng     Ctx.diagnose(DiagnosticInfoUnsupported{
561c466477SZhaoshi Zheng         MF.getFunction(),
571c466477SZhaoshi Zheng         "Shadow Call Stack cannot be combined with Save/Restore LibCalls."});
581c466477SZhaoshi Zheng     return;
591c466477SZhaoshi Zheng   }
601c466477SZhaoshi Zheng 
611c466477SZhaoshi Zheng   const RISCVInstrInfo *TII = STI.getInstrInfo();
621c466477SZhaoshi Zheng   bool IsRV64 = STI.hasFeature(RISCV::Feature64Bit);
631c466477SZhaoshi Zheng   int64_t SlotSize = STI.getXLen() / 8;
641c466477SZhaoshi Zheng   // Store return address to shadow call stack
651c466477SZhaoshi Zheng   // s[w|d]  ra, 0(s2)
661c466477SZhaoshi Zheng   // addi    s2, s2, [4|8]
671c466477SZhaoshi Zheng   BuildMI(MBB, MI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
681c466477SZhaoshi Zheng       .addReg(RAReg)
691c466477SZhaoshi Zheng       .addReg(SCSPReg)
701c466477SZhaoshi Zheng       .addImm(0);
711c466477SZhaoshi Zheng   BuildMI(MBB, MI, DL, TII->get(RISCV::ADDI))
721c466477SZhaoshi Zheng       .addReg(SCSPReg, RegState::Define)
731c466477SZhaoshi Zheng       .addReg(SCSPReg)
741c466477SZhaoshi Zheng       .addImm(SlotSize);
751c466477SZhaoshi Zheng }
761c466477SZhaoshi Zheng 
771c466477SZhaoshi Zheng static void emitSCSEpilogue(MachineFunction &MF, MachineBasicBlock &MBB,
781c466477SZhaoshi Zheng                             MachineBasicBlock::iterator MI,
791c466477SZhaoshi Zheng                             const DebugLoc &DL) {
801c466477SZhaoshi Zheng   if (!MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack))
811c466477SZhaoshi Zheng     return;
821c466477SZhaoshi Zheng 
831c466477SZhaoshi Zheng   const auto &STI = MF.getSubtarget<RISCVSubtarget>();
841c466477SZhaoshi Zheng   Register RAReg = STI.getRegisterInfo()->getRARegister();
851c466477SZhaoshi Zheng 
861c466477SZhaoshi Zheng   // See emitSCSPrologue() above.
871c466477SZhaoshi Zheng   std::vector<CalleeSavedInfo> &CSI = MF.getFrameInfo().getCalleeSavedInfo();
881c466477SZhaoshi Zheng   if (std::none_of(CSI.begin(), CSI.end(),
891c466477SZhaoshi Zheng                    [&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
901c466477SZhaoshi Zheng     return;
911c466477SZhaoshi Zheng 
921c466477SZhaoshi Zheng   Register SCSPReg = RISCVABI::getSCSPReg();
931c466477SZhaoshi Zheng 
941c466477SZhaoshi Zheng   auto &Ctx = MF.getFunction().getContext();
951c466477SZhaoshi Zheng   if (!STI.isRegisterReservedByUser(SCSPReg)) {
961c466477SZhaoshi Zheng     Ctx.diagnose(DiagnosticInfoUnsupported{
971c466477SZhaoshi Zheng         MF.getFunction(), "x18 not reserved by user for Shadow Call Stack."});
981c466477SZhaoshi Zheng     return;
991c466477SZhaoshi Zheng   }
1001c466477SZhaoshi Zheng 
1011c466477SZhaoshi Zheng   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1021c466477SZhaoshi Zheng   if (RVFI->useSaveRestoreLibCalls(MF)) {
1031c466477SZhaoshi Zheng     Ctx.diagnose(DiagnosticInfoUnsupported{
1041c466477SZhaoshi Zheng         MF.getFunction(),
1051c466477SZhaoshi Zheng         "Shadow Call Stack cannot be combined with Save/Restore LibCalls."});
1061c466477SZhaoshi Zheng     return;
1071c466477SZhaoshi Zheng   }
1081c466477SZhaoshi Zheng 
1091c466477SZhaoshi Zheng   const RISCVInstrInfo *TII = STI.getInstrInfo();
1101c466477SZhaoshi Zheng   bool IsRV64 = STI.hasFeature(RISCV::Feature64Bit);
1111c466477SZhaoshi Zheng   int64_t SlotSize = STI.getXLen() / 8;
1121c466477SZhaoshi Zheng   // Load return address from shadow call stack
1131c466477SZhaoshi Zheng   // l[w|d]  ra, -[4|8](s2)
1141c466477SZhaoshi Zheng   // addi    s2, s2, -[4|8]
1151c466477SZhaoshi Zheng   BuildMI(MBB, MI, DL, TII->get(IsRV64 ? RISCV::LD : RISCV::LW))
1161c466477SZhaoshi Zheng       .addReg(RAReg, RegState::Define)
1171c466477SZhaoshi Zheng       .addReg(SCSPReg)
1181c466477SZhaoshi Zheng       .addImm(-SlotSize);
1191c466477SZhaoshi Zheng   BuildMI(MBB, MI, DL, TII->get(RISCV::ADDI))
1201c466477SZhaoshi Zheng       .addReg(SCSPReg, RegState::Define)
1211c466477SZhaoshi Zheng       .addReg(SCSPReg)
1221c466477SZhaoshi Zheng       .addImm(-SlotSize);
1231c466477SZhaoshi Zheng }
1241c466477SZhaoshi Zheng 
12507f7c002Slewis-revill // Get the ID of the libcall used for spilling and restoring callee saved
12607f7c002Slewis-revill // registers. The ID is representative of the number of registers saved or
12707f7c002Slewis-revill // restored by the libcall, except it is zero-indexed - ID 0 corresponds to a
12807f7c002Slewis-revill // single register.
12907f7c002Slewis-revill static int getLibCallID(const MachineFunction &MF,
13007f7c002Slewis-revill                         const std::vector<CalleeSavedInfo> &CSI) {
13107f7c002Slewis-revill   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
13207f7c002Slewis-revill 
13308649f0aSMatt Arsenault   if (CSI.empty() || !RVFI->useSaveRestoreLibCalls(MF))
13407f7c002Slewis-revill     return -1;
13507f7c002Slewis-revill 
13607f7c002Slewis-revill   Register MaxReg = RISCV::NoRegister;
13707f7c002Slewis-revill   for (auto &CS : CSI)
13807f7c002Slewis-revill     // RISCVRegisterInfo::hasReservedSpillSlot assigns negative frame indexes to
13907f7c002Slewis-revill     // registers which can be saved by libcall.
14007f7c002Slewis-revill     if (CS.getFrameIdx() < 0)
14107f7c002Slewis-revill       MaxReg = std::max(MaxReg.id(), CS.getReg());
14207f7c002Slewis-revill 
14307f7c002Slewis-revill   if (MaxReg == RISCV::NoRegister)
14407f7c002Slewis-revill     return -1;
14507f7c002Slewis-revill 
14607f7c002Slewis-revill   switch (MaxReg) {
14707f7c002Slewis-revill   default:
14807f7c002Slewis-revill     llvm_unreachable("Something has gone wrong!");
14907f7c002Slewis-revill   case /*s11*/ RISCV::X27: return 12;
15007f7c002Slewis-revill   case /*s10*/ RISCV::X26: return 11;
15107f7c002Slewis-revill   case /*s9*/  RISCV::X25: return 10;
15207f7c002Slewis-revill   case /*s8*/  RISCV::X24: return 9;
15307f7c002Slewis-revill   case /*s7*/  RISCV::X23: return 8;
15407f7c002Slewis-revill   case /*s6*/  RISCV::X22: return 7;
15507f7c002Slewis-revill   case /*s5*/  RISCV::X21: return 6;
15607f7c002Slewis-revill   case /*s4*/  RISCV::X20: return 5;
15707f7c002Slewis-revill   case /*s3*/  RISCV::X19: return 4;
15807f7c002Slewis-revill   case /*s2*/  RISCV::X18: return 3;
15907f7c002Slewis-revill   case /*s1*/  RISCV::X9:  return 2;
16007f7c002Slewis-revill   case /*s0*/  RISCV::X8:  return 1;
16107f7c002Slewis-revill   case /*ra*/  RISCV::X1:  return 0;
16207f7c002Slewis-revill   }
16307f7c002Slewis-revill }
16407f7c002Slewis-revill 
16507f7c002Slewis-revill // Get the name of the libcall used for spilling callee saved registers.
16607f7c002Slewis-revill // If this function will not use save/restore libcalls, then return a nullptr.
16707f7c002Slewis-revill static const char *
16807f7c002Slewis-revill getSpillLibCallName(const MachineFunction &MF,
16907f7c002Slewis-revill                     const std::vector<CalleeSavedInfo> &CSI) {
17007f7c002Slewis-revill   static const char *const SpillLibCalls[] = {
17107f7c002Slewis-revill     "__riscv_save_0",
17207f7c002Slewis-revill     "__riscv_save_1",
17307f7c002Slewis-revill     "__riscv_save_2",
17407f7c002Slewis-revill     "__riscv_save_3",
17507f7c002Slewis-revill     "__riscv_save_4",
17607f7c002Slewis-revill     "__riscv_save_5",
17707f7c002Slewis-revill     "__riscv_save_6",
17807f7c002Slewis-revill     "__riscv_save_7",
17907f7c002Slewis-revill     "__riscv_save_8",
18007f7c002Slewis-revill     "__riscv_save_9",
18107f7c002Slewis-revill     "__riscv_save_10",
18207f7c002Slewis-revill     "__riscv_save_11",
18307f7c002Slewis-revill     "__riscv_save_12"
18407f7c002Slewis-revill   };
18507f7c002Slewis-revill 
18607f7c002Slewis-revill   int LibCallID = getLibCallID(MF, CSI);
18707f7c002Slewis-revill   if (LibCallID == -1)
18807f7c002Slewis-revill     return nullptr;
18907f7c002Slewis-revill   return SpillLibCalls[LibCallID];
19007f7c002Slewis-revill }
19107f7c002Slewis-revill 
19207f7c002Slewis-revill // Get the name of the libcall used for restoring callee saved registers.
19307f7c002Slewis-revill // If this function will not use save/restore libcalls, then return a nullptr.
19407f7c002Slewis-revill static const char *
19507f7c002Slewis-revill getRestoreLibCallName(const MachineFunction &MF,
19607f7c002Slewis-revill                       const std::vector<CalleeSavedInfo> &CSI) {
19707f7c002Slewis-revill   static const char *const RestoreLibCalls[] = {
19807f7c002Slewis-revill     "__riscv_restore_0",
19907f7c002Slewis-revill     "__riscv_restore_1",
20007f7c002Slewis-revill     "__riscv_restore_2",
20107f7c002Slewis-revill     "__riscv_restore_3",
20207f7c002Slewis-revill     "__riscv_restore_4",
20307f7c002Slewis-revill     "__riscv_restore_5",
20407f7c002Slewis-revill     "__riscv_restore_6",
20507f7c002Slewis-revill     "__riscv_restore_7",
20607f7c002Slewis-revill     "__riscv_restore_8",
20707f7c002Slewis-revill     "__riscv_restore_9",
20807f7c002Slewis-revill     "__riscv_restore_10",
20907f7c002Slewis-revill     "__riscv_restore_11",
21007f7c002Slewis-revill     "__riscv_restore_12"
21107f7c002Slewis-revill   };
21207f7c002Slewis-revill 
21307f7c002Slewis-revill   int LibCallID = getLibCallID(MF, CSI);
21407f7c002Slewis-revill   if (LibCallID == -1)
21507f7c002Slewis-revill     return nullptr;
21607f7c002Slewis-revill   return RestoreLibCalls[LibCallID];
21707f7c002Slewis-revill }
21807f7c002Slewis-revill 
2197d6aa1f7SAlex Bradbury bool RISCVFrameLowering::hasFP(const MachineFunction &MF) const {
2207d6aa1f7SAlex Bradbury   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
2217d6aa1f7SAlex Bradbury 
2227d6aa1f7SAlex Bradbury   const MachineFrameInfo &MFI = MF.getFrameInfo();
2237d6aa1f7SAlex Bradbury   return MF.getTarget().Options.DisableFramePointerElim(MF) ||
2247d6aa1f7SAlex Bradbury          RegInfo->needsStackRealignment(MF) || MFI.hasVarSizedObjects() ||
2257d6aa1f7SAlex Bradbury          MFI.isFrameAddressTaken();
2267d6aa1f7SAlex Bradbury }
2278971842fSAlex Bradbury 
228cf6cf0cdSShiva Chen bool RISCVFrameLowering::hasBP(const MachineFunction &MF) const {
229cf6cf0cdSShiva Chen   const MachineFrameInfo &MFI = MF.getFrameInfo();
230cf6cf0cdSShiva Chen   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
231cf6cf0cdSShiva Chen 
232cf6cf0cdSShiva Chen   return MFI.hasVarSizedObjects() && TRI->needsStackRealignment(MF);
233cf6cf0cdSShiva Chen }
234cf6cf0cdSShiva Chen 
235b014e3deSAlex Bradbury // Determines the size of the frame and maximum call frame size.
236b014e3deSAlex Bradbury void RISCVFrameLowering::determineFrameLayout(MachineFunction &MF) const {
237b014e3deSAlex Bradbury   MachineFrameInfo &MFI = MF.getFrameInfo();
238b014e3deSAlex Bradbury   const RISCVRegisterInfo *RI = STI.getRegisterInfo();
239b014e3deSAlex Bradbury 
240b014e3deSAlex Bradbury   // Get the number of bytes to allocate from the FrameInfo.
241b014e3deSAlex Bradbury   uint64_t FrameSize = MFI.getStackSize();
242b014e3deSAlex Bradbury 
243b014e3deSAlex Bradbury   // Get the alignment.
244d000655aSGuillaume Chatelet   Align StackAlign = getStackAlign();
245cd44aee3SSam Elliott   if (RI->needsStackRealignment(MF)) {
246d000655aSGuillaume Chatelet     Align MaxStackAlign = std::max(StackAlign, MFI.getMaxAlign());
247d000655aSGuillaume Chatelet     FrameSize += (MaxStackAlign.value() - StackAlign.value());
248cd44aee3SSam Elliott     StackAlign = MaxStackAlign;
249cd44aee3SSam Elliott   }
250cd44aee3SSam Elliott 
251cd44aee3SSam Elliott   // Set Max Call Frame Size
252cd44aee3SSam Elliott   uint64_t MaxCallSize = alignTo(MFI.getMaxCallFrameSize(), StackAlign);
253cd44aee3SSam Elliott   MFI.setMaxCallFrameSize(MaxCallSize);
254b014e3deSAlex Bradbury 
255b014e3deSAlex Bradbury   // Make sure the frame is aligned.
256b014e3deSAlex Bradbury   FrameSize = alignTo(FrameSize, StackAlign);
257b014e3deSAlex Bradbury 
258b014e3deSAlex Bradbury   // Update frame info.
259b014e3deSAlex Bradbury   MFI.setStackSize(FrameSize);
260b014e3deSAlex Bradbury }
261b014e3deSAlex Bradbury 
262b014e3deSAlex Bradbury void RISCVFrameLowering::adjustReg(MachineBasicBlock &MBB,
263b014e3deSAlex Bradbury                                    MachineBasicBlock::iterator MBBI,
264fa06e958SLuis Marques                                    const DebugLoc &DL, Register DestReg,
265fa06e958SLuis Marques                                    Register SrcReg, int64_t Val,
266b014e3deSAlex Bradbury                                    MachineInstr::MIFlag Flag) const {
2679fea4881SAlex Bradbury   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
268b014e3deSAlex Bradbury   const RISCVInstrInfo *TII = STI.getInstrInfo();
269b014e3deSAlex Bradbury 
270b014e3deSAlex Bradbury   if (DestReg == SrcReg && Val == 0)
271b014e3deSAlex Bradbury     return;
272b014e3deSAlex Bradbury 
2739fea4881SAlex Bradbury   if (isInt<12>(Val)) {
274b014e3deSAlex Bradbury     BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), DestReg)
275b014e3deSAlex Bradbury         .addReg(SrcReg)
276b014e3deSAlex Bradbury         .addImm(Val)
277b014e3deSAlex Bradbury         .setMIFlag(Flag);
278a49a16ddSShiva Chen   } else {
2799fea4881SAlex Bradbury     unsigned Opc = RISCV::ADD;
2809fea4881SAlex Bradbury     bool isSub = Val < 0;
2819fea4881SAlex Bradbury     if (isSub) {
2829fea4881SAlex Bradbury       Val = -Val;
2839fea4881SAlex Bradbury       Opc = RISCV::SUB;
2849fea4881SAlex Bradbury     }
2859fea4881SAlex Bradbury 
2863836874dSDaniel Sanders     Register ScratchReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
287a49a16ddSShiva Chen     TII->movImm(MBB, MBBI, DL, ScratchReg, Val, Flag);
2889fea4881SAlex Bradbury     BuildMI(MBB, MBBI, DL, TII->get(Opc), DestReg)
2899fea4881SAlex Bradbury         .addReg(SrcReg)
2909fea4881SAlex Bradbury         .addReg(ScratchReg, RegState::Kill)
2919fea4881SAlex Bradbury         .setMIFlag(Flag);
2929fea4881SAlex Bradbury   }
293b014e3deSAlex Bradbury }
294b014e3deSAlex Bradbury 
295b014e3deSAlex Bradbury // Returns the register used to hold the frame pointer.
296fa06e958SLuis Marques static Register getFPReg(const RISCVSubtarget &STI) { return RISCV::X8; }
297b014e3deSAlex Bradbury 
298b014e3deSAlex Bradbury // Returns the register used to hold the stack pointer.
299fa06e958SLuis Marques static Register getSPReg(const RISCVSubtarget &STI) { return RISCV::X2; }
300b014e3deSAlex Bradbury 
30107f7c002Slewis-revill static SmallVector<CalleeSavedInfo, 8>
30207f7c002Slewis-revill getNonLibcallCSI(const std::vector<CalleeSavedInfo> &CSI) {
30307f7c002Slewis-revill   SmallVector<CalleeSavedInfo, 8> NonLibcallCSI;
30407f7c002Slewis-revill 
30507f7c002Slewis-revill   for (auto &CS : CSI)
30607f7c002Slewis-revill     if (CS.getFrameIdx() >= 0)
30707f7c002Slewis-revill       NonLibcallCSI.push_back(CS);
30807f7c002Slewis-revill 
30907f7c002Slewis-revill   return NonLibcallCSI;
31007f7c002Slewis-revill }
31107f7c002Slewis-revill 
3128971842fSAlex Bradbury void RISCVFrameLowering::emitPrologue(MachineFunction &MF,
313b014e3deSAlex Bradbury                                       MachineBasicBlock &MBB) const {
314b014e3deSAlex Bradbury   MachineFrameInfo &MFI = MF.getFrameInfo();
315c85be0deSAlex Bradbury   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
31604ddf39bSHsiangkai Wang   const RISCVRegisterInfo *RI = STI.getRegisterInfo();
31704ddf39bSHsiangkai Wang   const RISCVInstrInfo *TII = STI.getInstrInfo();
318b014e3deSAlex Bradbury   MachineBasicBlock::iterator MBBI = MBB.begin();
319b014e3deSAlex Bradbury 
320fa06e958SLuis Marques   Register FPReg = getFPReg(STI);
321fa06e958SLuis Marques   Register SPReg = getSPReg(STI);
322cf6cf0cdSShiva Chen   Register BPReg = RISCVABI::getBPReg();
323b014e3deSAlex Bradbury 
3241c466477SZhaoshi Zheng   // Debug location must be unknown since the first debug location is used
3251c466477SZhaoshi Zheng   // to determine the end of the prologue.
3261c466477SZhaoshi Zheng   DebugLoc DL;
3271c466477SZhaoshi Zheng 
328a8dc2110SLuís Marques   // All calls are tail calls in GHC calling conv, and functions have no
329a8dc2110SLuís Marques   // prologue/epilogue.
330a8dc2110SLuís Marques   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
331a8dc2110SLuís Marques     return;
332a8dc2110SLuís Marques 
3331c466477SZhaoshi Zheng   // Emit prologue for shadow call stack.
3341c466477SZhaoshi Zheng   emitSCSPrologue(MF, MBB, MBBI, DL);
3351c466477SZhaoshi Zheng 
33607f7c002Slewis-revill   // Since spillCalleeSavedRegisters may have inserted a libcall, skip past
33707f7c002Slewis-revill   // any instructions marked as FrameSetup
33807f7c002Slewis-revill   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
33907f7c002Slewis-revill     ++MBBI;
34007f7c002Slewis-revill 
341b014e3deSAlex Bradbury   // Determine the correct frame layout
342b014e3deSAlex Bradbury   determineFrameLayout(MF);
343b014e3deSAlex Bradbury 
34407f7c002Slewis-revill   // If libcalls are used to spill and restore callee-saved registers, the frame
34507f7c002Slewis-revill   // has two sections; the opaque section managed by the libcalls, and the
34607f7c002Slewis-revill   // section managed by MachineFrameInfo which can also hold callee saved
34707f7c002Slewis-revill   // registers in fixed stack slots, both of which have negative frame indices.
34807f7c002Slewis-revill   // This gets even more complicated when incoming arguments are passed via the
34907f7c002Slewis-revill   // stack, as these too have negative frame indices. An example is detailed
35007f7c002Slewis-revill   // below:
35107f7c002Slewis-revill   //
35207f7c002Slewis-revill   //  | incoming arg | <- FI[-3]
35307f7c002Slewis-revill   //  | libcallspill |
35407f7c002Slewis-revill   //  | calleespill  | <- FI[-2]
35507f7c002Slewis-revill   //  | calleespill  | <- FI[-1]
35607f7c002Slewis-revill   //  | this_frame   | <- FI[0]
35707f7c002Slewis-revill   //
35807f7c002Slewis-revill   // For negative frame indices, the offset from the frame pointer will differ
35907f7c002Slewis-revill   // depending on which of these groups the frame index applies to.
36007f7c002Slewis-revill   // The following calculates the correct offset knowing the number of callee
36107f7c002Slewis-revill   // saved registers spilt by the two methods.
36207f7c002Slewis-revill   if (int LibCallRegs = getLibCallID(MF, MFI.getCalleeSavedInfo()) + 1) {
36307f7c002Slewis-revill     // Calculate the size of the frame managed by the libcall. The libcalls are
36407f7c002Slewis-revill     // implemented such that the stack will always be 16 byte aligned.
36507f7c002Slewis-revill     unsigned LibCallFrameSize = alignTo((STI.getXLen() / 8) * LibCallRegs, 16);
36607f7c002Slewis-revill     RVFI->setLibCallStackSize(LibCallFrameSize);
36707f7c002Slewis-revill   }
36807f7c002Slewis-revill 
369b014e3deSAlex Bradbury   // FIXME (note copied from Lanai): This appears to be overallocating.  Needs
370b014e3deSAlex Bradbury   // investigation. Get the number of bytes to allocate from the FrameInfo.
371b014e3deSAlex Bradbury   uint64_t StackSize = MFI.getStackSize();
37207f7c002Slewis-revill   uint64_t RealStackSize = StackSize + RVFI->getLibCallStackSize();
373b014e3deSAlex Bradbury 
374b014e3deSAlex Bradbury   // Early exit if there is no need to allocate on the stack
37507f7c002Slewis-revill   if (RealStackSize == 0 && !MFI.adjustsStack())
376b014e3deSAlex Bradbury     return;
377b014e3deSAlex Bradbury 
378aed9d6d6SSimon Cook   // If the stack pointer has been marked as reserved, then produce an error if
379aed9d6d6SSimon Cook   // the frame requires stack allocation
380aed9d6d6SSimon Cook   if (STI.isRegisterReservedByUser(SPReg))
381aed9d6d6SSimon Cook     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
382aed9d6d6SSimon Cook         MF.getFunction(), "Stack pointer required, but has been reserved."});
383aed9d6d6SSimon Cook 
384ff55e2e0SShiva Chen   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
385ff55e2e0SShiva Chen   // Split the SP adjustment to reduce the offsets of callee saved spill.
38607f7c002Slewis-revill   if (FirstSPAdjustAmount) {
387ff55e2e0SShiva Chen     StackSize = FirstSPAdjustAmount;
38807f7c002Slewis-revill     RealStackSize = FirstSPAdjustAmount;
38907f7c002Slewis-revill   }
390ff55e2e0SShiva Chen 
391b014e3deSAlex Bradbury   // Allocate space on the stack if necessary.
392b014e3deSAlex Bradbury   adjustReg(MBB, MBBI, DL, SPReg, SPReg, -StackSize, MachineInstr::FrameSetup);
393b014e3deSAlex Bradbury 
39407f7c002Slewis-revill   // Emit ".cfi_def_cfa_offset RealStackSize"
39504ddf39bSHsiangkai Wang   unsigned CFIIndex = MF.addFrameInst(
3960840d725SFangrui Song       MCCFIInstruction::cfiDefCfaOffset(nullptr, RealStackSize));
39704ddf39bSHsiangkai Wang   BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
39804ddf39bSHsiangkai Wang       .addCFIIndex(CFIIndex);
39904ddf39bSHsiangkai Wang 
40007f7c002Slewis-revill   const auto &CSI = MFI.getCalleeSavedInfo();
40107f7c002Slewis-revill 
402b014e3deSAlex Bradbury   // The frame pointer is callee-saved, and code has been generated for us to
403b014e3deSAlex Bradbury   // save it to the stack. We need to skip over the storing of callee-saved
404b014e3deSAlex Bradbury   // registers as the frame pointer must be modified after it has been saved
405b014e3deSAlex Bradbury   // to the stack, not before.
406b014e3deSAlex Bradbury   // FIXME: assumes exactly one instruction is used to save each callee-saved
407b014e3deSAlex Bradbury   // register.
40807f7c002Slewis-revill   std::advance(MBBI, getNonLibcallCSI(CSI).size());
409b014e3deSAlex Bradbury 
41004ddf39bSHsiangkai Wang   // Iterate over list of callee-saved registers and emit .cfi_offset
41104ddf39bSHsiangkai Wang   // directives.
41204ddf39bSHsiangkai Wang   for (const auto &Entry : CSI) {
41307f7c002Slewis-revill     int FrameIdx = Entry.getFrameIdx();
41407f7c002Slewis-revill     int64_t Offset;
41507f7c002Slewis-revill     // Offsets for objects with fixed locations (IE: those saved by libcall) are
41607f7c002Slewis-revill     // simply calculated from the frame index.
41707f7c002Slewis-revill     if (FrameIdx < 0)
41807f7c002Slewis-revill       Offset = FrameIdx * (int64_t) STI.getXLen() / 8;
41907f7c002Slewis-revill     else
42007f7c002Slewis-revill       Offset = MFI.getObjectOffset(Entry.getFrameIdx()) -
42107f7c002Slewis-revill                RVFI->getLibCallStackSize();
422fa06e958SLuis Marques     Register Reg = Entry.getReg();
42304ddf39bSHsiangkai Wang     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
42404ddf39bSHsiangkai Wang         nullptr, RI->getDwarfRegNum(Reg, true), Offset));
42504ddf39bSHsiangkai Wang     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
42604ddf39bSHsiangkai Wang         .addCFIIndex(CFIIndex);
42704ddf39bSHsiangkai Wang   }
42804ddf39bSHsiangkai Wang 
429b014e3deSAlex Bradbury   // Generate new FP.
43004ddf39bSHsiangkai Wang   if (hasFP(MF)) {
431aed9d6d6SSimon Cook     if (STI.isRegisterReservedByUser(FPReg))
432aed9d6d6SSimon Cook       MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
433aed9d6d6SSimon Cook           MF.getFunction(), "Frame pointer required, but has been reserved."});
434aed9d6d6SSimon Cook 
4357d6aa1f7SAlex Bradbury     adjustReg(MBB, MBBI, DL, FPReg, SPReg,
43607f7c002Slewis-revill               RealStackSize - RVFI->getVarArgsSaveSize(),
43707f7c002Slewis-revill               MachineInstr::FrameSetup);
43804ddf39bSHsiangkai Wang 
4397e49dc61SFangrui Song     // Emit ".cfi_def_cfa $fp, RVFI->getVarArgsSaveSize()"
4407e49dc61SFangrui Song     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(
4417e49dc61SFangrui Song         nullptr, RI->getDwarfRegNum(FPReg, true), RVFI->getVarArgsSaveSize()));
44204ddf39bSHsiangkai Wang     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
44304ddf39bSHsiangkai Wang         .addCFIIndex(CFIIndex);
444ff55e2e0SShiva Chen   }
445cd44aee3SSam Elliott 
446ff55e2e0SShiva Chen   // Emit the second SP adjustment after saving callee saved registers.
447ff55e2e0SShiva Chen   if (FirstSPAdjustAmount) {
448ff55e2e0SShiva Chen     uint64_t SecondSPAdjustAmount = MFI.getStackSize() - FirstSPAdjustAmount;
449ff55e2e0SShiva Chen     assert(SecondSPAdjustAmount > 0 &&
450ff55e2e0SShiva Chen            "SecondSPAdjustAmount should be greater than zero");
451ff55e2e0SShiva Chen     adjustReg(MBB, MBBI, DL, SPReg, SPReg, -SecondSPAdjustAmount,
452ff55e2e0SShiva Chen               MachineInstr::FrameSetup);
4531c737f54SLuís Marques 
4541c737f54SLuís Marques     // If we are using a frame-pointer, and thus emitted ".cfi_def_cfa fp, 0",
4551c737f54SLuís Marques     // don't emit an sp-based .cfi_def_cfa_offset
4561c737f54SLuís Marques     if (!hasFP(MF)) {
457ff55e2e0SShiva Chen       // Emit ".cfi_def_cfa_offset StackSize"
458ff55e2e0SShiva Chen       unsigned CFIIndex = MF.addFrameInst(
4590840d725SFangrui Song           MCCFIInstruction::cfiDefCfaOffset(nullptr, MFI.getStackSize()));
460ff55e2e0SShiva Chen       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
461ff55e2e0SShiva Chen           .addCFIIndex(CFIIndex);
462ff55e2e0SShiva Chen     }
4631c737f54SLuís Marques   }
464ff55e2e0SShiva Chen 
465ff55e2e0SShiva Chen   if (hasFP(MF)) {
466cd44aee3SSam Elliott     // Realign Stack
467cd44aee3SSam Elliott     const RISCVRegisterInfo *RI = STI.getRegisterInfo();
468cd44aee3SSam Elliott     if (RI->needsStackRealignment(MF)) {
469d000655aSGuillaume Chatelet       Align MaxAlignment = MFI.getMaxAlign();
470cd44aee3SSam Elliott 
471cd44aee3SSam Elliott       const RISCVInstrInfo *TII = STI.getInstrInfo();
472d000655aSGuillaume Chatelet       if (isInt<12>(-(int)MaxAlignment.value())) {
473cd44aee3SSam Elliott         BuildMI(MBB, MBBI, DL, TII->get(RISCV::ANDI), SPReg)
474cd44aee3SSam Elliott             .addReg(SPReg)
475d000655aSGuillaume Chatelet             .addImm(-(int)MaxAlignment.value());
476cd44aee3SSam Elliott       } else {
477d000655aSGuillaume Chatelet         unsigned ShiftAmount = Log2(MaxAlignment);
478fa06e958SLuis Marques         Register VR =
479cd44aee3SSam Elliott             MF.getRegInfo().createVirtualRegister(&RISCV::GPRRegClass);
480cd44aee3SSam Elliott         BuildMI(MBB, MBBI, DL, TII->get(RISCV::SRLI), VR)
481cd44aee3SSam Elliott             .addReg(SPReg)
482cd44aee3SSam Elliott             .addImm(ShiftAmount);
483cd44aee3SSam Elliott         BuildMI(MBB, MBBI, DL, TII->get(RISCV::SLLI), SPReg)
484cd44aee3SSam Elliott             .addReg(VR)
485cd44aee3SSam Elliott             .addImm(ShiftAmount);
486cd44aee3SSam Elliott       }
487cf6cf0cdSShiva Chen       // FP will be used to restore the frame in the epilogue, so we need
488cf6cf0cdSShiva Chen       // another base register BP to record SP after re-alignment. SP will
489cf6cf0cdSShiva Chen       // track the current stack after allocating variable sized objects.
490cf6cf0cdSShiva Chen       if (hasBP(MF)) {
491cf6cf0cdSShiva Chen         // move BP, SP
492cf6cf0cdSShiva Chen         BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), BPReg)
493cf6cf0cdSShiva Chen             .addReg(SPReg)
494cf6cf0cdSShiva Chen             .addImm(0);
495cf6cf0cdSShiva Chen       }
496cd44aee3SSam Elliott     }
49704ddf39bSHsiangkai Wang   }
498b014e3deSAlex Bradbury }
4998971842fSAlex Bradbury 
5008971842fSAlex Bradbury void RISCVFrameLowering::emitEpilogue(MachineFunction &MF,
501b014e3deSAlex Bradbury                                       MachineBasicBlock &MBB) const {
502b014e3deSAlex Bradbury   const RISCVRegisterInfo *RI = STI.getRegisterInfo();
503b014e3deSAlex Bradbury   MachineFrameInfo &MFI = MF.getFrameInfo();
504c85be0deSAlex Bradbury   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
505fa06e958SLuis Marques   Register FPReg = getFPReg(STI);
506fa06e958SLuis Marques   Register SPReg = getSPReg(STI);
507b014e3deSAlex Bradbury 
508a8dc2110SLuís Marques   // All calls are tail calls in GHC calling conv, and functions have no
509a8dc2110SLuís Marques   // prologue/epilogue.
510a8dc2110SLuís Marques   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
511a8dc2110SLuís Marques     return;
512a8dc2110SLuís Marques 
513cd800f3bSlewis-revill   // Get the insert location for the epilogue. If there were no terminators in
514cd800f3bSlewis-revill   // the block, get the last instruction.
515cd800f3bSlewis-revill   MachineBasicBlock::iterator MBBI = MBB.end();
516cd800f3bSlewis-revill   DebugLoc DL;
517cd800f3bSlewis-revill   if (!MBB.empty()) {
518cd800f3bSlewis-revill     MBBI = MBB.getFirstTerminator();
519cd800f3bSlewis-revill     if (MBBI == MBB.end())
520cd800f3bSlewis-revill       MBBI = MBB.getLastNonDebugInstr();
521cd800f3bSlewis-revill     DL = MBBI->getDebugLoc();
522cd800f3bSlewis-revill 
523cd800f3bSlewis-revill     // If this is not a terminator, the actual insert location should be after the
524cd800f3bSlewis-revill     // last instruction.
525cd800f3bSlewis-revill     if (!MBBI->isTerminator())
526cd800f3bSlewis-revill       MBBI = std::next(MBBI);
52707f7c002Slewis-revill 
52807f7c002Slewis-revill     // If callee-saved registers are saved via libcall, place stack adjustment
52907f7c002Slewis-revill     // before this call.
53007f7c002Slewis-revill     while (MBBI != MBB.begin() &&
53107f7c002Slewis-revill            std::prev(MBBI)->getFlag(MachineInstr::FrameDestroy))
53207f7c002Slewis-revill       --MBBI;
533cd800f3bSlewis-revill   }
534cd800f3bSlewis-revill 
53507f7c002Slewis-revill   const auto &CSI = getNonLibcallCSI(MFI.getCalleeSavedInfo());
53607f7c002Slewis-revill 
537b014e3deSAlex Bradbury   // Skip to before the restores of callee-saved registers
538b014e3deSAlex Bradbury   // FIXME: assumes exactly one instruction is used to restore each
539b014e3deSAlex Bradbury   // callee-saved register.
54007f7c002Slewis-revill   auto LastFrameDestroy = MBBI;
54107f7c002Slewis-revill   if (!CSI.empty())
54207f7c002Slewis-revill     LastFrameDestroy = std::prev(MBBI, CSI.size());
543b014e3deSAlex Bradbury 
544b014e3deSAlex Bradbury   uint64_t StackSize = MFI.getStackSize();
54507f7c002Slewis-revill   uint64_t RealStackSize = StackSize + RVFI->getLibCallStackSize();
54607f7c002Slewis-revill   uint64_t FPOffset = RealStackSize - RVFI->getVarArgsSaveSize();
547b014e3deSAlex Bradbury 
548b014e3deSAlex Bradbury   // Restore the stack pointer using the value of the frame pointer. Only
549b014e3deSAlex Bradbury   // necessary if the stack pointer was modified, meaning the stack size is
550b014e3deSAlex Bradbury   // unknown.
551b014e3deSAlex Bradbury   if (RI->needsStackRealignment(MF) || MFI.hasVarSizedObjects()) {
5527d6aa1f7SAlex Bradbury     assert(hasFP(MF) && "frame pointer should not have been eliminated");
55304ddf39bSHsiangkai Wang     adjustReg(MBB, LastFrameDestroy, DL, SPReg, FPReg, -FPOffset,
554b014e3deSAlex Bradbury               MachineInstr::FrameDestroy);
555b014e3deSAlex Bradbury   }
556b014e3deSAlex Bradbury 
557ff55e2e0SShiva Chen   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
558ff55e2e0SShiva Chen   if (FirstSPAdjustAmount) {
559ff55e2e0SShiva Chen     uint64_t SecondSPAdjustAmount = MFI.getStackSize() - FirstSPAdjustAmount;
560ff55e2e0SShiva Chen     assert(SecondSPAdjustAmount > 0 &&
561ff55e2e0SShiva Chen            "SecondSPAdjustAmount should be greater than zero");
562ff55e2e0SShiva Chen 
563ff55e2e0SShiva Chen     adjustReg(MBB, LastFrameDestroy, DL, SPReg, SPReg, SecondSPAdjustAmount,
564ff55e2e0SShiva Chen               MachineInstr::FrameDestroy);
56504ddf39bSHsiangkai Wang   }
56604ddf39bSHsiangkai Wang 
567ff55e2e0SShiva Chen   if (FirstSPAdjustAmount)
568ff55e2e0SShiva Chen     StackSize = FirstSPAdjustAmount;
569ff55e2e0SShiva Chen 
570b014e3deSAlex Bradbury   // Deallocate stack
571b014e3deSAlex Bradbury   adjustReg(MBB, MBBI, DL, SPReg, SPReg, StackSize, MachineInstr::FrameDestroy);
5721c466477SZhaoshi Zheng 
5731c466477SZhaoshi Zheng   // Emit epilogue for shadow call stack.
5741c466477SZhaoshi Zheng   emitSCSEpilogue(MF, MBB, MBBI, DL);
575b014e3deSAlex Bradbury }
576660bccecSAlex Bradbury 
577d57bba7cSSander de Smalen StackOffset
578d57bba7cSSander de Smalen RISCVFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
5792481f26aSMatt Arsenault                                            Register &FrameReg) const {
580660bccecSAlex Bradbury   const MachineFrameInfo &MFI = MF.getFrameInfo();
581660bccecSAlex Bradbury   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
582c85be0deSAlex Bradbury   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
583660bccecSAlex Bradbury 
584660bccecSAlex Bradbury   // Callee-saved registers should be referenced relative to the stack
585660bccecSAlex Bradbury   // pointer (positive offset), otherwise use the frame pointer (negative
586660bccecSAlex Bradbury   // offset).
58707f7c002Slewis-revill   const auto &CSI = getNonLibcallCSI(MFI.getCalleeSavedInfo());
588660bccecSAlex Bradbury   int MinCSFI = 0;
589660bccecSAlex Bradbury   int MaxCSFI = -1;
590660bccecSAlex Bradbury 
591660bccecSAlex Bradbury   int Offset = MFI.getObjectOffset(FI) - getOffsetOfLocalArea() +
592660bccecSAlex Bradbury                MFI.getOffsetAdjustment();
593660bccecSAlex Bradbury 
594ff55e2e0SShiva Chen   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
595ff55e2e0SShiva Chen 
596660bccecSAlex Bradbury   if (CSI.size()) {
597660bccecSAlex Bradbury     MinCSFI = CSI[0].getFrameIdx();
598660bccecSAlex Bradbury     MaxCSFI = CSI[CSI.size() - 1].getFrameIdx();
599660bccecSAlex Bradbury   }
600660bccecSAlex Bradbury 
601660bccecSAlex Bradbury   if (FI >= MinCSFI && FI <= MaxCSFI) {
602660bccecSAlex Bradbury     FrameReg = RISCV::X2;
603ff55e2e0SShiva Chen 
604ff55e2e0SShiva Chen     if (FirstSPAdjustAmount)
605ff55e2e0SShiva Chen       Offset += FirstSPAdjustAmount;
606ff55e2e0SShiva Chen     else
60707f7c002Slewis-revill       Offset += MFI.getStackSize();
608cf6cf0cdSShiva Chen   } else if (RI->needsStackRealignment(MF) && !MFI.isFixedObjectIndex(FI)) {
609cd44aee3SSam Elliott     // If the stack was realigned, the frame pointer is set in order to allow
610cf6cf0cdSShiva Chen     // SP to be restored, so we need another base register to record the stack
611cf6cf0cdSShiva Chen     // after realignment.
612cf6cf0cdSShiva Chen     if (hasBP(MF))
613cf6cf0cdSShiva Chen       FrameReg = RISCVABI::getBPReg();
614cf6cf0cdSShiva Chen     else
615cd44aee3SSam Elliott       FrameReg = RISCV::X2;
61607f7c002Slewis-revill     Offset += MFI.getStackSize();
61707f7c002Slewis-revill     if (FI < 0)
61807f7c002Slewis-revill       Offset += RVFI->getLibCallStackSize();
619c85be0deSAlex Bradbury   } else {
620c85be0deSAlex Bradbury     FrameReg = RI->getFrameRegister(MF);
62107f7c002Slewis-revill     if (hasFP(MF)) {
622c85be0deSAlex Bradbury       Offset += RVFI->getVarArgsSaveSize();
62307f7c002Slewis-revill       if (FI >= 0)
62407f7c002Slewis-revill         Offset -= RVFI->getLibCallStackSize();
62507f7c002Slewis-revill     } else {
62607f7c002Slewis-revill       Offset += MFI.getStackSize();
62707f7c002Slewis-revill       if (FI < 0)
62807f7c002Slewis-revill         Offset += RVFI->getLibCallStackSize();
62907f7c002Slewis-revill     }
630660bccecSAlex Bradbury   }
631d57bba7cSSander de Smalen   return StackOffset::getFixed(Offset);
632660bccecSAlex Bradbury }
633b014e3deSAlex Bradbury 
634b014e3deSAlex Bradbury void RISCVFrameLowering::determineCalleeSaves(MachineFunction &MF,
635b014e3deSAlex Bradbury                                               BitVector &SavedRegs,
636b014e3deSAlex Bradbury                                               RegScavenger *RS) const {
637b014e3deSAlex Bradbury   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
6387d6aa1f7SAlex Bradbury   // Unconditionally spill RA and FP only if the function uses a frame
6397d6aa1f7SAlex Bradbury   // pointer.
6407d6aa1f7SAlex Bradbury   if (hasFP(MF)) {
641b014e3deSAlex Bradbury     SavedRegs.set(RISCV::X1);
642b014e3deSAlex Bradbury     SavedRegs.set(RISCV::X8);
643b014e3deSAlex Bradbury   }
644cf6cf0cdSShiva Chen   // Mark BP as used if function has dedicated base pointer.
645cf6cf0cdSShiva Chen   if (hasBP(MF))
646cf6cf0cdSShiva Chen     SavedRegs.set(RISCVABI::getBPReg());
6472e4106b7SAna Pazos 
6482e4106b7SAna Pazos   // If interrupt is enabled and there are calls in the handler,
6492e4106b7SAna Pazos   // unconditionally save all Caller-saved registers and
6502e4106b7SAna Pazos   // all FP registers, regardless whether they are used.
6512e4106b7SAna Pazos   MachineFrameInfo &MFI = MF.getFrameInfo();
6522e4106b7SAna Pazos 
6532e4106b7SAna Pazos   if (MF.getFunction().hasFnAttribute("interrupt") && MFI.hasCalls()) {
6542e4106b7SAna Pazos 
6552e4106b7SAna Pazos     static const MCPhysReg CSRegs[] = { RISCV::X1,      /* ra */
6562e4106b7SAna Pazos       RISCV::X5, RISCV::X6, RISCV::X7,                  /* t0-t2 */
6572e4106b7SAna Pazos       RISCV::X10, RISCV::X11,                           /* a0-a1, a2-a7 */
6582e4106b7SAna Pazos       RISCV::X12, RISCV::X13, RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17,
6592e4106b7SAna Pazos       RISCV::X28, RISCV::X29, RISCV::X30, RISCV::X31, 0 /* t3-t6 */
6602e4106b7SAna Pazos     };
6612e4106b7SAna Pazos 
6622e4106b7SAna Pazos     for (unsigned i = 0; CSRegs[i]; ++i)
6632e4106b7SAna Pazos       SavedRegs.set(CSRegs[i]);
6642e4106b7SAna Pazos 
665*f7bc7c29SHsiangkai Wang     if (MF.getSubtarget<RISCVSubtarget>().hasStdExtF()) {
6662e4106b7SAna Pazos 
6672e4106b7SAna Pazos       // If interrupt is enabled, this list contains all FP registers.
6682e4106b7SAna Pazos       const MCPhysReg * Regs = MF.getRegInfo().getCalleeSavedRegs();
6692e4106b7SAna Pazos 
6702e4106b7SAna Pazos       for (unsigned i = 0; Regs[i]; ++i)
671*f7bc7c29SHsiangkai Wang         if (RISCV::FPR16RegClass.contains(Regs[i]) ||
672*f7bc7c29SHsiangkai Wang             RISCV::FPR32RegClass.contains(Regs[i]) ||
6732e4106b7SAna Pazos             RISCV::FPR64RegClass.contains(Regs[i]))
6742e4106b7SAna Pazos           SavedRegs.set(Regs[i]);
6752e4106b7SAna Pazos     }
6762e4106b7SAna Pazos   }
6777d6aa1f7SAlex Bradbury }
6780715d35eSAlex Bradbury 
6790715d35eSAlex Bradbury void RISCVFrameLowering::processFunctionBeforeFrameFinalized(
6800715d35eSAlex Bradbury     MachineFunction &MF, RegScavenger *RS) const {
6810715d35eSAlex Bradbury   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
6820715d35eSAlex Bradbury   MachineFrameInfo &MFI = MF.getFrameInfo();
6830715d35eSAlex Bradbury   const TargetRegisterClass *RC = &RISCV::GPRRegClass;
6840715d35eSAlex Bradbury   // estimateStackSize has been observed to under-estimate the final stack
6850715d35eSAlex Bradbury   // size, so give ourselves wiggle-room by checking for stack size
6860715d35eSAlex Bradbury   // representable an 11-bit signed field rather than 12-bits.
6870715d35eSAlex Bradbury   // FIXME: It may be possible to craft a function with a small stack that
6880715d35eSAlex Bradbury   // still needs an emergency spill slot for branch relaxation. This case
6890715d35eSAlex Bradbury   // would currently be missed.
6900715d35eSAlex Bradbury   if (!isInt<11>(MFI.estimateStackSize(MF))) {
69128de229bSGuillaume Chatelet     int RegScavFI = MFI.CreateStackObject(RegInfo->getSpillSize(*RC),
69228de229bSGuillaume Chatelet                                           RegInfo->getSpillAlign(*RC), false);
6930715d35eSAlex Bradbury     RS->addScavengingFrameIndex(RegScavFI);
6940715d35eSAlex Bradbury   }
6950715d35eSAlex Bradbury }
696cbd498acSShiva Chen 
697cbd498acSShiva Chen // Not preserve stack space within prologue for outgoing variables when the
698cbd498acSShiva Chen // function contains variable size objects and let eliminateCallFramePseudoInstr
699cbd498acSShiva Chen // preserve stack space for it.
700cbd498acSShiva Chen bool RISCVFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
701cbd498acSShiva Chen   return !MF.getFrameInfo().hasVarSizedObjects();
702cbd498acSShiva Chen }
703cbd498acSShiva Chen 
704cbd498acSShiva Chen // Eliminate ADJCALLSTACKDOWN, ADJCALLSTACKUP pseudo instructions.
705cbd498acSShiva Chen MachineBasicBlock::iterator RISCVFrameLowering::eliminateCallFramePseudoInstr(
706cbd498acSShiva Chen     MachineFunction &MF, MachineBasicBlock &MBB,
707cbd498acSShiva Chen     MachineBasicBlock::iterator MI) const {
708fa06e958SLuis Marques   Register SPReg = RISCV::X2;
709cbd498acSShiva Chen   DebugLoc DL = MI->getDebugLoc();
710cbd498acSShiva Chen 
711cbd498acSShiva Chen   if (!hasReservedCallFrame(MF)) {
712cbd498acSShiva Chen     // If space has not been reserved for a call frame, ADJCALLSTACKDOWN and
713cbd498acSShiva Chen     // ADJCALLSTACKUP must be converted to instructions manipulating the stack
714cbd498acSShiva Chen     // pointer. This is necessary when there is a variable length stack
715cbd498acSShiva Chen     // allocation (e.g. alloca), which means it's not possible to allocate
716cbd498acSShiva Chen     // space for outgoing arguments from within the function prologue.
717cbd498acSShiva Chen     int64_t Amount = MI->getOperand(0).getImm();
718cbd498acSShiva Chen 
719cbd498acSShiva Chen     if (Amount != 0) {
720cbd498acSShiva Chen       // Ensure the stack remains aligned after adjustment.
721cbd498acSShiva Chen       Amount = alignSPAdjust(Amount);
722cbd498acSShiva Chen 
723cbd498acSShiva Chen       if (MI->getOpcode() == RISCV::ADJCALLSTACKDOWN)
724cbd498acSShiva Chen         Amount = -Amount;
725cbd498acSShiva Chen 
726cbd498acSShiva Chen       adjustReg(MBB, MI, DL, SPReg, SPReg, Amount, MachineInstr::NoFlags);
727cbd498acSShiva Chen     }
728cbd498acSShiva Chen   }
729cbd498acSShiva Chen 
730cbd498acSShiva Chen   return MBB.erase(MI);
731cbd498acSShiva Chen }
732ff55e2e0SShiva Chen 
733ff55e2e0SShiva Chen // We would like to split the SP adjustment to reduce prologue/epilogue
734ff55e2e0SShiva Chen // as following instructions. In this way, the offset of the callee saved
735ff55e2e0SShiva Chen // register could fit in a single store.
736ff55e2e0SShiva Chen //   add     sp,sp,-2032
737ff55e2e0SShiva Chen //   sw      ra,2028(sp)
738ff55e2e0SShiva Chen //   sw      s0,2024(sp)
739ff55e2e0SShiva Chen //   sw      s1,2020(sp)
740ff55e2e0SShiva Chen //   sw      s3,2012(sp)
741ff55e2e0SShiva Chen //   sw      s4,2008(sp)
742ff55e2e0SShiva Chen //   add     sp,sp,-64
743ff55e2e0SShiva Chen uint64_t
744ff55e2e0SShiva Chen RISCVFrameLowering::getFirstSPAdjustAmount(const MachineFunction &MF) const {
74507f7c002Slewis-revill   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
746ff55e2e0SShiva Chen   const MachineFrameInfo &MFI = MF.getFrameInfo();
747ff55e2e0SShiva Chen   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
748ff55e2e0SShiva Chen   uint64_t StackSize = MFI.getStackSize();
749ff55e2e0SShiva Chen 
75007f7c002Slewis-revill   // Disable SplitSPAdjust if save-restore libcall used. The callee saved
75107f7c002Slewis-revill   // registers will be pushed by the save-restore libcalls, so we don't have to
75207f7c002Slewis-revill   // split the SP adjustment in this case.
75307f7c002Slewis-revill   if (RVFI->getLibCallStackSize())
75407f7c002Slewis-revill     return 0;
75507f7c002Slewis-revill 
756ff55e2e0SShiva Chen   // Return the FirstSPAdjustAmount if the StackSize can not fit in signed
757ff55e2e0SShiva Chen   // 12-bit and there exists a callee saved register need to be pushed.
758ff55e2e0SShiva Chen   if (!isInt<12>(StackSize) && (CSI.size() > 0)) {
759ff55e2e0SShiva Chen     // FirstSPAdjustAmount is choosed as (2048 - StackAlign)
760ff55e2e0SShiva Chen     // because 2048 will cause sp = sp + 2048 in epilogue split into
761ff55e2e0SShiva Chen     // multi-instructions. The offset smaller than 2048 can fit in signle
762ff55e2e0SShiva Chen     // load/store instruction and we have to stick with the stack alignment.
763ff55e2e0SShiva Chen     // 2048 is 16-byte alignment. The stack alignment for RV32 and RV64 is 16,
764ff55e2e0SShiva Chen     // for RV32E is 4. So (2048 - StackAlign) will satisfy the stack alignment.
7653ba550a0SGuillaume Chatelet     return 2048 - getStackAlign().value();
766ff55e2e0SShiva Chen   }
767ff55e2e0SShiva Chen   return 0;
768ff55e2e0SShiva Chen }
76907f7c002Slewis-revill 
77007f7c002Slewis-revill bool RISCVFrameLowering::spillCalleeSavedRegisters(
77107f7c002Slewis-revill     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
77207f7c002Slewis-revill     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
77307f7c002Slewis-revill   if (CSI.empty())
77407f7c002Slewis-revill     return true;
77507f7c002Slewis-revill 
77607f7c002Slewis-revill   MachineFunction *MF = MBB.getParent();
77707f7c002Slewis-revill   const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
77807f7c002Slewis-revill   DebugLoc DL;
77907f7c002Slewis-revill   if (MI != MBB.end() && !MI->isDebugInstr())
78007f7c002Slewis-revill     DL = MI->getDebugLoc();
78107f7c002Slewis-revill 
78207f7c002Slewis-revill   const char *SpillLibCall = getSpillLibCallName(*MF, CSI);
78307f7c002Slewis-revill   if (SpillLibCall) {
78407f7c002Slewis-revill     // Add spill libcall via non-callee-saved register t0.
78507f7c002Slewis-revill     BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoCALLReg), RISCV::X5)
78607f7c002Slewis-revill         .addExternalSymbol(SpillLibCall, RISCVII::MO_CALL)
78707f7c002Slewis-revill         .setMIFlag(MachineInstr::FrameSetup);
78807f7c002Slewis-revill 
78907f7c002Slewis-revill     // Add registers spilled in libcall as liveins.
79007f7c002Slewis-revill     for (auto &CS : CSI)
79107f7c002Slewis-revill       MBB.addLiveIn(CS.getReg());
79207f7c002Slewis-revill   }
79307f7c002Slewis-revill 
79407f7c002Slewis-revill   // Manually spill values not spilled by libcall.
79507f7c002Slewis-revill   const auto &NonLibcallCSI = getNonLibcallCSI(CSI);
79607f7c002Slewis-revill   for (auto &CS : NonLibcallCSI) {
79707f7c002Slewis-revill     // Insert the spill to the stack frame.
79807f7c002Slewis-revill     Register Reg = CS.getReg();
79907f7c002Slewis-revill     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
80007f7c002Slewis-revill     TII.storeRegToStackSlot(MBB, MI, Reg, true, CS.getFrameIdx(), RC, TRI);
80107f7c002Slewis-revill   }
80207f7c002Slewis-revill 
80307f7c002Slewis-revill   return true;
80407f7c002Slewis-revill }
80507f7c002Slewis-revill 
80607f7c002Slewis-revill bool RISCVFrameLowering::restoreCalleeSavedRegisters(
80707f7c002Slewis-revill     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
808186dd631SBenjamin Kramer     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
80907f7c002Slewis-revill   if (CSI.empty())
81007f7c002Slewis-revill     return true;
81107f7c002Slewis-revill 
81207f7c002Slewis-revill   MachineFunction *MF = MBB.getParent();
81307f7c002Slewis-revill   const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
81407f7c002Slewis-revill   DebugLoc DL;
81507f7c002Slewis-revill   if (MI != MBB.end() && !MI->isDebugInstr())
81607f7c002Slewis-revill     DL = MI->getDebugLoc();
81707f7c002Slewis-revill 
81807f7c002Slewis-revill   // Manually restore values not restored by libcall. Insert in reverse order.
81907f7c002Slewis-revill   // loadRegFromStackSlot can insert multiple instructions.
82007f7c002Slewis-revill   const auto &NonLibcallCSI = getNonLibcallCSI(CSI);
82107f7c002Slewis-revill   for (auto &CS : reverse(NonLibcallCSI)) {
82207f7c002Slewis-revill     Register Reg = CS.getReg();
82307f7c002Slewis-revill     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
82407f7c002Slewis-revill     TII.loadRegFromStackSlot(MBB, MI, Reg, CS.getFrameIdx(), RC, TRI);
82507f7c002Slewis-revill     assert(MI != MBB.begin() && "loadRegFromStackSlot didn't insert any code!");
82607f7c002Slewis-revill   }
82707f7c002Slewis-revill 
82807f7c002Slewis-revill   const char *RestoreLibCall = getRestoreLibCallName(*MF, CSI);
82907f7c002Slewis-revill   if (RestoreLibCall) {
83007f7c002Slewis-revill     // Add restore libcall via tail call.
83107f7c002Slewis-revill     MachineBasicBlock::iterator NewMI =
83207f7c002Slewis-revill         BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoTAIL))
83307f7c002Slewis-revill             .addExternalSymbol(RestoreLibCall, RISCVII::MO_CALL)
83407f7c002Slewis-revill             .setMIFlag(MachineInstr::FrameDestroy);
83507f7c002Slewis-revill 
83607f7c002Slewis-revill     // Remove trailing returns, since the terminator is now a tail call to the
83707f7c002Slewis-revill     // restore function.
83807f7c002Slewis-revill     if (MI != MBB.end() && MI->getOpcode() == RISCV::PseudoRET) {
83907f7c002Slewis-revill       NewMI->copyImplicitOps(*MF, *MI);
84007f7c002Slewis-revill       MI->eraseFromParent();
84107f7c002Slewis-revill     }
84207f7c002Slewis-revill   }
84307f7c002Slewis-revill 
84407f7c002Slewis-revill   return true;
84507f7c002Slewis-revill }
84607f7c002Slewis-revill 
84707f7c002Slewis-revill bool RISCVFrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const {
84807f7c002Slewis-revill   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
84908649f0aSMatt Arsenault   const MachineFunction *MF = MBB.getParent();
85008649f0aSMatt Arsenault   const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
85107f7c002Slewis-revill 
85208649f0aSMatt Arsenault   if (!RVFI->useSaveRestoreLibCalls(*MF))
85307f7c002Slewis-revill     return true;
85407f7c002Slewis-revill 
85507f7c002Slewis-revill   // Inserting a call to a __riscv_save libcall requires the use of the register
85607f7c002Slewis-revill   // t0 (X5) to hold the return address. Therefore if this register is already
85707f7c002Slewis-revill   // used we can't insert the call.
85807f7c002Slewis-revill 
85907f7c002Slewis-revill   RegScavenger RS;
86007f7c002Slewis-revill   RS.enterBasicBlock(*TmpMBB);
86107f7c002Slewis-revill   return !RS.isRegUsed(RISCV::X5);
86207f7c002Slewis-revill }
86307f7c002Slewis-revill 
86407f7c002Slewis-revill bool RISCVFrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
86508649f0aSMatt Arsenault   const MachineFunction *MF = MBB.getParent();
86607f7c002Slewis-revill   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
86708649f0aSMatt Arsenault   const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
86807f7c002Slewis-revill 
86908649f0aSMatt Arsenault   if (!RVFI->useSaveRestoreLibCalls(*MF))
87007f7c002Slewis-revill     return true;
87107f7c002Slewis-revill 
87207f7c002Slewis-revill   // Using the __riscv_restore libcalls to restore CSRs requires a tail call.
87307f7c002Slewis-revill   // This means if we still need to continue executing code within this function
87407f7c002Slewis-revill   // the restore cannot take place in this basic block.
87507f7c002Slewis-revill 
87607f7c002Slewis-revill   if (MBB.succ_size() > 1)
87707f7c002Slewis-revill     return false;
87807f7c002Slewis-revill 
87907f7c002Slewis-revill   MachineBasicBlock *SuccMBB =
88007f7c002Slewis-revill       MBB.succ_empty() ? TmpMBB->getFallThrough() : *MBB.succ_begin();
88107f7c002Slewis-revill 
88207f7c002Slewis-revill   // Doing a tail call should be safe if there are no successors, because either
88307f7c002Slewis-revill   // we have a returning block or the end of the block is unreachable, so the
88407f7c002Slewis-revill   // restore will be eliminated regardless.
88507f7c002Slewis-revill   if (!SuccMBB)
88607f7c002Slewis-revill     return true;
88707f7c002Slewis-revill 
88807f7c002Slewis-revill   // The successor can only contain a return, since we would effectively be
88907f7c002Slewis-revill   // replacing the successor with our own tail return at the end of our block.
89007f7c002Slewis-revill   return SuccMBB->isReturnBlock() && SuccMBB->size() == 1;
89107f7c002Slewis-revill }
892