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