Fix assertion to not dereference end!
[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       // Scan the function for modified caller saved registers and insert spill
40       // code for any caller saved registers that are modified.  Also calculate
41       // the MaxCallFrameSize and HasCalls variables for the function's frame
42       // information and eliminates call frame pseudo instructions.
43       saveCallerSavedRegisters(Fn);
44
45       // Allow the target machine to make final modifications to the function
46       // before the frame layout is finalized.
47       Fn.getTarget().getRegisterInfo()->processFunctionBeforeFrameFinalized(Fn);
48
49       // Calculate actual frame offsets for all of the abstract stack objects...
50       calculateFrameObjectOffsets(Fn);
51
52       // Add prolog and epilog code to the function.
53       insertPrologEpilogCode(Fn);
54
55       // Replace all MO_FrameIndex operands with physical register references
56       // and actual offsets.
57       //
58       replaceFrameIndices(Fn);
59       return true;
60     }
61
62   private:
63     void saveCallerSavedRegisters(MachineFunction &Fn);
64     void calculateFrameObjectOffsets(MachineFunction &Fn);
65     void replaceFrameIndices(MachineFunction &Fn);
66     void insertPrologEpilogCode(MachineFunction &Fn);
67   };
68 }
69
70
71 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
72 /// prolog and epilog code, and eliminates abstract frame references.
73 ///
74 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
75
76
77 /// saveCallerSavedRegisters - Scan the function for modified caller saved
78 /// registers and insert spill code for any caller saved registers that are
79 /// modified.  Also calculate the MaxCallFrameSize and HasCalls variables for
80 /// the function's frame information and eliminates call frame pseudo
81 /// instructions.
82 ///
83 void PEI::saveCallerSavedRegisters(MachineFunction &Fn) {
84   const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
85   const TargetFrameInfo &FrameInfo = *Fn.getTarget().getFrameInfo();
86
87   // Get the callee saved register list...
88   const unsigned *CSRegs = RegInfo->getCalleeSaveRegs();
89
90   // Get the function call frame set-up and tear-down instruction opcode
91   int FrameSetupOpcode   = RegInfo->getCallFrameSetupOpcode();
92   int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
93
94   // Early exit for targets which have no callee saved registers and no call
95   // frame setup/destroy pseudo instructions.
96   if ((CSRegs == 0 || CSRegs[0] == 0) &&
97       FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
98     return;
99
100   // This bitset contains an entry for each physical register for the target...
101   std::vector<bool> ModifiedRegs(RegInfo->getNumRegs());
102   unsigned MaxCallFrameSize = 0;
103   bool HasCalls = false;
104
105   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
106     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); )
107       if (I->getOpcode() == FrameSetupOpcode ||
108           I->getOpcode() == FrameDestroyOpcode) {
109         assert(I->getNumOperands() == 1 && "Call Frame Setup/Destroy Pseudo"
110                " instructions should have a single immediate argument!");
111         unsigned Size = I->getOperand(0).getImmedValue();
112         if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
113         HasCalls = true;
114         RegInfo->eliminateCallFramePseudoInstr(Fn, *BB, I++);
115       } else {
116         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
117           MachineOperand &MO = I->getOperand(i);
118           if (MO.isRegister() && MO.isDef()) {
119             assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
120                    "Register allocation must be performed!");
121             ModifiedRegs[MO.getReg()] = true;         // Register is modified
122           }
123         }
124         ++I;
125       }
126
127   MachineFrameInfo *FFI = Fn.getFrameInfo();
128   FFI->setHasCalls(HasCalls);
129   FFI->setMaxCallFrameSize(MaxCallFrameSize);
130
131   // Now figure out which *callee saved* registers are modified by the current
132   // function, thus needing to be saved and restored in the prolog/epilog.
133   //
134   std::vector<unsigned> RegsToSave;
135   for (unsigned i = 0; CSRegs[i]; ++i) {
136     unsigned Reg = CSRegs[i];
137     if (ModifiedRegs[Reg]) {
138       RegsToSave.push_back(Reg);  // If modified register...
139     } else {
140       for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
141            *AliasSet; ++AliasSet) {  // Check alias registers too...
142         if (ModifiedRegs[*AliasSet]) {
143           RegsToSave.push_back(Reg);
144           break;
145         }
146       }
147     }
148   }
149
150   if (RegsToSave.empty())
151     return;   // Early exit if no caller saved registers are modified!
152
153   // Now that we know which registers need to be saved and restored, allocate
154   // stack slots for them.
155   std::vector<int> StackSlots;
156   for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
157     int FrameIdx = FFI->CreateStackObject(RegInfo->getRegClass(RegsToSave[i]));
158     StackSlots.push_back(FrameIdx);
159   }
160
161   // Now that we have a stack slot for each register to be saved, insert spill
162   // code into the entry block...
163   MachineBasicBlock *MBB = Fn.begin();
164   MachineBasicBlock::iterator I = MBB->begin();
165   for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
166     const TargetRegisterClass *RC = RegInfo->getRegClass(RegsToSave[i]);
167
168     // Insert the spill to the stack frame...
169     RegInfo->storeRegToStackSlot(*MBB, I, RegsToSave[i], StackSlots[i], RC);
170   }
171
172   // Add code to restore the callee-save registers in each exiting block.
173   const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
174   for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI) {
175     // If last instruction is a return instruction, add an epilogue
176     if (!FI->empty() && TII.isReturn(FI->back().getOpcode())) {
177       MBB = FI;
178       I = MBB->end(); --I;
179
180       for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
181         const TargetRegisterClass *RC = RegInfo->getRegClass(RegsToSave[i]);
182         RegInfo->loadRegFromStackSlot(*MBB, I, RegsToSave[i],StackSlots[i], RC);
183         --I;  // Insert in reverse order
184       }
185     }
186   }
187 }
188
189
190 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
191 /// abstract stack objects...
192 ///
193 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
194   const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
195   
196   bool StackGrowsDown =
197     TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
198  
199   // Loop over all of the stack objects, assigning sequential addresses...
200   MachineFrameInfo *FFI = Fn.getFrameInfo();
201
202   unsigned StackAlignment = TFI.getStackAlignment();
203
204   // Start at the beginning of the local area.
205   // The Offset is the distance from the stack top in the direction
206   // of stack growth -- so it's always positive.
207   int Offset = TFI.getOffsetOfLocalArea();
208   if (StackGrowsDown)
209     Offset = -Offset;
210   assert(Offset >= 0 
211          && "Local area offset should be in direction of stack growth");
212
213   // If there are fixed sized objects that are preallocated in the local area,
214   // non-fixed objects can't be allocated right at the start of local area.
215   // We currently don't support filling in holes in between fixed sized objects, 
216   // so we adjust 'Offset' to point to the end of last fixed sized
217   // preallocated object.
218   for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
219     int FixedOff;
220     if (StackGrowsDown) {
221       // The maximum distance from the stack pointer is at lower address of
222       // the object -- which is given by offset. For down growing stack
223       // the offset is negative, so we negate the offset to get the distance.
224       FixedOff = -FFI->getObjectOffset(i);
225     } else {
226       // The maximum distance from the start pointer is at the upper 
227       // address of the object.
228       FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i);
229     }    
230     if (FixedOff > Offset) Offset = FixedOff;            
231   }
232
233   for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
234     // If stack grows down, we need to add size of find the lowest
235     // address of the object.
236     if (StackGrowsDown)
237       Offset += FFI->getObjectSize(i);
238
239     unsigned Align = FFI->getObjectAlignment(i);
240     assert(Align <= StackAlignment && "Cannot align stack object to higher "
241            "alignment boundary than the stack itself!");
242     Offset = (Offset+Align-1)/Align*Align;   // Adjust to Alignment boundary...
243     
244     if (StackGrowsDown) {
245       FFI->setObjectOffset(i, -Offset);        // Set the computed offset
246     } else {
247       FFI->setObjectOffset(i, Offset); 
248       Offset += FFI->getObjectSize(i);
249     }
250   }
251
252   // Align the final stack pointer offset, but only if there are calls in the
253   // function.  This ensures that any calls to subroutines have their stack
254   // frames suitable aligned.
255   if (FFI->hasCalls())
256     Offset = (Offset+StackAlignment-1)/StackAlignment*StackAlignment;
257
258   // Set the final value of the stack pointer...
259   FFI->setStackSize(Offset+TFI.getOffsetOfLocalArea());
260 }
261
262
263 /// insertPrologEpilogCode - Scan the function for modified caller saved
264 /// registers, insert spill code for these caller saved registers, then add
265 /// prolog and epilog code to the function.
266 ///
267 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
268   // Add prologue to the function...
269   Fn.getTarget().getRegisterInfo()->emitPrologue(Fn);
270
271   // Add epilogue to restore the callee-save registers in each exiting block
272   const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
273   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
274     // If last instruction is a return instruction, add an epilogue
275     if (!I->empty() && TII.isReturn(I->back().getOpcode()))
276       Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I);
277   }
278 }
279
280
281 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
282 /// register references and actual offsets.
283 ///
284 void PEI::replaceFrameIndices(MachineFunction &Fn) {
285   if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
286
287   const TargetMachine &TM = Fn.getTarget();
288   assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
289   const MRegisterInfo &MRI = *TM.getRegisterInfo();
290
291   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
292     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
293       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
294         if (I->getOperand(i).isFrameIndex()) {
295           // If this instruction has a FrameIndex operand, we need to use that
296           // target machine register info object to eliminate it.
297           MRI.eliminateFrameIndex(Fn, I);
298           break;
299         }
300 }