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 
3281c466477SZhaoshi Zheng   // Emit prologue for shadow call stack.
3291c466477SZhaoshi Zheng   emitSCSPrologue(MF, MBB, MBBI, DL);
3301c466477SZhaoshi Zheng 
33107f7c002Slewis-revill   // Since spillCalleeSavedRegisters may have inserted a libcall, skip past
33207f7c002Slewis-revill   // any instructions marked as FrameSetup
33307f7c002Slewis-revill   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
33407f7c002Slewis-revill     ++MBBI;
33507f7c002Slewis-revill 
336b014e3deSAlex Bradbury   // Determine the correct frame layout
337b014e3deSAlex Bradbury   determineFrameLayout(MF);
338b014e3deSAlex Bradbury 
33907f7c002Slewis-revill   // If libcalls are used to spill and restore callee-saved registers, the frame
34007f7c002Slewis-revill   // has two sections; the opaque section managed by the libcalls, and the
34107f7c002Slewis-revill   // section managed by MachineFrameInfo which can also hold callee saved
34207f7c002Slewis-revill   // registers in fixed stack slots, both of which have negative frame indices.
34307f7c002Slewis-revill   // This gets even more complicated when incoming arguments are passed via the
34407f7c002Slewis-revill   // stack, as these too have negative frame indices. An example is detailed
34507f7c002Slewis-revill   // below:
34607f7c002Slewis-revill   //
34707f7c002Slewis-revill   //  | incoming arg | <- FI[-3]
34807f7c002Slewis-revill   //  | libcallspill |
34907f7c002Slewis-revill   //  | calleespill  | <- FI[-2]
35007f7c002Slewis-revill   //  | calleespill  | <- FI[-1]
35107f7c002Slewis-revill   //  | this_frame   | <- FI[0]
35207f7c002Slewis-revill   //
35307f7c002Slewis-revill   // For negative frame indices, the offset from the frame pointer will differ
35407f7c002Slewis-revill   // depending on which of these groups the frame index applies to.
35507f7c002Slewis-revill   // The following calculates the correct offset knowing the number of callee
35607f7c002Slewis-revill   // saved registers spilt by the two methods.
35707f7c002Slewis-revill   if (int LibCallRegs = getLibCallID(MF, MFI.getCalleeSavedInfo()) + 1) {
35807f7c002Slewis-revill     // Calculate the size of the frame managed by the libcall. The libcalls are
35907f7c002Slewis-revill     // implemented such that the stack will always be 16 byte aligned.
36007f7c002Slewis-revill     unsigned LibCallFrameSize = alignTo((STI.getXLen() / 8) * LibCallRegs, 16);
36107f7c002Slewis-revill     RVFI->setLibCallStackSize(LibCallFrameSize);
36207f7c002Slewis-revill   }
36307f7c002Slewis-revill 
364b014e3deSAlex Bradbury   // FIXME (note copied from Lanai): This appears to be overallocating.  Needs
365b014e3deSAlex Bradbury   // investigation. Get the number of bytes to allocate from the FrameInfo.
366b014e3deSAlex Bradbury   uint64_t StackSize = MFI.getStackSize();
36707f7c002Slewis-revill   uint64_t RealStackSize = StackSize + RVFI->getLibCallStackSize();
368b014e3deSAlex Bradbury 
369b014e3deSAlex Bradbury   // Early exit if there is no need to allocate on the stack
37007f7c002Slewis-revill   if (RealStackSize == 0 && !MFI.adjustsStack())
371b014e3deSAlex Bradbury     return;
372b014e3deSAlex Bradbury 
373aed9d6d6SSimon Cook   // If the stack pointer has been marked as reserved, then produce an error if
374aed9d6d6SSimon Cook   // the frame requires stack allocation
375aed9d6d6SSimon Cook   if (STI.isRegisterReservedByUser(SPReg))
376aed9d6d6SSimon Cook     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
377aed9d6d6SSimon Cook         MF.getFunction(), "Stack pointer required, but has been reserved."});
378aed9d6d6SSimon Cook 
379ff55e2e0SShiva Chen   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
380ff55e2e0SShiva Chen   // Split the SP adjustment to reduce the offsets of callee saved spill.
38107f7c002Slewis-revill   if (FirstSPAdjustAmount) {
382ff55e2e0SShiva Chen     StackSize = FirstSPAdjustAmount;
38307f7c002Slewis-revill     RealStackSize = FirstSPAdjustAmount;
38407f7c002Slewis-revill   }
385ff55e2e0SShiva Chen 
386b014e3deSAlex Bradbury   // Allocate space on the stack if necessary.
387b014e3deSAlex Bradbury   adjustReg(MBB, MBBI, DL, SPReg, SPReg, -StackSize, MachineInstr::FrameSetup);
388b014e3deSAlex Bradbury 
38907f7c002Slewis-revill   // Emit ".cfi_def_cfa_offset RealStackSize"
39004ddf39bSHsiangkai Wang   unsigned CFIIndex = MF.addFrameInst(
3910840d725SFangrui Song       MCCFIInstruction::cfiDefCfaOffset(nullptr, RealStackSize));
39204ddf39bSHsiangkai Wang   BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
39304ddf39bSHsiangkai Wang       .addCFIIndex(CFIIndex);
39404ddf39bSHsiangkai Wang 
39507f7c002Slewis-revill   const auto &CSI = MFI.getCalleeSavedInfo();
39607f7c002Slewis-revill 
397b014e3deSAlex Bradbury   // The frame pointer is callee-saved, and code has been generated for us to
398b014e3deSAlex Bradbury   // save it to the stack. We need to skip over the storing of callee-saved
399b014e3deSAlex Bradbury   // registers as the frame pointer must be modified after it has been saved
400b014e3deSAlex Bradbury   // to the stack, not before.
401b014e3deSAlex Bradbury   // FIXME: assumes exactly one instruction is used to save each callee-saved
402b014e3deSAlex Bradbury   // register.
40307f7c002Slewis-revill   std::advance(MBBI, getNonLibcallCSI(CSI).size());
404b014e3deSAlex Bradbury 
40504ddf39bSHsiangkai Wang   // Iterate over list of callee-saved registers and emit .cfi_offset
40604ddf39bSHsiangkai Wang   // directives.
40704ddf39bSHsiangkai Wang   for (const auto &Entry : CSI) {
40807f7c002Slewis-revill     int FrameIdx = Entry.getFrameIdx();
40907f7c002Slewis-revill     int64_t Offset;
41007f7c002Slewis-revill     // Offsets for objects with fixed locations (IE: those saved by libcall) are
41107f7c002Slewis-revill     // simply calculated from the frame index.
41207f7c002Slewis-revill     if (FrameIdx < 0)
41307f7c002Slewis-revill       Offset = FrameIdx * (int64_t) STI.getXLen() / 8;
41407f7c002Slewis-revill     else
41507f7c002Slewis-revill       Offset = MFI.getObjectOffset(Entry.getFrameIdx()) -
41607f7c002Slewis-revill                RVFI->getLibCallStackSize();
417fa06e958SLuis Marques     Register Reg = Entry.getReg();
41804ddf39bSHsiangkai Wang     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
41904ddf39bSHsiangkai Wang         nullptr, RI->getDwarfRegNum(Reg, true), Offset));
42004ddf39bSHsiangkai Wang     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
42104ddf39bSHsiangkai Wang         .addCFIIndex(CFIIndex);
42204ddf39bSHsiangkai Wang   }
42304ddf39bSHsiangkai Wang 
424b014e3deSAlex Bradbury   // Generate new FP.
42504ddf39bSHsiangkai Wang   if (hasFP(MF)) {
426aed9d6d6SSimon Cook     if (STI.isRegisterReservedByUser(FPReg))
427aed9d6d6SSimon Cook       MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
428aed9d6d6SSimon Cook           MF.getFunction(), "Frame pointer required, but has been reserved."});
429aed9d6d6SSimon Cook 
4307d6aa1f7SAlex Bradbury     adjustReg(MBB, MBBI, DL, FPReg, SPReg,
43107f7c002Slewis-revill               RealStackSize - RVFI->getVarArgsSaveSize(),
43207f7c002Slewis-revill               MachineInstr::FrameSetup);
43304ddf39bSHsiangkai Wang 
4347e49dc61SFangrui Song     // Emit ".cfi_def_cfa $fp, RVFI->getVarArgsSaveSize()"
4357e49dc61SFangrui Song     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(
4367e49dc61SFangrui Song         nullptr, RI->getDwarfRegNum(FPReg, true), RVFI->getVarArgsSaveSize()));
43704ddf39bSHsiangkai Wang     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
43804ddf39bSHsiangkai Wang         .addCFIIndex(CFIIndex);
439ff55e2e0SShiva Chen   }
440cd44aee3SSam Elliott 
441ff55e2e0SShiva Chen   // Emit the second SP adjustment after saving callee saved registers.
442ff55e2e0SShiva Chen   if (FirstSPAdjustAmount) {
443ff55e2e0SShiva Chen     uint64_t SecondSPAdjustAmount = MFI.getStackSize() - FirstSPAdjustAmount;
444ff55e2e0SShiva Chen     assert(SecondSPAdjustAmount > 0 &&
445ff55e2e0SShiva Chen            "SecondSPAdjustAmount should be greater than zero");
446ff55e2e0SShiva Chen     adjustReg(MBB, MBBI, DL, SPReg, SPReg, -SecondSPAdjustAmount,
447ff55e2e0SShiva Chen               MachineInstr::FrameSetup);
4481c737f54SLuís Marques 
4491c737f54SLuís Marques     // If we are using a frame-pointer, and thus emitted ".cfi_def_cfa fp, 0",
4501c737f54SLuís Marques     // don't emit an sp-based .cfi_def_cfa_offset
4511c737f54SLuís Marques     if (!hasFP(MF)) {
452ff55e2e0SShiva Chen       // Emit ".cfi_def_cfa_offset StackSize"
453ff55e2e0SShiva Chen       unsigned CFIIndex = MF.addFrameInst(
4540840d725SFangrui Song           MCCFIInstruction::cfiDefCfaOffset(nullptr, MFI.getStackSize()));
455ff55e2e0SShiva Chen       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
456ff55e2e0SShiva Chen           .addCFIIndex(CFIIndex);
457ff55e2e0SShiva Chen     }
4581c737f54SLuís Marques   }
459ff55e2e0SShiva Chen 
460ff55e2e0SShiva Chen   if (hasFP(MF)) {
461cd44aee3SSam Elliott     // Realign Stack
462cd44aee3SSam Elliott     const RISCVRegisterInfo *RI = STI.getRegisterInfo();
463cd44aee3SSam Elliott     if (RI->needsStackRealignment(MF)) {
464d000655aSGuillaume Chatelet       Align MaxAlignment = MFI.getMaxAlign();
465cd44aee3SSam Elliott 
466cd44aee3SSam Elliott       const RISCVInstrInfo *TII = STI.getInstrInfo();
467d000655aSGuillaume Chatelet       if (isInt<12>(-(int)MaxAlignment.value())) {
468cd44aee3SSam Elliott         BuildMI(MBB, MBBI, DL, TII->get(RISCV::ANDI), SPReg)
469cd44aee3SSam Elliott             .addReg(SPReg)
470d000655aSGuillaume Chatelet             .addImm(-(int)MaxAlignment.value());
471cd44aee3SSam Elliott       } else {
472d000655aSGuillaume Chatelet         unsigned ShiftAmount = Log2(MaxAlignment);
473fa06e958SLuis Marques         Register VR =
474cd44aee3SSam Elliott             MF.getRegInfo().createVirtualRegister(&RISCV::GPRRegClass);
475cd44aee3SSam Elliott         BuildMI(MBB, MBBI, DL, TII->get(RISCV::SRLI), VR)
476cd44aee3SSam Elliott             .addReg(SPReg)
477cd44aee3SSam Elliott             .addImm(ShiftAmount);
478cd44aee3SSam Elliott         BuildMI(MBB, MBBI, DL, TII->get(RISCV::SLLI), SPReg)
479cd44aee3SSam Elliott             .addReg(VR)
480cd44aee3SSam Elliott             .addImm(ShiftAmount);
481cd44aee3SSam Elliott       }
482cf6cf0cdSShiva Chen       // FP will be used to restore the frame in the epilogue, so we need
483cf6cf0cdSShiva Chen       // another base register BP to record SP after re-alignment. SP will
484cf6cf0cdSShiva Chen       // track the current stack after allocating variable sized objects.
485cf6cf0cdSShiva Chen       if (hasBP(MF)) {
486cf6cf0cdSShiva Chen         // move BP, SP
487cf6cf0cdSShiva Chen         BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), BPReg)
488cf6cf0cdSShiva Chen             .addReg(SPReg)
489cf6cf0cdSShiva Chen             .addImm(0);
490cf6cf0cdSShiva Chen       }
491cd44aee3SSam Elliott     }
49204ddf39bSHsiangkai Wang   }
493b014e3deSAlex Bradbury }
4948971842fSAlex Bradbury 
4958971842fSAlex Bradbury void RISCVFrameLowering::emitEpilogue(MachineFunction &MF,
496b014e3deSAlex Bradbury                                       MachineBasicBlock &MBB) const {
497b014e3deSAlex Bradbury   const RISCVRegisterInfo *RI = STI.getRegisterInfo();
498b014e3deSAlex Bradbury   MachineFrameInfo &MFI = MF.getFrameInfo();
499c85be0deSAlex Bradbury   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
500fa06e958SLuis Marques   Register FPReg = getFPReg(STI);
501fa06e958SLuis Marques   Register SPReg = getSPReg(STI);
502b014e3deSAlex Bradbury 
503cd800f3bSlewis-revill   // Get the insert location for the epilogue. If there were no terminators in
504cd800f3bSlewis-revill   // the block, get the last instruction.
505cd800f3bSlewis-revill   MachineBasicBlock::iterator MBBI = MBB.end();
506cd800f3bSlewis-revill   DebugLoc DL;
507cd800f3bSlewis-revill   if (!MBB.empty()) {
508cd800f3bSlewis-revill     MBBI = MBB.getFirstTerminator();
509cd800f3bSlewis-revill     if (MBBI == MBB.end())
510cd800f3bSlewis-revill       MBBI = MBB.getLastNonDebugInstr();
511cd800f3bSlewis-revill     DL = MBBI->getDebugLoc();
512cd800f3bSlewis-revill 
513cd800f3bSlewis-revill     // If this is not a terminator, the actual insert location should be after the
514cd800f3bSlewis-revill     // last instruction.
515cd800f3bSlewis-revill     if (!MBBI->isTerminator())
516cd800f3bSlewis-revill       MBBI = std::next(MBBI);
51707f7c002Slewis-revill 
51807f7c002Slewis-revill     // If callee-saved registers are saved via libcall, place stack adjustment
51907f7c002Slewis-revill     // before this call.
52007f7c002Slewis-revill     while (MBBI != MBB.begin() &&
52107f7c002Slewis-revill            std::prev(MBBI)->getFlag(MachineInstr::FrameDestroy))
52207f7c002Slewis-revill       --MBBI;
523cd800f3bSlewis-revill   }
524cd800f3bSlewis-revill 
52507f7c002Slewis-revill   const auto &CSI = getNonLibcallCSI(MFI.getCalleeSavedInfo());
52607f7c002Slewis-revill 
527b014e3deSAlex Bradbury   // Skip to before the restores of callee-saved registers
528b014e3deSAlex Bradbury   // FIXME: assumes exactly one instruction is used to restore each
529b014e3deSAlex Bradbury   // callee-saved register.
53007f7c002Slewis-revill   auto LastFrameDestroy = MBBI;
53107f7c002Slewis-revill   if (!CSI.empty())
53207f7c002Slewis-revill     LastFrameDestroy = std::prev(MBBI, CSI.size());
533b014e3deSAlex Bradbury 
534b014e3deSAlex Bradbury   uint64_t StackSize = MFI.getStackSize();
53507f7c002Slewis-revill   uint64_t RealStackSize = StackSize + RVFI->getLibCallStackSize();
53607f7c002Slewis-revill   uint64_t FPOffset = RealStackSize - RVFI->getVarArgsSaveSize();
537b014e3deSAlex Bradbury 
538b014e3deSAlex Bradbury   // Restore the stack pointer using the value of the frame pointer. Only
539b014e3deSAlex Bradbury   // necessary if the stack pointer was modified, meaning the stack size is
540b014e3deSAlex Bradbury   // unknown.
541b014e3deSAlex Bradbury   if (RI->needsStackRealignment(MF) || MFI.hasVarSizedObjects()) {
5427d6aa1f7SAlex Bradbury     assert(hasFP(MF) && "frame pointer should not have been eliminated");
54304ddf39bSHsiangkai Wang     adjustReg(MBB, LastFrameDestroy, DL, SPReg, FPReg, -FPOffset,
544b014e3deSAlex Bradbury               MachineInstr::FrameDestroy);
545b014e3deSAlex Bradbury   }
546b014e3deSAlex Bradbury 
547ff55e2e0SShiva Chen   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
548ff55e2e0SShiva Chen   if (FirstSPAdjustAmount) {
549ff55e2e0SShiva Chen     uint64_t SecondSPAdjustAmount = MFI.getStackSize() - FirstSPAdjustAmount;
550ff55e2e0SShiva Chen     assert(SecondSPAdjustAmount > 0 &&
551ff55e2e0SShiva Chen            "SecondSPAdjustAmount should be greater than zero");
552ff55e2e0SShiva Chen 
553ff55e2e0SShiva Chen     adjustReg(MBB, LastFrameDestroy, DL, SPReg, SPReg, SecondSPAdjustAmount,
554ff55e2e0SShiva Chen               MachineInstr::FrameDestroy);
55504ddf39bSHsiangkai Wang   }
55604ddf39bSHsiangkai Wang 
557ff55e2e0SShiva Chen   if (FirstSPAdjustAmount)
558ff55e2e0SShiva Chen     StackSize = FirstSPAdjustAmount;
559ff55e2e0SShiva Chen 
560b014e3deSAlex Bradbury   // Deallocate stack
561b014e3deSAlex Bradbury   adjustReg(MBB, MBBI, DL, SPReg, SPReg, StackSize, MachineInstr::FrameDestroy);
5621c466477SZhaoshi Zheng 
5631c466477SZhaoshi Zheng   // Emit epilogue for shadow call stack.
5641c466477SZhaoshi Zheng   emitSCSEpilogue(MF, MBB, MBBI, DL);
565b014e3deSAlex Bradbury }
566660bccecSAlex Bradbury 
567*d57bba7cSSander de Smalen StackOffset
568*d57bba7cSSander de Smalen RISCVFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
5692481f26aSMatt Arsenault                                            Register &FrameReg) const {
570660bccecSAlex Bradbury   const MachineFrameInfo &MFI = MF.getFrameInfo();
571660bccecSAlex Bradbury   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
572c85be0deSAlex Bradbury   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
573660bccecSAlex Bradbury 
574660bccecSAlex Bradbury   // Callee-saved registers should be referenced relative to the stack
575660bccecSAlex Bradbury   // pointer (positive offset), otherwise use the frame pointer (negative
576660bccecSAlex Bradbury   // offset).
57707f7c002Slewis-revill   const auto &CSI = getNonLibcallCSI(MFI.getCalleeSavedInfo());
578660bccecSAlex Bradbury   int MinCSFI = 0;
579660bccecSAlex Bradbury   int MaxCSFI = -1;
580660bccecSAlex Bradbury 
581660bccecSAlex Bradbury   int Offset = MFI.getObjectOffset(FI) - getOffsetOfLocalArea() +
582660bccecSAlex Bradbury                MFI.getOffsetAdjustment();
583660bccecSAlex Bradbury 
584ff55e2e0SShiva Chen   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
585ff55e2e0SShiva Chen 
586660bccecSAlex Bradbury   if (CSI.size()) {
587660bccecSAlex Bradbury     MinCSFI = CSI[0].getFrameIdx();
588660bccecSAlex Bradbury     MaxCSFI = CSI[CSI.size() - 1].getFrameIdx();
589660bccecSAlex Bradbury   }
590660bccecSAlex Bradbury 
591660bccecSAlex Bradbury   if (FI >= MinCSFI && FI <= MaxCSFI) {
592660bccecSAlex Bradbury     FrameReg = RISCV::X2;
593ff55e2e0SShiva Chen 
594ff55e2e0SShiva Chen     if (FirstSPAdjustAmount)
595ff55e2e0SShiva Chen       Offset += FirstSPAdjustAmount;
596ff55e2e0SShiva Chen     else
59707f7c002Slewis-revill       Offset += MFI.getStackSize();
598cf6cf0cdSShiva Chen   } else if (RI->needsStackRealignment(MF) && !MFI.isFixedObjectIndex(FI)) {
599cd44aee3SSam Elliott     // If the stack was realigned, the frame pointer is set in order to allow
600cf6cf0cdSShiva Chen     // SP to be restored, so we need another base register to record the stack
601cf6cf0cdSShiva Chen     // after realignment.
602cf6cf0cdSShiva Chen     if (hasBP(MF))
603cf6cf0cdSShiva Chen       FrameReg = RISCVABI::getBPReg();
604cf6cf0cdSShiva Chen     else
605cd44aee3SSam Elliott       FrameReg = RISCV::X2;
60607f7c002Slewis-revill     Offset += MFI.getStackSize();
60707f7c002Slewis-revill     if (FI < 0)
60807f7c002Slewis-revill       Offset += RVFI->getLibCallStackSize();
609c85be0deSAlex Bradbury   } else {
610c85be0deSAlex Bradbury     FrameReg = RI->getFrameRegister(MF);
61107f7c002Slewis-revill     if (hasFP(MF)) {
612c85be0deSAlex Bradbury       Offset += RVFI->getVarArgsSaveSize();
61307f7c002Slewis-revill       if (FI >= 0)
61407f7c002Slewis-revill         Offset -= RVFI->getLibCallStackSize();
61507f7c002Slewis-revill     } else {
61607f7c002Slewis-revill       Offset += MFI.getStackSize();
61707f7c002Slewis-revill       if (FI < 0)
61807f7c002Slewis-revill         Offset += RVFI->getLibCallStackSize();
61907f7c002Slewis-revill     }
620660bccecSAlex Bradbury   }
621*d57bba7cSSander de Smalen   return StackOffset::getFixed(Offset);
622660bccecSAlex Bradbury }
623b014e3deSAlex Bradbury 
624b014e3deSAlex Bradbury void RISCVFrameLowering::determineCalleeSaves(MachineFunction &MF,
625b014e3deSAlex Bradbury                                               BitVector &SavedRegs,
626b014e3deSAlex Bradbury                                               RegScavenger *RS) const {
627b014e3deSAlex Bradbury   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
6287d6aa1f7SAlex Bradbury   // Unconditionally spill RA and FP only if the function uses a frame
6297d6aa1f7SAlex Bradbury   // pointer.
6307d6aa1f7SAlex Bradbury   if (hasFP(MF)) {
631b014e3deSAlex Bradbury     SavedRegs.set(RISCV::X1);
632b014e3deSAlex Bradbury     SavedRegs.set(RISCV::X8);
633b014e3deSAlex Bradbury   }
634cf6cf0cdSShiva Chen   // Mark BP as used if function has dedicated base pointer.
635cf6cf0cdSShiva Chen   if (hasBP(MF))
636cf6cf0cdSShiva Chen     SavedRegs.set(RISCVABI::getBPReg());
6372e4106b7SAna Pazos 
6382e4106b7SAna Pazos   // If interrupt is enabled and there are calls in the handler,
6392e4106b7SAna Pazos   // unconditionally save all Caller-saved registers and
6402e4106b7SAna Pazos   // all FP registers, regardless whether they are used.
6412e4106b7SAna Pazos   MachineFrameInfo &MFI = MF.getFrameInfo();
6422e4106b7SAna Pazos 
6432e4106b7SAna Pazos   if (MF.getFunction().hasFnAttribute("interrupt") && MFI.hasCalls()) {
6442e4106b7SAna Pazos 
6452e4106b7SAna Pazos     static const MCPhysReg CSRegs[] = { RISCV::X1,      /* ra */
6462e4106b7SAna Pazos       RISCV::X5, RISCV::X6, RISCV::X7,                  /* t0-t2 */
6472e4106b7SAna Pazos       RISCV::X10, RISCV::X11,                           /* a0-a1, a2-a7 */
6482e4106b7SAna Pazos       RISCV::X12, RISCV::X13, RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17,
6492e4106b7SAna Pazos       RISCV::X28, RISCV::X29, RISCV::X30, RISCV::X31, 0 /* t3-t6 */
6502e4106b7SAna Pazos     };
6512e4106b7SAna Pazos 
6522e4106b7SAna Pazos     for (unsigned i = 0; CSRegs[i]; ++i)
6532e4106b7SAna Pazos       SavedRegs.set(CSRegs[i]);
6542e4106b7SAna Pazos 
6552e4106b7SAna Pazos     if (MF.getSubtarget<RISCVSubtarget>().hasStdExtD() ||
6562e4106b7SAna Pazos         MF.getSubtarget<RISCVSubtarget>().hasStdExtF()) {
6572e4106b7SAna Pazos 
6582e4106b7SAna Pazos       // If interrupt is enabled, this list contains all FP registers.
6592e4106b7SAna Pazos       const MCPhysReg * Regs = MF.getRegInfo().getCalleeSavedRegs();
6602e4106b7SAna Pazos 
6612e4106b7SAna Pazos       for (unsigned i = 0; Regs[i]; ++i)
6622e4106b7SAna Pazos         if (RISCV::FPR32RegClass.contains(Regs[i]) ||
6632e4106b7SAna Pazos             RISCV::FPR64RegClass.contains(Regs[i]))
6642e4106b7SAna Pazos           SavedRegs.set(Regs[i]);
6652e4106b7SAna Pazos     }
6662e4106b7SAna Pazos   }
6677d6aa1f7SAlex Bradbury }
6680715d35eSAlex Bradbury 
6690715d35eSAlex Bradbury void RISCVFrameLowering::processFunctionBeforeFrameFinalized(
6700715d35eSAlex Bradbury     MachineFunction &MF, RegScavenger *RS) const {
6710715d35eSAlex Bradbury   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
6720715d35eSAlex Bradbury   MachineFrameInfo &MFI = MF.getFrameInfo();
6730715d35eSAlex Bradbury   const TargetRegisterClass *RC = &RISCV::GPRRegClass;
6740715d35eSAlex Bradbury   // estimateStackSize has been observed to under-estimate the final stack
6750715d35eSAlex Bradbury   // size, so give ourselves wiggle-room by checking for stack size
6760715d35eSAlex Bradbury   // representable an 11-bit signed field rather than 12-bits.
6770715d35eSAlex Bradbury   // FIXME: It may be possible to craft a function with a small stack that
6780715d35eSAlex Bradbury   // still needs an emergency spill slot for branch relaxation. This case
6790715d35eSAlex Bradbury   // would currently be missed.
6800715d35eSAlex Bradbury   if (!isInt<11>(MFI.estimateStackSize(MF))) {
68128de229bSGuillaume Chatelet     int RegScavFI = MFI.CreateStackObject(RegInfo->getSpillSize(*RC),
68228de229bSGuillaume Chatelet                                           RegInfo->getSpillAlign(*RC), false);
6830715d35eSAlex Bradbury     RS->addScavengingFrameIndex(RegScavFI);
6840715d35eSAlex Bradbury   }
6850715d35eSAlex Bradbury }
686cbd498acSShiva Chen 
687cbd498acSShiva Chen // Not preserve stack space within prologue for outgoing variables when the
688cbd498acSShiva Chen // function contains variable size objects and let eliminateCallFramePseudoInstr
689cbd498acSShiva Chen // preserve stack space for it.
690cbd498acSShiva Chen bool RISCVFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
691cbd498acSShiva Chen   return !MF.getFrameInfo().hasVarSizedObjects();
692cbd498acSShiva Chen }
693cbd498acSShiva Chen 
694cbd498acSShiva Chen // Eliminate ADJCALLSTACKDOWN, ADJCALLSTACKUP pseudo instructions.
695cbd498acSShiva Chen MachineBasicBlock::iterator RISCVFrameLowering::eliminateCallFramePseudoInstr(
696cbd498acSShiva Chen     MachineFunction &MF, MachineBasicBlock &MBB,
697cbd498acSShiva Chen     MachineBasicBlock::iterator MI) const {
698fa06e958SLuis Marques   Register SPReg = RISCV::X2;
699cbd498acSShiva Chen   DebugLoc DL = MI->getDebugLoc();
700cbd498acSShiva Chen 
701cbd498acSShiva Chen   if (!hasReservedCallFrame(MF)) {
702cbd498acSShiva Chen     // If space has not been reserved for a call frame, ADJCALLSTACKDOWN and
703cbd498acSShiva Chen     // ADJCALLSTACKUP must be converted to instructions manipulating the stack
704cbd498acSShiva Chen     // pointer. This is necessary when there is a variable length stack
705cbd498acSShiva Chen     // allocation (e.g. alloca), which means it's not possible to allocate
706cbd498acSShiva Chen     // space for outgoing arguments from within the function prologue.
707cbd498acSShiva Chen     int64_t Amount = MI->getOperand(0).getImm();
708cbd498acSShiva Chen 
709cbd498acSShiva Chen     if (Amount != 0) {
710cbd498acSShiva Chen       // Ensure the stack remains aligned after adjustment.
711cbd498acSShiva Chen       Amount = alignSPAdjust(Amount);
712cbd498acSShiva Chen 
713cbd498acSShiva Chen       if (MI->getOpcode() == RISCV::ADJCALLSTACKDOWN)
714cbd498acSShiva Chen         Amount = -Amount;
715cbd498acSShiva Chen 
716cbd498acSShiva Chen       adjustReg(MBB, MI, DL, SPReg, SPReg, Amount, MachineInstr::NoFlags);
717cbd498acSShiva Chen     }
718cbd498acSShiva Chen   }
719cbd498acSShiva Chen 
720cbd498acSShiva Chen   return MBB.erase(MI);
721cbd498acSShiva Chen }
722ff55e2e0SShiva Chen 
723ff55e2e0SShiva Chen // We would like to split the SP adjustment to reduce prologue/epilogue
724ff55e2e0SShiva Chen // as following instructions. In this way, the offset of the callee saved
725ff55e2e0SShiva Chen // register could fit in a single store.
726ff55e2e0SShiva Chen //   add     sp,sp,-2032
727ff55e2e0SShiva Chen //   sw      ra,2028(sp)
728ff55e2e0SShiva Chen //   sw      s0,2024(sp)
729ff55e2e0SShiva Chen //   sw      s1,2020(sp)
730ff55e2e0SShiva Chen //   sw      s3,2012(sp)
731ff55e2e0SShiva Chen //   sw      s4,2008(sp)
732ff55e2e0SShiva Chen //   add     sp,sp,-64
733ff55e2e0SShiva Chen uint64_t
734ff55e2e0SShiva Chen RISCVFrameLowering::getFirstSPAdjustAmount(const MachineFunction &MF) const {
73507f7c002Slewis-revill   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
736ff55e2e0SShiva Chen   const MachineFrameInfo &MFI = MF.getFrameInfo();
737ff55e2e0SShiva Chen   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
738ff55e2e0SShiva Chen   uint64_t StackSize = MFI.getStackSize();
739ff55e2e0SShiva Chen 
74007f7c002Slewis-revill   // Disable SplitSPAdjust if save-restore libcall used. The callee saved
74107f7c002Slewis-revill   // registers will be pushed by the save-restore libcalls, so we don't have to
74207f7c002Slewis-revill   // split the SP adjustment in this case.
74307f7c002Slewis-revill   if (RVFI->getLibCallStackSize())
74407f7c002Slewis-revill     return 0;
74507f7c002Slewis-revill 
746ff55e2e0SShiva Chen   // Return the FirstSPAdjustAmount if the StackSize can not fit in signed
747ff55e2e0SShiva Chen   // 12-bit and there exists a callee saved register need to be pushed.
748ff55e2e0SShiva Chen   if (!isInt<12>(StackSize) && (CSI.size() > 0)) {
749ff55e2e0SShiva Chen     // FirstSPAdjustAmount is choosed as (2048 - StackAlign)
750ff55e2e0SShiva Chen     // because 2048 will cause sp = sp + 2048 in epilogue split into
751ff55e2e0SShiva Chen     // multi-instructions. The offset smaller than 2048 can fit in signle
752ff55e2e0SShiva Chen     // load/store instruction and we have to stick with the stack alignment.
753ff55e2e0SShiva Chen     // 2048 is 16-byte alignment. The stack alignment for RV32 and RV64 is 16,
754ff55e2e0SShiva Chen     // for RV32E is 4. So (2048 - StackAlign) will satisfy the stack alignment.
7553ba550a0SGuillaume Chatelet     return 2048 - getStackAlign().value();
756ff55e2e0SShiva Chen   }
757ff55e2e0SShiva Chen   return 0;
758ff55e2e0SShiva Chen }
75907f7c002Slewis-revill 
76007f7c002Slewis-revill bool RISCVFrameLowering::spillCalleeSavedRegisters(
76107f7c002Slewis-revill     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
76207f7c002Slewis-revill     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
76307f7c002Slewis-revill   if (CSI.empty())
76407f7c002Slewis-revill     return true;
76507f7c002Slewis-revill 
76607f7c002Slewis-revill   MachineFunction *MF = MBB.getParent();
76707f7c002Slewis-revill   const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
76807f7c002Slewis-revill   DebugLoc DL;
76907f7c002Slewis-revill   if (MI != MBB.end() && !MI->isDebugInstr())
77007f7c002Slewis-revill     DL = MI->getDebugLoc();
77107f7c002Slewis-revill 
77207f7c002Slewis-revill   const char *SpillLibCall = getSpillLibCallName(*MF, CSI);
77307f7c002Slewis-revill   if (SpillLibCall) {
77407f7c002Slewis-revill     // Add spill libcall via non-callee-saved register t0.
77507f7c002Slewis-revill     BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoCALLReg), RISCV::X5)
77607f7c002Slewis-revill         .addExternalSymbol(SpillLibCall, RISCVII::MO_CALL)
77707f7c002Slewis-revill         .setMIFlag(MachineInstr::FrameSetup);
77807f7c002Slewis-revill 
77907f7c002Slewis-revill     // Add registers spilled in libcall as liveins.
78007f7c002Slewis-revill     for (auto &CS : CSI)
78107f7c002Slewis-revill       MBB.addLiveIn(CS.getReg());
78207f7c002Slewis-revill   }
78307f7c002Slewis-revill 
78407f7c002Slewis-revill   // Manually spill values not spilled by libcall.
78507f7c002Slewis-revill   const auto &NonLibcallCSI = getNonLibcallCSI(CSI);
78607f7c002Slewis-revill   for (auto &CS : NonLibcallCSI) {
78707f7c002Slewis-revill     // Insert the spill to the stack frame.
78807f7c002Slewis-revill     Register Reg = CS.getReg();
78907f7c002Slewis-revill     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
79007f7c002Slewis-revill     TII.storeRegToStackSlot(MBB, MI, Reg, true, CS.getFrameIdx(), RC, TRI);
79107f7c002Slewis-revill   }
79207f7c002Slewis-revill 
79307f7c002Slewis-revill   return true;
79407f7c002Slewis-revill }
79507f7c002Slewis-revill 
79607f7c002Slewis-revill bool RISCVFrameLowering::restoreCalleeSavedRegisters(
79707f7c002Slewis-revill     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
798186dd631SBenjamin Kramer     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
79907f7c002Slewis-revill   if (CSI.empty())
80007f7c002Slewis-revill     return true;
80107f7c002Slewis-revill 
80207f7c002Slewis-revill   MachineFunction *MF = MBB.getParent();
80307f7c002Slewis-revill   const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
80407f7c002Slewis-revill   DebugLoc DL;
80507f7c002Slewis-revill   if (MI != MBB.end() && !MI->isDebugInstr())
80607f7c002Slewis-revill     DL = MI->getDebugLoc();
80707f7c002Slewis-revill 
80807f7c002Slewis-revill   // Manually restore values not restored by libcall. Insert in reverse order.
80907f7c002Slewis-revill   // loadRegFromStackSlot can insert multiple instructions.
81007f7c002Slewis-revill   const auto &NonLibcallCSI = getNonLibcallCSI(CSI);
81107f7c002Slewis-revill   for (auto &CS : reverse(NonLibcallCSI)) {
81207f7c002Slewis-revill     Register Reg = CS.getReg();
81307f7c002Slewis-revill     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
81407f7c002Slewis-revill     TII.loadRegFromStackSlot(MBB, MI, Reg, CS.getFrameIdx(), RC, TRI);
81507f7c002Slewis-revill     assert(MI != MBB.begin() && "loadRegFromStackSlot didn't insert any code!");
81607f7c002Slewis-revill   }
81707f7c002Slewis-revill 
81807f7c002Slewis-revill   const char *RestoreLibCall = getRestoreLibCallName(*MF, CSI);
81907f7c002Slewis-revill   if (RestoreLibCall) {
82007f7c002Slewis-revill     // Add restore libcall via tail call.
82107f7c002Slewis-revill     MachineBasicBlock::iterator NewMI =
82207f7c002Slewis-revill         BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoTAIL))
82307f7c002Slewis-revill             .addExternalSymbol(RestoreLibCall, RISCVII::MO_CALL)
82407f7c002Slewis-revill             .setMIFlag(MachineInstr::FrameDestroy);
82507f7c002Slewis-revill 
82607f7c002Slewis-revill     // Remove trailing returns, since the terminator is now a tail call to the
82707f7c002Slewis-revill     // restore function.
82807f7c002Slewis-revill     if (MI != MBB.end() && MI->getOpcode() == RISCV::PseudoRET) {
82907f7c002Slewis-revill       NewMI->copyImplicitOps(*MF, *MI);
83007f7c002Slewis-revill       MI->eraseFromParent();
83107f7c002Slewis-revill     }
83207f7c002Slewis-revill   }
83307f7c002Slewis-revill 
83407f7c002Slewis-revill   return true;
83507f7c002Slewis-revill }
83607f7c002Slewis-revill 
83707f7c002Slewis-revill bool RISCVFrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const {
83807f7c002Slewis-revill   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
83908649f0aSMatt Arsenault   const MachineFunction *MF = MBB.getParent();
84008649f0aSMatt Arsenault   const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
84107f7c002Slewis-revill 
84208649f0aSMatt Arsenault   if (!RVFI->useSaveRestoreLibCalls(*MF))
84307f7c002Slewis-revill     return true;
84407f7c002Slewis-revill 
84507f7c002Slewis-revill   // Inserting a call to a __riscv_save libcall requires the use of the register
84607f7c002Slewis-revill   // t0 (X5) to hold the return address. Therefore if this register is already
84707f7c002Slewis-revill   // used we can't insert the call.
84807f7c002Slewis-revill 
84907f7c002Slewis-revill   RegScavenger RS;
85007f7c002Slewis-revill   RS.enterBasicBlock(*TmpMBB);
85107f7c002Slewis-revill   return !RS.isRegUsed(RISCV::X5);
85207f7c002Slewis-revill }
85307f7c002Slewis-revill 
85407f7c002Slewis-revill bool RISCVFrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
85508649f0aSMatt Arsenault   const MachineFunction *MF = MBB.getParent();
85607f7c002Slewis-revill   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
85708649f0aSMatt Arsenault   const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
85807f7c002Slewis-revill 
85908649f0aSMatt Arsenault   if (!RVFI->useSaveRestoreLibCalls(*MF))
86007f7c002Slewis-revill     return true;
86107f7c002Slewis-revill 
86207f7c002Slewis-revill   // Using the __riscv_restore libcalls to restore CSRs requires a tail call.
86307f7c002Slewis-revill   // This means if we still need to continue executing code within this function
86407f7c002Slewis-revill   // the restore cannot take place in this basic block.
86507f7c002Slewis-revill 
86607f7c002Slewis-revill   if (MBB.succ_size() > 1)
86707f7c002Slewis-revill     return false;
86807f7c002Slewis-revill 
86907f7c002Slewis-revill   MachineBasicBlock *SuccMBB =
87007f7c002Slewis-revill       MBB.succ_empty() ? TmpMBB->getFallThrough() : *MBB.succ_begin();
87107f7c002Slewis-revill 
87207f7c002Slewis-revill   // Doing a tail call should be safe if there are no successors, because either
87307f7c002Slewis-revill   // we have a returning block or the end of the block is unreachable, so the
87407f7c002Slewis-revill   // restore will be eliminated regardless.
87507f7c002Slewis-revill   if (!SuccMBB)
87607f7c002Slewis-revill     return true;
87707f7c002Slewis-revill 
87807f7c002Slewis-revill   // The successor can only contain a return, since we would effectively be
87907f7c002Slewis-revill   // replacing the successor with our own tail return at the end of our block.
88007f7c002Slewis-revill   return SuccMBB->isReturnBlock() && SuccMBB->size() == 1;
88107f7c002Slewis-revill }
882