1 //===-- RISCVFrameLowering.cpp - RISCV Frame Information ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the RISCV implementation of TargetFrameLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RISCVFrameLowering.h"
15 #include "RISCVMachineFunctionInfo.h"
16 #include "RISCVSubtarget.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/RegisterScavenging.h"
22 
23 using namespace llvm;
24 
25 bool RISCVFrameLowering::hasFP(const MachineFunction &MF) const {
26   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
27 
28   const MachineFrameInfo &MFI = MF.getFrameInfo();
29   return MF.getTarget().Options.DisableFramePointerElim(MF) ||
30          RegInfo->needsStackRealignment(MF) || MFI.hasVarSizedObjects() ||
31          MFI.isFrameAddressTaken();
32 }
33 
34 // Determines the size of the frame and maximum call frame size.
35 void RISCVFrameLowering::determineFrameLayout(MachineFunction &MF) const {
36   MachineFrameInfo &MFI = MF.getFrameInfo();
37   const RISCVRegisterInfo *RI = STI.getRegisterInfo();
38 
39   // Get the number of bytes to allocate from the FrameInfo.
40   uint64_t FrameSize = MFI.getStackSize();
41 
42   // Get the alignment.
43   uint64_t StackAlign = RI->needsStackRealignment(MF) ? MFI.getMaxAlignment()
44                                                       : getStackAlignment();
45 
46   // Get the maximum call frame size of all the calls.
47   uint64_t MaxCallFrameSize = MFI.getMaxCallFrameSize();
48 
49   // If we have dynamic alloca then MaxCallFrameSize needs to be aligned so
50   // that allocations will be aligned.
51   if (MFI.hasVarSizedObjects())
52     MaxCallFrameSize = alignTo(MaxCallFrameSize, StackAlign);
53 
54   // Update maximum call frame size.
55   MFI.setMaxCallFrameSize(MaxCallFrameSize);
56 
57   // Include call frame size in total.
58   if (!(hasReservedCallFrame(MF) && MFI.adjustsStack()))
59     FrameSize += MaxCallFrameSize;
60 
61   // Make sure the frame is aligned.
62   FrameSize = alignTo(FrameSize, StackAlign);
63 
64   // Update frame info.
65   MFI.setStackSize(FrameSize);
66 }
67 
68 void RISCVFrameLowering::adjustReg(MachineBasicBlock &MBB,
69                                    MachineBasicBlock::iterator MBBI,
70                                    const DebugLoc &DL, unsigned DestReg,
71                                    unsigned SrcReg, int64_t Val,
72                                    MachineInstr::MIFlag Flag) const {
73   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
74   const RISCVInstrInfo *TII = STI.getInstrInfo();
75 
76   if (DestReg == SrcReg && Val == 0)
77     return;
78 
79   if (isInt<12>(Val)) {
80     BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), DestReg)
81         .addReg(SrcReg)
82         .addImm(Val)
83         .setMIFlag(Flag);
84   } else if (isInt<32>(Val)) {
85     unsigned Opc = RISCV::ADD;
86     bool isSub = Val < 0;
87     if (isSub) {
88       Val = -Val;
89       Opc = RISCV::SUB;
90     }
91 
92     unsigned ScratchReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
93     TII->movImm32(MBB, MBBI, DL, ScratchReg, Val, Flag);
94     BuildMI(MBB, MBBI, DL, TII->get(Opc), DestReg)
95         .addReg(SrcReg)
96         .addReg(ScratchReg, RegState::Kill)
97         .setMIFlag(Flag);
98   } else {
99     report_fatal_error("adjustReg cannot yet handle adjustments >32 bits");
100   }
101 }
102 
103 // Returns the register used to hold the frame pointer.
104 static unsigned getFPReg(const RISCVSubtarget &STI) { return RISCV::X8; }
105 
106 // Returns the register used to hold the stack pointer.
107 static unsigned getSPReg(const RISCVSubtarget &STI) { return RISCV::X2; }
108 
109 void RISCVFrameLowering::emitPrologue(MachineFunction &MF,
110                                       MachineBasicBlock &MBB) const {
111   assert(&MF.front() == &MBB && "Shrink-wrapping not yet supported");
112 
113   MachineFrameInfo &MFI = MF.getFrameInfo();
114   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
115   MachineBasicBlock::iterator MBBI = MBB.begin();
116 
117   unsigned FPReg = getFPReg(STI);
118   unsigned SPReg = getSPReg(STI);
119 
120   // Debug location must be unknown since the first debug location is used
121   // to determine the end of the prologue.
122   DebugLoc DL;
123 
124   // Determine the correct frame layout
125   determineFrameLayout(MF);
126 
127   // FIXME (note copied from Lanai): This appears to be overallocating.  Needs
128   // investigation. Get the number of bytes to allocate from the FrameInfo.
129   uint64_t StackSize = MFI.getStackSize();
130 
131   // Early exit if there is no need to allocate on the stack
132   if (StackSize == 0 && !MFI.adjustsStack())
133     return;
134 
135   // Allocate space on the stack if necessary.
136   adjustReg(MBB, MBBI, DL, SPReg, SPReg, -StackSize, MachineInstr::FrameSetup);
137 
138   // The frame pointer is callee-saved, and code has been generated for us to
139   // save it to the stack. We need to skip over the storing of callee-saved
140   // registers as the frame pointer must be modified after it has been saved
141   // to the stack, not before.
142   // FIXME: assumes exactly one instruction is used to save each callee-saved
143   // register.
144   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
145   std::advance(MBBI, CSI.size());
146 
147   // Generate new FP.
148   if (hasFP(MF))
149     adjustReg(MBB, MBBI, DL, FPReg, SPReg,
150               StackSize - RVFI->getVarArgsSaveSize(), MachineInstr::FrameSetup);
151 }
152 
153 void RISCVFrameLowering::emitEpilogue(MachineFunction &MF,
154                                       MachineBasicBlock &MBB) const {
155   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
156   const RISCVRegisterInfo *RI = STI.getRegisterInfo();
157   MachineFrameInfo &MFI = MF.getFrameInfo();
158   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
159   DebugLoc DL = MBBI->getDebugLoc();
160   unsigned FPReg = getFPReg(STI);
161   unsigned SPReg = getSPReg(STI);
162 
163   // Skip to before the restores of callee-saved registers
164   // FIXME: assumes exactly one instruction is used to restore each
165   // callee-saved register.
166   MachineBasicBlock::iterator LastFrameDestroy = MBBI;
167   std::advance(LastFrameDestroy, -MFI.getCalleeSavedInfo().size());
168 
169   uint64_t StackSize = MFI.getStackSize();
170 
171   // Restore the stack pointer using the value of the frame pointer. Only
172   // necessary if the stack pointer was modified, meaning the stack size is
173   // unknown.
174   if (RI->needsStackRealignment(MF) || MFI.hasVarSizedObjects()) {
175     assert(hasFP(MF) && "frame pointer should not have been eliminated");
176     adjustReg(MBB, LastFrameDestroy, DL, SPReg, FPReg,
177               -StackSize + RVFI->getVarArgsSaveSize(),
178               MachineInstr::FrameDestroy);
179   }
180 
181   // Deallocate stack
182   adjustReg(MBB, MBBI, DL, SPReg, SPReg, StackSize, MachineInstr::FrameDestroy);
183 }
184 
185 int RISCVFrameLowering::getFrameIndexReference(const MachineFunction &MF,
186                                                int FI,
187                                                unsigned &FrameReg) const {
188   const MachineFrameInfo &MFI = MF.getFrameInfo();
189   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
190   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
191 
192   // Callee-saved registers should be referenced relative to the stack
193   // pointer (positive offset), otherwise use the frame pointer (negative
194   // offset).
195   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
196   int MinCSFI = 0;
197   int MaxCSFI = -1;
198 
199   int Offset = MFI.getObjectOffset(FI) - getOffsetOfLocalArea() +
200                MFI.getOffsetAdjustment();
201 
202   if (CSI.size()) {
203     MinCSFI = CSI[0].getFrameIdx();
204     MaxCSFI = CSI[CSI.size() - 1].getFrameIdx();
205   }
206 
207   if (FI >= MinCSFI && FI <= MaxCSFI) {
208     FrameReg = RISCV::X2;
209     Offset += MF.getFrameInfo().getStackSize();
210   } else {
211     FrameReg = RI->getFrameRegister(MF);
212     if (hasFP(MF))
213       Offset += RVFI->getVarArgsSaveSize();
214     else
215       Offset += MF.getFrameInfo().getStackSize();
216   }
217   return Offset;
218 }
219 
220 void RISCVFrameLowering::determineCalleeSaves(MachineFunction &MF,
221                                               BitVector &SavedRegs,
222                                               RegScavenger *RS) const {
223   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
224   // Unconditionally spill RA and FP only if the function uses a frame
225   // pointer.
226   if (hasFP(MF)) {
227     SavedRegs.set(RISCV::X1);
228     SavedRegs.set(RISCV::X8);
229   }
230 }
231 
232 void RISCVFrameLowering::processFunctionBeforeFrameFinalized(
233     MachineFunction &MF, RegScavenger *RS) const {
234   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
235   MachineFrameInfo &MFI = MF.getFrameInfo();
236   const TargetRegisterClass *RC = &RISCV::GPRRegClass;
237   // estimateStackSize has been observed to under-estimate the final stack
238   // size, so give ourselves wiggle-room by checking for stack size
239   // representable an 11-bit signed field rather than 12-bits.
240   // FIXME: It may be possible to craft a function with a small stack that
241   // still needs an emergency spill slot for branch relaxation. This case
242   // would currently be missed.
243   if (!isInt<11>(MFI.estimateStackSize(MF))) {
244     int RegScavFI = MFI.CreateStackObject(
245         RegInfo->getSpillSize(*RC), RegInfo->getSpillAlignment(*RC), false);
246     RS->addScavengingFrameIndex(RegScavFI);
247   }
248 }
249