Fix casting so there's no warning on Alpha.
[oota-llvm.git] / lib / CodeGen / PrologEpilogInserter.cpp
1 //===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass is responsible for finalizing the functions frame layout, saving
11 // callee saved registers, and for emitting prolog & epilog code for the
12 // function.
13 //
14 // This pass must be run after register allocation.  After this pass is
15 // executed, it is illegal to construct MO_FrameIndex operands.
16 //
17 //===----------------------------------------------------------------------===//
18
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 using namespace llvm;
28
29 namespace {
30   struct PEI : public MachineFunctionPass {
31     const char *getPassName() const {
32       return "Prolog/Epilog Insertion & Frame Finalization";
33     }
34
35     /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
36     /// frame indexes with appropriate references.
37     ///
38     bool runOnMachineFunction(MachineFunction &Fn) {
39       // Get MachineDebugInfo so that we can track the construction of the
40       // frame.
41       if (MachineDebugInfo *DI = getAnalysisToUpdate<MachineDebugInfo>()) {
42         Fn.getFrameInfo()->setMachineDebugInfo(DI);
43       }
44       
45       // Scan the function for modified caller saved registers and insert spill
46       // code for any caller saved registers that are modified.  Also calculate
47       // the MaxCallFrameSize and HasCalls variables for the function's frame
48       // information and eliminates call frame pseudo instructions.
49       calculateCallerSavedRegisters(Fn);
50
51       // Add the code to save and restore the caller saved registers
52       saveCallerSavedRegisters(Fn);
53
54       // Allow the target machine to make final modifications to the function
55       // before the frame layout is finalized.
56       Fn.getTarget().getRegisterInfo()->processFunctionBeforeFrameFinalized(Fn);
57
58       // Calculate actual frame offsets for all of the abstract stack objects...
59       calculateFrameObjectOffsets(Fn);
60
61       // Add prolog and epilog code to the function.  This function is required
62       // to align the stack frame as necessary for any stack variables or
63       // called functions.  Because of this, calculateCallerSavedRegisters
64       // must be called before this function in order to set the HasCalls
65       // and MaxCallFrameSize variables.
66       insertPrologEpilogCode(Fn);
67
68       // Replace all MO_FrameIndex operands with physical register references
69       // and actual offsets.
70       //
71       replaceFrameIndices(Fn);
72
73       RegsToSave.clear();
74       StackSlots.clear();
75       return true;
76     }
77
78   private:
79     std::vector<std::pair<unsigned, const TargetRegisterClass*> > RegsToSave;
80     std::vector<int> StackSlots;
81
82     void calculateCallerSavedRegisters(MachineFunction &Fn);
83     void saveCallerSavedRegisters(MachineFunction &Fn);
84     void calculateFrameObjectOffsets(MachineFunction &Fn);
85     void replaceFrameIndices(MachineFunction &Fn);
86     void insertPrologEpilogCode(MachineFunction &Fn);
87   };
88 }
89
90
91 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
92 /// prolog and epilog code, and eliminates abstract frame references.
93 ///
94 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
95
96
97 /// calculateCallerSavedRegisters - Scan the function for modified caller saved
98 /// registers.  Also calculate the MaxCallFrameSize and HasCalls variables for
99 /// the function's frame information and eliminates call frame pseudo
100 /// instructions.
101 ///
102 void PEI::calculateCallerSavedRegisters(MachineFunction &Fn) {
103   const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
104   const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
105
106   // Get the callee saved register list...
107   const unsigned *CSRegs = RegInfo->getCalleeSaveRegs();
108
109   // Get the function call frame set-up and tear-down instruction opcode
110   int FrameSetupOpcode   = RegInfo->getCallFrameSetupOpcode();
111   int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
112
113   // Early exit for targets which have no callee saved registers and no call
114   // frame setup/destroy pseudo instructions.
115   if ((CSRegs == 0 || CSRegs[0] == 0) &&
116       FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
117     return;
118
119   unsigned MaxCallFrameSize = 0;
120   bool HasCalls = false;
121
122   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
123     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); )
124       if (I->getOpcode() == FrameSetupOpcode ||
125           I->getOpcode() == FrameDestroyOpcode) {
126         assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
127                " instructions should have a single immediate argument!");
128         unsigned Size = I->getOperand(0).getImmedValue();
129         if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
130         HasCalls = true;
131         RegInfo->eliminateCallFramePseudoInstr(Fn, *BB, I++);
132       } else {
133         ++I;
134       }
135
136   MachineFrameInfo *FFI = Fn.getFrameInfo();
137   FFI->setHasCalls(HasCalls);
138   FFI->setMaxCallFrameSize(MaxCallFrameSize);
139
140   // Now figure out which *callee saved* registers are modified by the current
141   // function, thus needing to be saved and restored in the prolog/epilog.
142   //
143   const bool *PhysRegsUsed = Fn.getUsedPhysregs();
144   const TargetRegisterClass* const *CSRegClasses =
145     RegInfo->getCalleeSaveRegClasses();
146   for (unsigned i = 0; CSRegs[i]; ++i) {
147     unsigned Reg = CSRegs[i];
148     if (PhysRegsUsed[Reg]) {
149         // If the reg is modified, save it!
150       RegsToSave.push_back(std::make_pair(Reg, CSRegClasses[i]));
151     } else {
152       for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
153            *AliasSet; ++AliasSet) {  // Check alias registers too.
154         if (PhysRegsUsed[*AliasSet]) {
155           RegsToSave.push_back(std::make_pair(Reg, CSRegClasses[i]));
156           break;
157         }
158       }
159     }
160   }
161
162   if (RegsToSave.empty())
163     return;   // Early exit if no caller saved registers are modified!
164
165   unsigned NumFixedSpillSlots;
166   const std::pair<unsigned,int> *FixedSpillSlots =
167     TFI->getCalleeSaveSpillSlots(NumFixedSpillSlots);
168
169   // Now that we know which registers need to be saved and restored, allocate
170   // stack slots for them.
171   for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
172     unsigned Reg = RegsToSave[i].first;
173     const TargetRegisterClass *RC = RegsToSave[i].second;
174
175     // Check to see if this physreg must be spilled to a particular stack slot
176     // on this target.
177     const std::pair<unsigned,int> *FixedSlot = FixedSpillSlots;
178     while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
179            FixedSlot->first != Reg)
180       ++FixedSlot;
181
182     int FrameIdx;
183     if (FixedSlot == FixedSpillSlots+NumFixedSpillSlots) {
184       // Nope, just spill it anywhere convenient.
185       FrameIdx = FFI->CreateStackObject(RC->getSize(), RC->getAlignment());
186     } else {
187       // Spill it to the stack where we must.
188       FrameIdx = FFI->CreateFixedObject(RC->getSize(), FixedSlot->second);
189     }
190     StackSlots.push_back(FrameIdx);
191   }
192 }
193
194 /// saveCallerSavedRegisters -  Insert spill code for any caller saved registers
195 /// that are modified in the function.
196 ///
197 void PEI::saveCallerSavedRegisters(MachineFunction &Fn) {
198   // Early exit if no caller saved registers are modified!
199   if (RegsToSave.empty())
200     return;
201
202   const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
203
204   // Now that we have a stack slot for each register to be saved, insert spill
205   // code into the entry block.
206   MachineBasicBlock *MBB = Fn.begin();
207   MachineBasicBlock::iterator I = MBB->begin();
208   for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
209     // Insert the spill to the stack frame.
210     RegInfo->storeRegToStackSlot(*MBB, I, RegsToSave[i].first, StackSlots[i],
211                                  RegsToSave[i].second);
212   }
213
214   // Add code to restore the callee-save registers in each exiting block.
215   const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
216   for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI)
217     // If last instruction is a return instruction, add an epilogue.
218     if (!FI->empty() && TII.isReturn(FI->back().getOpcode())) {
219       MBB = FI;
220       I = MBB->end(); --I;
221
222       // Skip over all terminator instructions, which are part of the return
223       // sequence.
224       MachineBasicBlock::iterator I2 = I;
225       while (I2 != MBB->begin() && TII.isTerminatorInstr((--I2)->getOpcode()))
226         I = I2;
227
228       bool AtStart = I == MBB->begin();
229       MachineBasicBlock::iterator BeforeI = I;
230       if (!AtStart)
231         --BeforeI;
232       
233       // Restore all registers immediately before the return and any terminators
234       // that preceed it.
235       for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
236         RegInfo->loadRegFromStackSlot(*MBB, I, RegsToSave[i].first,
237                                       StackSlots[i], RegsToSave[i].second);
238         assert(I != MBB->begin() &&
239                "loadRegFromStackSlot didn't insert any code!");
240         // Insert in reverse order.  loadRegFromStackSlot can insert multiple
241         // instructions.
242         if (AtStart)
243           I = MBB->begin();
244         else {
245           I = BeforeI;
246           ++I;
247         }
248       }
249     }
250 }
251
252
253 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
254 /// abstract stack objects.
255 ///
256 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
257   const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
258
259   bool StackGrowsDown =
260     TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
261
262   // Loop over all of the stack objects, assigning sequential addresses...
263   MachineFrameInfo *FFI = Fn.getFrameInfo();
264
265   unsigned StackAlignment = TFI.getStackAlignment();
266   unsigned MaxAlign = 0;
267
268   // Start at the beginning of the local area.
269   // The Offset is the distance from the stack top in the direction
270   // of stack growth -- so it's always positive.
271   int Offset = TFI.getOffsetOfLocalArea();
272   if (StackGrowsDown)
273     Offset = -Offset;
274   assert(Offset >= 0
275          && "Local area offset should be in direction of stack growth");
276
277   // If there are fixed sized objects that are preallocated in the local area,
278   // non-fixed objects can't be allocated right at the start of local area.
279   // We currently don't support filling in holes in between fixed sized objects,
280   // so we adjust 'Offset' to point to the end of last fixed sized
281   // preallocated object.
282   for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
283     int FixedOff;
284     if (StackGrowsDown) {
285       // The maximum distance from the stack pointer is at lower address of
286       // the object -- which is given by offset. For down growing stack
287       // the offset is negative, so we negate the offset to get the distance.
288       FixedOff = -FFI->getObjectOffset(i);
289     } else {
290       // The maximum distance from the start pointer is at the upper
291       // address of the object.
292       FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i);
293     }
294     if (FixedOff > Offset) Offset = FixedOff;
295   }
296
297   for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
298     // If stack grows down, we need to add size of find the lowest
299     // address of the object.
300     if (StackGrowsDown)
301       Offset += FFI->getObjectSize(i);
302
303     unsigned Align = FFI->getObjectAlignment(i);
304     // If the alignment of this object is greater than that of the stack, then
305     // increase the stack alignment to match.
306     MaxAlign = std::max(MaxAlign, Align);
307     // Adjust to alignment boundary
308     Offset = (Offset+Align-1)/Align*Align;
309
310     if (StackGrowsDown) {
311       FFI->setObjectOffset(i, -Offset);        // Set the computed offset
312     } else {
313       FFI->setObjectOffset(i, Offset);
314       Offset += FFI->getObjectSize(i);
315     }
316   }
317
318   // Align the final stack pointer offset, but only if there are calls in the
319   // function.  This ensures that any calls to subroutines have their stack
320   // frames suitable aligned.
321   if (FFI->hasCalls())
322     Offset = (Offset+StackAlignment-1)/StackAlignment*StackAlignment;
323
324   // Set the final value of the stack pointer...
325   FFI->setStackSize(Offset+TFI.getOffsetOfLocalArea());
326
327   // Remember the required stack alignment in case targets need it to perform
328   // dynamic stack alignment.
329   assert(FFI->getMaxAlignment() == MaxAlign &&
330          "Stack alignment calculation broken!");
331 }
332
333
334 /// insertPrologEpilogCode - Scan the function for modified caller saved
335 /// registers, insert spill code for these caller saved registers, then add
336 /// prolog and epilog code to the function.
337 ///
338 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
339   // Add prologue to the function...
340   Fn.getTarget().getRegisterInfo()->emitPrologue(Fn);
341
342   // Add epilogue to restore the callee-save registers in each exiting block
343   const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
344   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
345     // If last instruction is a return instruction, add an epilogue
346     if (!I->empty() && TII.isReturn(I->back().getOpcode()))
347       Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I);
348   }
349 }
350
351
352 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
353 /// register references and actual offsets.
354 ///
355 void PEI::replaceFrameIndices(MachineFunction &Fn) {
356   if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
357
358   const TargetMachine &TM = Fn.getTarget();
359   assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
360   const MRegisterInfo &MRI = *TM.getRegisterInfo();
361
362   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
363     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
364       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
365         if (I->getOperand(i).isFrameIndex()) {
366           // If this instruction has a FrameIndex operand, we need to use that
367           // target machine register info object to eliminate it.
368           MRI.eliminateFrameIndex(I);
369           break;
370         }
371 }