Add TwoAddressInstructionPass to handle instructions that have two or
[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
28 namespace llvm {
29
30 namespace {
31   struct PEI : public MachineFunctionPass {
32     const char *getPassName() const {
33       return "Prolog/Epilog Insertion & Frame Finalization";
34     }
35
36     /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
37     /// frame indexes with appropriate references.
38     ///
39     bool runOnMachineFunction(MachineFunction &Fn) {
40       // Scan the function for modified caller saved registers and insert spill
41       // code for any caller saved registers that are modified.  Also calculate
42       // the MaxCallFrameSize and HasCalls variables for the function's frame
43       // information and eliminates call frame pseudo instructions.
44       saveCallerSavedRegisters(Fn);
45
46       // Allow the target machine to make final modifications to the function
47       // before the frame layout is finalized.
48       Fn.getTarget().getRegisterInfo()->processFunctionBeforeFrameFinalized(Fn);
49
50       // Calculate actual frame offsets for all of the abstract stack objects...
51       calculateFrameObjectOffsets(Fn);
52
53       // Add prolog and epilog code to the function.
54       insertPrologEpilogCode(Fn);
55
56       // Replace all MO_FrameIndex operands with physical register references
57       // and actual offsets.
58       //
59       replaceFrameIndices(Fn);
60       return true;
61     }
62
63   private:
64     void saveCallerSavedRegisters(MachineFunction &Fn);
65     void calculateFrameObjectOffsets(MachineFunction &Fn);
66     void replaceFrameIndices(MachineFunction &Fn);
67     void insertPrologEpilogCode(MachineFunction &Fn);
68   };
69 }
70
71
72 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
73 /// prolog and epilog code, and eliminates abstract frame references.
74 ///
75 FunctionPass *createPrologEpilogCodeInserter() { return new PEI(); }
76
77
78 /// saveCallerSavedRegisters - Scan the function for modified caller saved
79 /// registers and insert spill code for any caller saved registers that are
80 /// modified.  Also calculate the MaxCallFrameSize and HasCalls variables for
81 /// the function's frame information and eliminates call frame pseudo
82 /// instructions.
83 ///
84 void PEI::saveCallerSavedRegisters(MachineFunction &Fn) {
85   const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
86   const TargetFrameInfo &FrameInfo = Fn.getTarget().getFrameInfo();
87
88   // Get the callee saved register list...
89   const unsigned *CSRegs = RegInfo->getCalleeSaveRegs();
90
91   // Get the function call frame set-up and tear-down instruction opcode
92   int FrameSetupOpcode   = RegInfo->getCallFrameSetupOpcode();
93   int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
94
95   // Early exit for targets which have no callee saved registers and no call
96   // frame setup/destroy pseudo instructions.
97   if ((CSRegs == 0 || CSRegs[0] == 0) &&
98       FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
99     return;
100
101   // This bitset contains an entry for each physical register for the target...
102   std::vector<bool> ModifiedRegs(MRegisterInfo::FirstVirtualRegister);
103   unsigned MaxCallFrameSize = 0;
104   bool HasCalls = false;
105
106   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
107     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); )
108       if ((*I)->getOpcode() == FrameSetupOpcode ||
109           (*I)->getOpcode() == FrameDestroyOpcode) {
110         assert((*I)->getNumOperands() == 1 && "Call Frame Setup/Destroy Pseudo"
111                " instructions should have a single immediate argument!");
112         unsigned Size = (*I)->getOperand(0).getImmedValue();
113         if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
114         HasCalls = true;
115         RegInfo->eliminateCallFramePseudoInstr(Fn, *BB, I);
116       } else {
117         for (unsigned i = 0, e = (*I)->getNumOperands(); i != e; ++i) {
118           MachineOperand &MO = (*I)->getOperand(i);
119           assert(!MO.isVirtualRegister() &&
120                  "Register allocation must be performed!");
121           if (MO.isPhysicalRegister() && MO.isDef())
122             ModifiedRegs[MO.getReg()] = true;         // Register is modified
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; I = MBB->end()-1;
178
179       for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
180         const TargetRegisterClass *RC = RegInfo->getRegClass(RegsToSave[i]);
181         RegInfo->loadRegFromStackSlot(*MBB, I, RegsToSave[i],StackSlots[i], RC);
182         --I;  // Insert in reverse order
183       }
184     }
185   }
186 }
187
188
189 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
190 /// abstract stack objects...
191 ///
192 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
193   const TargetFrameInfo &TFI = Fn.getTarget().getFrameInfo();
194   
195   bool StackGrowsDown =
196     TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
197   assert(StackGrowsDown && "Only tested on stack down growing targets!");
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   int Offset = TFI.getOffsetOfLocalArea();
206   for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
207     Offset += FFI->getObjectSize(i);         // Allocate Size bytes...
208
209     unsigned Align = FFI->getObjectAlignment(i);
210     assert(Align <= StackAlignment && "Cannot align stack object to higher "
211            "alignment boundary than the stack itself!");
212     Offset = (Offset+Align-1)/Align*Align;   // Adjust to Alignment boundary...
213     
214     FFI->setObjectOffset(i, -Offset);        // Set the computed offset
215   }
216
217   // Align the final stack pointer offset...
218   Offset = (Offset+StackAlignment-1)/StackAlignment*StackAlignment;
219
220   // Set the final value of the stack pointer...
221   FFI->setStackSize(Offset-TFI.getOffsetOfLocalArea());
222 }
223
224
225 /// insertPrologEpilogCode - Scan the function for modified caller saved
226 /// registers, insert spill code for these caller saved registers, then add
227 /// prolog and epilog code to the function.
228 ///
229 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
230   // Add prologue to the function...
231   Fn.getTarget().getRegisterInfo()->emitPrologue(Fn);
232
233   // Add epilogue to restore the callee-save registers in each exiting block
234   const TargetInstrInfo &TII = Fn.getTarget().getInstrInfo();
235   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
236     // If last instruction is a return instruction, add an epilogue
237     if (!I->empty() && TII.isReturn(I->back()->getOpcode()))
238       Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I);
239   }
240 }
241
242
243 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
244 /// register references and actual offsets.
245 ///
246 void PEI::replaceFrameIndices(MachineFunction &Fn) {
247   if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
248
249   const TargetMachine &TM = Fn.getTarget();
250   assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
251   const MRegisterInfo &MRI = *TM.getRegisterInfo();
252
253   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
254     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
255       for (unsigned i = 0, e = (*I)->getNumOperands(); i != e; ++i)
256         if ((*I)->getOperand(i).isFrameIndex()) {
257           // If this instruction has a FrameIndex operand, we need to use that
258           // target machine register info object to eliminate it.
259           MRI.eliminateFrameIndex(Fn, I);
260           break;
261         }
262 }
263
264 } // End llvm namespace