PrologEpilogInserter.cpp revision 1cbe4d0ad0888e50858cca83cf2a0d3083709513
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
28namespace llvm {
29
30namespace {
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///
75FunctionPass *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///
84void 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	  if (MO.isRegister() && MO.isDef()) {
120            assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
121                   "Register allocation must be performed!");
122	    ModifiedRegs[MO.getReg()] = true;         // Register is modified
123          }
124        }
125	++I;
126      }
127
128  MachineFrameInfo *FFI = Fn.getFrameInfo();
129  FFI->setHasCalls(HasCalls);
130  FFI->setMaxCallFrameSize(MaxCallFrameSize);
131
132  // Now figure out which *callee saved* registers are modified by the current
133  // function, thus needing to be saved and restored in the prolog/epilog.
134  //
135  std::vector<unsigned> RegsToSave;
136  for (unsigned i = 0; CSRegs[i]; ++i) {
137    unsigned Reg = CSRegs[i];
138    if (ModifiedRegs[Reg]) {
139      RegsToSave.push_back(Reg);  // If modified register...
140    } else {
141      for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
142           *AliasSet; ++AliasSet) {  // Check alias registers too...
143	if (ModifiedRegs[*AliasSet]) {
144	  RegsToSave.push_back(Reg);
145	  break;
146	}
147      }
148    }
149  }
150
151  if (RegsToSave.empty())
152    return;   // Early exit if no caller saved registers are modified!
153
154  // Now that we know which registers need to be saved and restored, allocate
155  // stack slots for them.
156  std::vector<int> StackSlots;
157  for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
158    int FrameIdx = FFI->CreateStackObject(RegInfo->getRegClass(RegsToSave[i]));
159    StackSlots.push_back(FrameIdx);
160  }
161
162  // Now that we have a stack slot for each register to be saved, insert spill
163  // code into the entry block...
164  MachineBasicBlock *MBB = Fn.begin();
165  MachineBasicBlock::iterator I = MBB->begin();
166  for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
167    const TargetRegisterClass *RC = RegInfo->getRegClass(RegsToSave[i]);
168
169    // Insert the spill to the stack frame...
170    RegInfo->storeRegToStackSlot(*MBB, I, RegsToSave[i], StackSlots[i], RC);
171  }
172
173  // Add code to restore the callee-save registers in each exiting block.
174  const TargetInstrInfo &TII = Fn.getTarget().getInstrInfo();
175  for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI) {
176    // If last instruction is a return instruction, add an epilogue
177    if (!FI->empty() && TII.isReturn(FI->back()->getOpcode())) {
178      MBB = FI; I = MBB->end()-1;
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///
193void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
194  const TargetFrameInfo &TFI = Fn.getTarget().getFrameInfo();
195
196  bool StackGrowsDown =
197    TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
198  assert(StackGrowsDown && "Only tested on stack down growing targets!");
199
200  // Loop over all of the stack objects, assigning sequential addresses...
201  MachineFrameInfo *FFI = Fn.getFrameInfo();
202
203  unsigned StackAlignment = TFI.getStackAlignment();
204
205  // Start at the beginning of the local area...
206  int Offset = TFI.getOffsetOfLocalArea();
207  for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
208    Offset += FFI->getObjectSize(i);         // Allocate Size bytes...
209
210    unsigned Align = FFI->getObjectAlignment(i);
211    assert(Align <= StackAlignment && "Cannot align stack object to higher "
212           "alignment boundary than the stack itself!");
213    Offset = (Offset+Align-1)/Align*Align;   // Adjust to Alignment boundary...
214
215    FFI->setObjectOffset(i, -Offset);        // Set the computed offset
216  }
217
218  // Align the final stack pointer offset...
219  Offset = (Offset+StackAlignment-1)/StackAlignment*StackAlignment;
220
221  // Set the final value of the stack pointer...
222  FFI->setStackSize(Offset-TFI.getOffsetOfLocalArea());
223}
224
225
226/// insertPrologEpilogCode - Scan the function for modified caller saved
227/// registers, insert spill code for these caller saved registers, then add
228/// prolog and epilog code to the function.
229///
230void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
231  // Add prologue to the function...
232  Fn.getTarget().getRegisterInfo()->emitPrologue(Fn);
233
234  // Add epilogue to restore the callee-save registers in each exiting block
235  const TargetInstrInfo &TII = Fn.getTarget().getInstrInfo();
236  for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
237    // If last instruction is a return instruction, add an epilogue
238    if (!I->empty() && TII.isReturn(I->back()->getOpcode()))
239      Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I);
240  }
241}
242
243
244/// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
245/// register references and actual offsets.
246///
247void PEI::replaceFrameIndices(MachineFunction &Fn) {
248  if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
249
250  const TargetMachine &TM = Fn.getTarget();
251  assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
252  const MRegisterInfo &MRI = *TM.getRegisterInfo();
253
254  for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
255    for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
256      for (unsigned i = 0, e = (*I)->getNumOperands(); i != e; ++i)
257	if ((*I)->getOperand(i).isFrameIndex()) {
258	  // If this instruction has a FrameIndex operand, we need to use that
259	  // target machine register info object to eliminate it.
260	  MRI.eliminateFrameIndex(Fn, I);
261	  break;
262	}
263}
264
265} // End llvm namespace
266