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"
32 struct VISIBILITY_HIDDEN PEI : public MachineFunctionPass {
33 const char *getPassName() const {
34 return "Prolog/Epilog Insertion & Frame Finalization";
37 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
38 /// frame indexes with appropriate references.
40 bool runOnMachineFunction(MachineFunction &Fn) {
41 // Get MachineDebugInfo so that we can track the construction of the
43 if (MachineDebugInfo *DI = getAnalysisToUpdate<MachineDebugInfo>()) {
44 Fn.getFrameInfo()->setMachineDebugInfo(DI);
47 // Allow the target machine to make some adjustments to the function
48 // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
49 Fn.getTarget().getRegisterInfo()
50 ->processFunctionBeforeCalleeSavedScan(Fn);
52 // Scan the function for modified callee saved registers and insert spill
53 // code for any callee saved registers that are modified. Also calculate
54 // the MaxCallFrameSize and HasCalls variables for the function's frame
55 // information and eliminates call frame pseudo instructions.
56 calculateCalleeSavedRegisters(Fn);
58 // Add the code to save and restore the callee saved registers
59 saveCalleeSavedRegisters(Fn);
61 // Allow the target machine to make final modifications to the function
62 // before the frame layout is finalized.
63 Fn.getTarget().getRegisterInfo()->processFunctionBeforeFrameFinalized(Fn);
65 // Calculate actual frame offsets for all of the abstract stack objects...
66 calculateFrameObjectOffsets(Fn);
68 // Add prolog and epilog code to the function. This function is required
69 // to align the stack frame as necessary for any stack variables or
70 // called functions. Because of this, calculateCalleeSavedRegisters
71 // must be called before this function in order to set the HasCalls
72 // and MaxCallFrameSize variables.
73 insertPrologEpilogCode(Fn);
75 // Replace all MO_FrameIndex operands with physical register references
76 // and actual offsets.
78 replaceFrameIndices(Fn);
84 // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved
85 // stack frame indexes.
86 unsigned MinCSFrameIndex, MaxCSFrameIndex;
88 void calculateCalleeSavedRegisters(MachineFunction &Fn);
89 void saveCalleeSavedRegisters(MachineFunction &Fn);
90 void calculateFrameObjectOffsets(MachineFunction &Fn);
91 void replaceFrameIndices(MachineFunction &Fn);
92 void insertPrologEpilogCode(MachineFunction &Fn);
97 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
98 /// prolog and epilog code, and eliminates abstract frame references.
100 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
103 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
104 /// registers. Also calculate the MaxCallFrameSize and HasCalls variables for
105 /// the function's frame information and eliminates call frame pseudo
108 void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
109 const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
110 const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
112 // Get the callee saved register list...
113 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs();
115 // Get the function call frame set-up and tear-down instruction opcode
116 int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode();
117 int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
119 // These are used to keep track the callee-save area. Initialize them.
120 MinCSFrameIndex = INT_MAX;
123 // Early exit for targets which have no callee saved registers and no call
124 // frame setup/destroy pseudo instructions.
125 if ((CSRegs == 0 || CSRegs[0] == 0) &&
126 FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
129 unsigned MaxCallFrameSize = 0;
130 bool HasCalls = false;
132 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
133 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); )
134 if (I->getOpcode() == FrameSetupOpcode ||
135 I->getOpcode() == FrameDestroyOpcode) {
136 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
137 " instructions should have a single immediate argument!");
138 unsigned Size = I->getOperand(0).getImmedValue();
139 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
141 RegInfo->eliminateCallFramePseudoInstr(Fn, *BB, I++);
146 MachineFrameInfo *FFI = Fn.getFrameInfo();
147 FFI->setHasCalls(HasCalls);
148 FFI->setMaxCallFrameSize(MaxCallFrameSize);
150 // Now figure out which *callee saved* registers are modified by the current
151 // function, thus needing to be saved and restored in the prolog/epilog.
153 const bool *PhysRegsUsed = Fn.getUsedPhysregs();
154 const TargetRegisterClass* const *CSRegClasses =
155 RegInfo->getCalleeSavedRegClasses();
156 std::vector<CalleeSavedInfo> CSI;
157 for (unsigned i = 0; CSRegs[i]; ++i) {
158 unsigned Reg = CSRegs[i];
159 if (PhysRegsUsed[Reg]) {
160 // If the reg is modified, save it!
161 CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
163 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
164 *AliasSet; ++AliasSet) { // Check alias registers too.
165 if (PhysRegsUsed[*AliasSet]) {
166 CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
174 return; // Early exit if no callee saved registers are modified!
176 unsigned NumFixedSpillSlots;
177 const std::pair<unsigned,int> *FixedSpillSlots =
178 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
180 // Now that we know which registers need to be saved and restored, allocate
181 // stack slots for them.
182 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
183 unsigned Reg = CSI[i].getReg();
184 const TargetRegisterClass *RC = CSI[i].getRegClass();
186 // Check to see if this physreg must be spilled to a particular stack slot
188 const std::pair<unsigned,int> *FixedSlot = FixedSpillSlots;
189 while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
190 FixedSlot->first != Reg)
194 if (FixedSlot == FixedSpillSlots+NumFixedSpillSlots) {
195 // Nope, just spill it anywhere convenient.
196 unsigned Align = RC->getAlignment();
197 unsigned StackAlign = TFI->getStackAlignment();
198 // We may not be able to sastify the desired alignment specification of
199 // the TargetRegisterClass if the stack alignment is smaller. Use the min.
200 Align = std::min(Align, StackAlign);
201 FrameIdx = FFI->CreateStackObject(RC->getSize(), Align);
202 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
203 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
205 // Spill it to the stack where we must.
206 FrameIdx = FFI->CreateFixedObject(RC->getSize(), FixedSlot->second);
208 CSI[i].setFrameIdx(FrameIdx);
211 FFI->setCalleeSavedInfo(CSI);
214 /// saveCalleeSavedRegisters - Insert spill code for any callee saved registers
215 /// that are modified in the function.
217 void PEI::saveCalleeSavedRegisters(MachineFunction &Fn) {
218 // Get callee saved register information.
219 MachineFrameInfo *FFI = Fn.getFrameInfo();
220 const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
222 // Early exit if no callee saved registers are modified!
226 const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
228 // Now that we have a stack slot for each register to be saved, insert spill
229 // code into the entry block.
230 MachineBasicBlock *MBB = Fn.begin();
231 MachineBasicBlock::iterator I = MBB->begin();
232 if (!RegInfo->spillCalleeSavedRegisters(*MBB, I, CSI)) {
233 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
234 // Insert the spill to the stack frame.
235 RegInfo->storeRegToStackSlot(*MBB, I, CSI[i].getReg(),
236 CSI[i].getFrameIdx(),
237 CSI[i].getRegClass());
241 // Add code to restore the callee-save registers in each exiting block.
242 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
243 for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI)
244 // If last instruction is a return instruction, add an epilogue.
245 if (!FI->empty() && TII.isReturn(FI->back().getOpcode())) {
249 // Skip over all terminator instructions, which are part of the return
251 MachineBasicBlock::iterator I2 = I;
252 while (I2 != MBB->begin() && TII.isTerminatorInstr((--I2)->getOpcode()))
255 bool AtStart = I == MBB->begin();
256 MachineBasicBlock::iterator BeforeI = I;
260 // Restore all registers immediately before the return and any terminators
262 if (!RegInfo->restoreCalleeSavedRegisters(*MBB, I, CSI)) {
263 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
264 RegInfo->loadRegFromStackSlot(*MBB, I, CSI[i].getReg(),
265 CSI[i].getFrameIdx(),
266 CSI[i].getRegClass());
267 assert(I != MBB->begin() &&
268 "loadRegFromStackSlot didn't insert any code!");
269 // Insert in reverse order. loadRegFromStackSlot can insert multiple
283 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
284 /// abstract stack objects.
286 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
287 const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
289 bool StackGrowsDown =
290 TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
292 // Loop over all of the stack objects, assigning sequential addresses...
293 MachineFrameInfo *FFI = Fn.getFrameInfo();
295 unsigned MaxAlign = 0;
297 // Start at the beginning of the local area.
298 // The Offset is the distance from the stack top in the direction
299 // of stack growth -- so it's always positive.
300 int Offset = TFI.getOffsetOfLocalArea();
304 && "Local area offset should be in direction of stack growth");
306 // If there are fixed sized objects that are preallocated in the local area,
307 // non-fixed objects can't be allocated right at the start of local area.
308 // We currently don't support filling in holes in between fixed sized objects,
309 // so we adjust 'Offset' to point to the end of last fixed sized
310 // preallocated object.
311 for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
313 if (StackGrowsDown) {
314 // The maximum distance from the stack pointer is at lower address of
315 // the object -- which is given by offset. For down growing stack
316 // the offset is negative, so we negate the offset to get the distance.
317 FixedOff = -FFI->getObjectOffset(i);
319 // The maximum distance from the start pointer is at the upper
320 // address of the object.
321 FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i);
323 if (FixedOff > Offset) Offset = FixedOff;
326 // First assign frame offsets to stack objects that are used to spill
327 // callee saved registers.
328 if (StackGrowsDown) {
329 for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
330 if (i < MinCSFrameIndex || i > MaxCSFrameIndex)
333 // If stack grows down, we need to add size of find the lowest
334 // address of the object.
335 Offset += FFI->getObjectSize(i);
337 unsigned Align = FFI->getObjectAlignment(i);
338 // If the alignment of this object is greater than that of the stack, then
339 // increase the stack alignment to match.
340 MaxAlign = std::max(MaxAlign, Align);
341 // Adjust to alignment boundary
342 Offset = (Offset+Align-1)/Align*Align;
344 FFI->setObjectOffset(i, -Offset); // Set the computed offset
347 for (int i = FFI->getObjectIndexEnd()-1; i >= 0; --i) {
348 if ((unsigned)i < MinCSFrameIndex || (unsigned)i > MaxCSFrameIndex)
351 unsigned Align = FFI->getObjectAlignment(i);
352 // If the alignment of this object is greater than that of the stack, then
353 // increase the stack alignment to match.
354 MaxAlign = std::max(MaxAlign, Align);
355 // Adjust to alignment boundary
356 Offset = (Offset+Align-1)/Align*Align;
358 FFI->setObjectOffset(i, Offset);
359 Offset += FFI->getObjectSize(i);
363 // Then assign frame offsets to stack objects that are not used to spill
364 // callee saved registers.
365 for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
366 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
369 // If stack grows down, we need to add size of find the lowest
370 // address of the object.
372 Offset += FFI->getObjectSize(i);
374 unsigned Align = FFI->getObjectAlignment(i);
375 // If the alignment of this object is greater than that of the stack, then
376 // increase the stack alignment to match.
377 MaxAlign = std::max(MaxAlign, Align);
378 // Adjust to alignment boundary
379 Offset = (Offset+Align-1)/Align*Align;
381 if (StackGrowsDown) {
382 FFI->setObjectOffset(i, -Offset); // Set the computed offset
384 FFI->setObjectOffset(i, Offset);
385 Offset += FFI->getObjectSize(i);
389 // Round up the size to a multiple of the alignment, but only if there are
390 // calls or alloca's in the function. This ensures that any calls to
391 // subroutines have their stack frames suitable aligned.
392 if (FFI->hasCalls() || FFI->hasVarSizedObjects()) {
393 // When we have no frame pointer, we reserve argument space for call sites
394 // in the function immediately on entry to the current function. This
395 // eliminates the need for add/sub sp brackets around call sites.
396 const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
397 if (!RegInfo->hasFP(Fn))
398 Offset += FFI->getMaxCallFrameSize();
400 unsigned AlignMask = TFI.getStackAlignment() - 1;
401 Offset = (Offset + AlignMask) & ~AlignMask;
404 // Update frame info to pretend that this is part of the stack...
405 FFI->setStackSize(Offset+TFI.getOffsetOfLocalArea());
407 // Remember the required stack alignment in case targets need it to perform
408 // dynamic stack alignment.
409 assert(FFI->getMaxAlignment() == MaxAlign &&
410 "Stack alignment calculation broken!");
414 /// insertPrologEpilogCode - Scan the function for modified callee saved
415 /// registers, insert spill code for these callee saved registers, then add
416 /// prolog and epilog code to the function.
418 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
419 // Add prologue to the function...
420 Fn.getTarget().getRegisterInfo()->emitPrologue(Fn);
422 // Add epilogue to restore the callee-save registers in each exiting block
423 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
424 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
425 // If last instruction is a return instruction, add an epilogue
426 if (!I->empty() && TII.isReturn(I->back().getOpcode()))
427 Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I);
432 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
433 /// register references and actual offsets.
435 void PEI::replaceFrameIndices(MachineFunction &Fn) {
436 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
438 const TargetMachine &TM = Fn.getTarget();
439 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
440 const MRegisterInfo &MRI = *TM.getRegisterInfo();
442 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
443 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
444 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
445 if (I->getOperand(i).isFrameIndex()) {
446 // If this instruction has a FrameIndex operand, we need to use that
447 // target machine register info object to eliminate it.
448 MRI.eliminateFrameIndex(I);