1 //===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass is responsible for finalizing the functions frame layout, saving
11 // callee saved registers, and for emitting prolog & epilog code for the
14 // This pass must be run after register allocation. After this pass is
15 // executed, it is illegal to construct MO_FrameIndex operands.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/MRegisterInfo.h"
25 #include "llvm/Target/TargetFrameInfo.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Support/Compiler.h"
31 struct VISIBILITY_HIDDEN PEI : public MachineFunctionPass {
32 const char *getPassName() const {
33 return "Prolog/Epilog Insertion & Frame Finalization";
36 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
37 /// frame indexes with appropriate references.
39 bool runOnMachineFunction(MachineFunction &Fn) {
40 // Get MachineDebugInfo so that we can track the construction of the
42 if (MachineDebugInfo *DI = getAnalysisToUpdate<MachineDebugInfo>()) {
43 Fn.getFrameInfo()->setMachineDebugInfo(DI);
46 // Scan the function for modified callee saved registers and insert spill
47 // code for any callee saved registers that are modified. Also calculate
48 // the MaxCallFrameSize and HasCalls variables for the function's frame
49 // information and eliminates call frame pseudo instructions.
50 calculateCalleeSavedRegisters(Fn);
52 // Add the code to save and restore the caller saved registers
53 saveCallerSavedRegisters(Fn);
55 // Allow the target machine to make final modifications to the function
56 // before the frame layout is finalized.
57 Fn.getTarget().getRegisterInfo()->processFunctionBeforeFrameFinalized(Fn);
59 // Calculate actual frame offsets for all of the abstract stack objects...
60 calculateFrameObjectOffsets(Fn);
62 // Add prolog and epilog code to the function. This function is required
63 // to align the stack frame as necessary for any stack variables or
64 // called functions. Because of this, calculateCalleeSavedRegisters
65 // must be called before this function in order to set the HasCalls
66 // and MaxCallFrameSize variables.
67 insertPrologEpilogCode(Fn);
69 // Replace all MO_FrameIndex operands with physical register references
70 // and actual offsets.
72 replaceFrameIndices(Fn);
78 void calculateCalleeSavedRegisters(MachineFunction &Fn);
79 void saveCallerSavedRegisters(MachineFunction &Fn);
80 void calculateFrameObjectOffsets(MachineFunction &Fn);
81 void replaceFrameIndices(MachineFunction &Fn);
82 void insertPrologEpilogCode(MachineFunction &Fn);
87 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
88 /// prolog and epilog code, and eliminates abstract frame references.
90 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
93 /// calculateCalleeSavedRegisters - Scan the function for modified caller saved
94 /// registers. Also calculate the MaxCallFrameSize and HasCalls variables for
95 /// the function's frame information and eliminates call frame pseudo
98 void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
99 const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
100 const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
102 // Get the callee saved register list...
103 const unsigned *CSRegs = RegInfo->getCalleeSaveRegs();
105 // Get the function call frame set-up and tear-down instruction opcode
106 int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode();
107 int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
109 // Early exit for targets which have no callee saved registers and no call
110 // frame setup/destroy pseudo instructions.
111 if ((CSRegs == 0 || CSRegs[0] == 0) &&
112 FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
115 unsigned MaxCallFrameSize = 0;
116 bool HasCalls = false;
118 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
119 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); )
120 if (I->getOpcode() == FrameSetupOpcode ||
121 I->getOpcode() == FrameDestroyOpcode) {
122 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
123 " instructions should have a single immediate argument!");
124 unsigned Size = I->getOperand(0).getImmedValue();
125 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
127 RegInfo->eliminateCallFramePseudoInstr(Fn, *BB, I++);
132 MachineFrameInfo *FFI = Fn.getFrameInfo();
133 FFI->setHasCalls(HasCalls);
134 FFI->setMaxCallFrameSize(MaxCallFrameSize);
136 // Now figure out which *callee saved* registers are modified by the current
137 // function, thus needing to be saved and restored in the prolog/epilog.
139 const bool *PhysRegsUsed = Fn.getUsedPhysregs();
140 const TargetRegisterClass* const *CSRegClasses =
141 RegInfo->getCalleeSaveRegClasses();
142 std::vector<CalleeSavedInfo> CSI;
143 for (unsigned i = 0; CSRegs[i]; ++i) {
144 unsigned Reg = CSRegs[i];
145 if (PhysRegsUsed[Reg]) {
146 // If the reg is modified, save it!
147 CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
149 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
150 *AliasSet; ++AliasSet) { // Check alias registers too.
151 if (PhysRegsUsed[*AliasSet]) {
152 CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
160 return; // Early exit if no caller saved registers are modified!
162 unsigned NumFixedSpillSlots;
163 const std::pair<unsigned,int> *FixedSpillSlots =
164 TFI->getCalleeSaveSpillSlots(NumFixedSpillSlots);
166 // Now that we know which registers need to be saved and restored, allocate
167 // stack slots for them.
168 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
169 unsigned Reg = CSI[i].getReg();
170 const TargetRegisterClass *RC = CSI[i].getRegClass();
172 // Check to see if this physreg must be spilled to a particular stack slot
174 const std::pair<unsigned,int> *FixedSlot = FixedSpillSlots;
175 while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
176 FixedSlot->first != Reg)
180 if (FixedSlot == FixedSpillSlots+NumFixedSpillSlots) {
181 // Nope, just spill it anywhere convenient.
182 FrameIdx = FFI->CreateStackObject(RC->getSize(), RC->getAlignment());
184 // Spill it to the stack where we must.
185 FrameIdx = FFI->CreateFixedObject(RC->getSize(), FixedSlot->second);
187 CSI[i].setFrameIdx(FrameIdx);
190 FFI->setCalleeSavedInfo(CSI);
193 /// saveCallerSavedRegisters - Insert spill code for any caller saved registers
194 /// that are modified in the function.
196 void PEI::saveCallerSavedRegisters(MachineFunction &Fn) {
197 // Get callee saved register information.
198 MachineFrameInfo *FFI = Fn.getFrameInfo();
199 const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
201 // Early exit if no caller saved registers are modified!
205 const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
207 // Now that we have a stack slot for each register to be saved, insert spill
208 // code into the entry block.
209 MachineBasicBlock *MBB = Fn.begin();
210 MachineBasicBlock::iterator I = MBB->begin();
211 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
212 // Insert the spill to the stack frame.
213 RegInfo->storeRegToStackSlot(*MBB, I, CSI[i].getReg(), CSI[i].getFrameIdx(),
214 CSI[i].getRegClass());
217 // Add code to restore the callee-save registers in each exiting block.
218 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
219 for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI)
220 // If last instruction is a return instruction, add an epilogue.
221 if (!FI->empty() && TII.isReturn(FI->back().getOpcode())) {
225 // Skip over all terminator instructions, which are part of the return
227 MachineBasicBlock::iterator I2 = I;
228 while (I2 != MBB->begin() && TII.isTerminatorInstr((--I2)->getOpcode()))
231 bool AtStart = I == MBB->begin();
232 MachineBasicBlock::iterator BeforeI = I;
236 // Restore all registers immediately before the return and any terminators
238 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
239 RegInfo->loadRegFromStackSlot(*MBB, I, CSI[i].getReg(),
240 CSI[i].getFrameIdx(),
241 CSI[i].getRegClass());
242 assert(I != MBB->begin() &&
243 "loadRegFromStackSlot didn't insert any code!");
244 // Insert in reverse order. loadRegFromStackSlot can insert multiple
257 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
258 /// abstract stack objects.
260 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
261 const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
263 bool StackGrowsDown =
264 TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
266 // Loop over all of the stack objects, assigning sequential addresses...
267 MachineFrameInfo *FFI = Fn.getFrameInfo();
269 unsigned StackAlignment = TFI.getStackAlignment();
270 unsigned MaxAlign = 0;
272 // Start at the beginning of the local area.
273 // The Offset is the distance from the stack top in the direction
274 // of stack growth -- so it's always positive.
275 int Offset = TFI.getOffsetOfLocalArea();
279 && "Local area offset should be in direction of stack growth");
281 // If there are fixed sized objects that are preallocated in the local area,
282 // non-fixed objects can't be allocated right at the start of local area.
283 // We currently don't support filling in holes in between fixed sized objects,
284 // so we adjust 'Offset' to point to the end of last fixed sized
285 // preallocated object.
286 for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
288 if (StackGrowsDown) {
289 // The maximum distance from the stack pointer is at lower address of
290 // the object -- which is given by offset. For down growing stack
291 // the offset is negative, so we negate the offset to get the distance.
292 FixedOff = -FFI->getObjectOffset(i);
294 // The maximum distance from the start pointer is at the upper
295 // address of the object.
296 FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i);
298 if (FixedOff > Offset) Offset = FixedOff;
301 for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
302 // If stack grows down, we need to add size of find the lowest
303 // address of the object.
305 Offset += FFI->getObjectSize(i);
307 unsigned Align = FFI->getObjectAlignment(i);
308 // If the alignment of this object is greater than that of the stack, then
309 // increase the stack alignment to match.
310 MaxAlign = std::max(MaxAlign, Align);
311 // Adjust to alignment boundary
312 Offset = (Offset+Align-1)/Align*Align;
314 if (StackGrowsDown) {
315 FFI->setObjectOffset(i, -Offset); // Set the computed offset
317 FFI->setObjectOffset(i, Offset);
318 Offset += FFI->getObjectSize(i);
322 // Align the final stack pointer offset, but only if there are calls in the
323 // function. This ensures that any calls to subroutines have their stack
324 // frames suitable aligned.
326 Offset = (Offset+StackAlignment-1)/StackAlignment*StackAlignment;
328 // Set the final value of the stack pointer...
329 FFI->setStackSize(Offset+TFI.getOffsetOfLocalArea());
331 // Remember the required stack alignment in case targets need it to perform
332 // dynamic stack alignment.
333 assert(FFI->getMaxAlignment() == MaxAlign &&
334 "Stack alignment calculation broken!");
338 /// insertPrologEpilogCode - Scan the function for modified caller saved
339 /// registers, insert spill code for these caller saved registers, then add
340 /// prolog and epilog code to the function.
342 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
343 // Add prologue to the function...
344 Fn.getTarget().getRegisterInfo()->emitPrologue(Fn);
346 // Add epilogue to restore the callee-save registers in each exiting block
347 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
348 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
349 // If last instruction is a return instruction, add an epilogue
350 if (!I->empty() && TII.isReturn(I->back().getOpcode()))
351 Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I);
356 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
357 /// register references and actual offsets.
359 void PEI::replaceFrameIndices(MachineFunction &Fn) {
360 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
362 const TargetMachine &TM = Fn.getTarget();
363 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
364 const MRegisterInfo &MRI = *TM.getRegisterInfo();
366 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
367 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
368 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
369 if (I->getOperand(i).isFrameIndex()) {
370 // If this instruction has a FrameIndex operand, we need to use that
371 // target machine register info object to eliminate it.
372 MRI.eliminateFrameIndex(I);