PrologEpilogInserter.cpp revision 10b8d22fc08d063995b647eea82e5ab79d2aff4b
1//===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// 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// This pass provides an optional shrink wrapping variant of prolog/epilog
18// insertion, enabled via --shrink-wrap. See ShrinkWrapping.cpp.
19//
20//===----------------------------------------------------------------------===//
21
22#include "PrologEpilogInserter.h"
23#include "llvm/CodeGen/MachineDominators.h"
24#include "llvm/CodeGen/MachineLoopInfo.h"
25#include "llvm/CodeGen/MachineInstr.h"
26#include "llvm/CodeGen/MachineFrameInfo.h"
27#include "llvm/CodeGen/MachineModuleInfo.h"
28#include "llvm/CodeGen/MachineRegisterInfo.h"
29#include "llvm/CodeGen/RegisterScavenging.h"
30#include "llvm/Target/TargetMachine.h"
31#include "llvm/Target/TargetRegisterInfo.h"
32#include "llvm/Target/TargetFrameInfo.h"
33#include "llvm/Target/TargetInstrInfo.h"
34#include "llvm/Support/Compiler.h"
35#include "llvm/ADT/STLExtras.h"
36#include <climits>
37
38using namespace llvm;
39
40char PEI::ID = 0;
41
42static RegisterPass<PEI>
43X("prologepilog", "Prologue/Epilogue Insertion");
44
45/// createPrologEpilogCodeInserter - This function returns a pass that inserts
46/// prolog and epilog code, and eliminates abstract frame references.
47///
48FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
49
50/// runOnMachineFunction - Insert prolog/epilog code and replace abstract
51/// frame indexes with appropriate references.
52///
53bool PEI::runOnMachineFunction(MachineFunction &Fn) {
54  const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
55  RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL;
56
57  // Get MachineModuleInfo so that we can track the construction of the
58  // frame.
59  if (MachineModuleInfo *MMI = getAnalysisIfAvailable<MachineModuleInfo>())
60    Fn.getFrameInfo()->setMachineModuleInfo(MMI);
61
62  // Allow the target machine to make some adjustments to the function
63  // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
64  TRI->processFunctionBeforeCalleeSavedScan(Fn, RS);
65
66  // Scan the function for modified callee saved registers and insert spill
67  // code for any callee saved registers that are modified.  Also calculate
68  // the MaxCallFrameSize and HasCalls variables for the function's frame
69  // information and eliminates call frame pseudo instructions.
70  calculateCalleeSavedRegisters(Fn);
71
72  // Determine placement of CSR spill/restore code:
73  //  - with shrink wrapping, place spills and restores to tightly
74  //    enclose regions in the Machine CFG of the function where
75  //    they are used. Without shrink wrapping
76  //  - default (no shrink wrapping), place all spills in the
77  //    entry block, all restores in return blocks.
78  placeCSRSpillsAndRestores(Fn);
79
80  // Add the code to save and restore the callee saved registers
81  insertCSRSpillsAndRestores(Fn);
82
83  // Allow the target machine to make final modifications to the function
84  // before the frame layout is finalized.
85  TRI->processFunctionBeforeFrameFinalized(Fn);
86
87  // Calculate actual frame offsets for all abstract stack objects...
88  calculateFrameObjectOffsets(Fn);
89
90  // Add prolog and epilog code to the function.  This function is required
91  // to align the stack frame as necessary for any stack variables or
92  // called functions.  Because of this, calculateCalleeSavedRegisters
93  // must be called before this function in order to set the HasCalls
94  // and MaxCallFrameSize variables.
95  insertPrologEpilogCode(Fn);
96
97  // Replace all MO_FrameIndex operands with physical register references
98  // and actual offsets.
99  //
100  replaceFrameIndices(Fn);
101
102  delete RS;
103  clearAllSets();
104  return true;
105}
106
107#if 0
108void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
109  AU.setPreservesCFG();
110  if (ShrinkWrapping || ShrinkWrapFunc != "") {
111    AU.addRequired<MachineLoopInfo>();
112    AU.addRequired<MachineDominatorTree>();
113  }
114  AU.addPreserved<MachineLoopInfo>();
115  AU.addPreserved<MachineDominatorTree>();
116  MachineFunctionPass::getAnalysisUsage(AU);
117}
118#endif
119
120/// calculateCalleeSavedRegisters - Scan the function for modified callee saved
121/// registers.  Also calculate the MaxCallFrameSize and HasCalls variables for
122/// the function's frame information and eliminates call frame pseudo
123/// instructions.
124///
125void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
126  const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
127  const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
128
129  // Get the callee saved register list...
130  const unsigned *CSRegs = RegInfo->getCalleeSavedRegs(&Fn);
131
132  // Get the function call frame set-up and tear-down instruction opcode
133  int FrameSetupOpcode   = RegInfo->getCallFrameSetupOpcode();
134  int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
135
136  // These are used to keep track the callee-save area. Initialize them.
137  MinCSFrameIndex = INT_MAX;
138  MaxCSFrameIndex = 0;
139
140  // Early exit for targets which have no callee saved registers and no call
141  // frame setup/destroy pseudo instructions.
142  if ((CSRegs == 0 || CSRegs[0] == 0) &&
143      FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
144    return;
145
146  unsigned MaxCallFrameSize = 0;
147  bool HasCalls = false;
148
149  std::vector<MachineBasicBlock::iterator> FrameSDOps;
150  for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
151    for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
152      if (I->getOpcode() == FrameSetupOpcode ||
153          I->getOpcode() == FrameDestroyOpcode) {
154        assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
155               " instructions should have a single immediate argument!");
156        unsigned Size = I->getOperand(0).getImm();
157        if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
158        HasCalls = true;
159        FrameSDOps.push_back(I);
160      }
161
162  MachineFrameInfo *FFI = Fn.getFrameInfo();
163  FFI->setHasCalls(HasCalls);
164  FFI->setMaxCallFrameSize(MaxCallFrameSize);
165
166  for (std::vector<MachineBasicBlock::iterator>::iterator
167         i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
168    MachineBasicBlock::iterator I = *i;
169
170    // If call frames are not being included as part of the stack frame, and
171    // there is no dynamic allocation (therefore referencing frame slots off
172    // sp), leave the pseudo ops alone. We'll eliminate them later.
173    if (RegInfo->hasReservedCallFrame(Fn) || RegInfo->hasFP(Fn))
174      RegInfo->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
175  }
176
177  // Now figure out which *callee saved* registers are modified by the current
178  // function, thus needing to be saved and restored in the prolog/epilog.
179  const TargetRegisterClass * const *CSRegClasses =
180    RegInfo->getCalleeSavedRegClasses(&Fn);
181
182  std::vector<CalleeSavedInfo> CSI;
183  for (unsigned i = 0; CSRegs[i]; ++i) {
184    unsigned Reg = CSRegs[i];
185    if (Fn.getRegInfo().isPhysRegUsed(Reg)) {
186      // If the reg is modified, save it!
187      CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
188    } else {
189      for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
190           *AliasSet; ++AliasSet) {  // Check alias registers too.
191        if (Fn.getRegInfo().isPhysRegUsed(*AliasSet)) {
192          CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
193          break;
194        }
195      }
196    }
197  }
198
199  if (CSI.empty())
200    return;   // Early exit if no callee saved registers are modified!
201
202  unsigned NumFixedSpillSlots;
203  const std::pair<unsigned,int> *FixedSpillSlots =
204    TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
205
206  // Now that we know which registers need to be saved and restored, allocate
207  // stack slots for them.
208  for (std::vector<CalleeSavedInfo>::iterator
209         I = CSI.begin(), E = CSI.end(); I != E; ++I) {
210    unsigned Reg = I->getReg();
211    const TargetRegisterClass *RC = I->getRegClass();
212
213    int FrameIdx;
214    if (RegInfo->hasReservedSpillSlot(Fn, Reg, FrameIdx)) {
215      I->setFrameIdx(FrameIdx);
216      continue;
217    }
218
219    // Check to see if this physreg must be spilled to a particular stack slot
220    // on this target.
221    const std::pair<unsigned,int> *FixedSlot = FixedSpillSlots;
222    while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
223           FixedSlot->first != Reg)
224      ++FixedSlot;
225
226    if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
227      // Nope, just spill it anywhere convenient.
228      unsigned Align = RC->getAlignment();
229      unsigned StackAlign = TFI->getStackAlignment();
230
231      // We may not be able to satisfy the desired alignment specification of
232      // the TargetRegisterClass if the stack alignment is smaller. Use the
233      // min.
234      Align = std::min(Align, StackAlign);
235      FrameIdx = FFI->CreateStackObject(RC->getSize(), Align);
236      if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
237      if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
238    } else {
239      // Spill it to the stack where we must.
240      FrameIdx = FFI->CreateFixedObject(RC->getSize(), FixedSlot->second);
241    }
242
243    I->setFrameIdx(FrameIdx);
244  }
245
246  FFI->setCalleeSavedInfo(CSI);
247}
248
249/// insertCSRSpillsAndRestores - Insert spill and restore code for
250/// callee saved registers used in the function, handling shrink wrapping.
251///
252void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
253  // Get callee saved register information.
254  MachineFrameInfo *FFI = Fn.getFrameInfo();
255  const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
256
257  // Early exit if no callee saved registers are modified!
258  if (CSI.empty())
259    return;
260
261  const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
262  MachineBasicBlock::iterator I;
263
264  if (! ShrinkWrapThisFunction) {
265    // Spill using target interface.
266    I = EntryBlock->begin();
267    if (!TII.spillCalleeSavedRegisters(*EntryBlock, I, CSI)) {
268      for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
269        // Add the callee-saved register as live-in.
270        // It's killed at the spill.
271        EntryBlock->addLiveIn(CSI[i].getReg());
272
273        // Insert the spill to the stack frame.
274        TII.storeRegToStackSlot(*EntryBlock, I, CSI[i].getReg(), true,
275                                CSI[i].getFrameIdx(), CSI[i].getRegClass());
276      }
277    }
278
279    // Restore using target interface.
280    for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) {
281      MachineBasicBlock* MBB = ReturnBlocks[ri];
282      I = MBB->end(); --I;
283
284      // Skip over all terminator instructions, which are part of the return
285      // sequence.
286      MachineBasicBlock::iterator I2 = I;
287      while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
288        I = I2;
289
290      bool AtStart = I == MBB->begin();
291      MachineBasicBlock::iterator BeforeI = I;
292      if (!AtStart)
293        --BeforeI;
294
295      // Restore all registers immediately before the return and any
296      // terminators that preceed it.
297      if (!TII.restoreCalleeSavedRegisters(*MBB, I, CSI)) {
298        for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
299          TII.loadRegFromStackSlot(*MBB, I, CSI[i].getReg(),
300                                   CSI[i].getFrameIdx(),
301                                   CSI[i].getRegClass());
302          assert(I != MBB->begin() &&
303                 "loadRegFromStackSlot didn't insert any code!");
304          // Insert in reverse order.  loadRegFromStackSlot can insert
305          // multiple instructions.
306          if (AtStart)
307            I = MBB->begin();
308          else {
309            I = BeforeI;
310            ++I;
311          }
312        }
313      }
314    }
315    return;
316  }
317
318  // Insert spills.
319  std::vector<CalleeSavedInfo> blockCSI;
320  for (CSRegBlockMap::iterator BI = CSRSave.begin(),
321         BE = CSRSave.end(); BI != BE; ++BI) {
322    MachineBasicBlock* MBB = BI->first;
323    CSRegSet save = BI->second;
324
325    if (save.empty())
326      continue;
327
328    blockCSI.clear();
329    for (CSRegSet::iterator RI = save.begin(),
330           RE = save.end(); RI != RE; ++RI) {
331      blockCSI.push_back(CSI[*RI]);
332    }
333    assert(blockCSI.size() > 0 &&
334           "Could not collect callee saved register info");
335
336    I = MBB->begin();
337
338    // When shrink wrapping, use stack slot stores/loads.
339    for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
340      // Add the callee-saved register as live-in.
341      // It's killed at the spill.
342      MBB->addLiveIn(blockCSI[i].getReg());
343
344      // Insert the spill to the stack frame.
345      TII.storeRegToStackSlot(*MBB, I, blockCSI[i].getReg(),
346                              true,
347                              blockCSI[i].getFrameIdx(),
348                              blockCSI[i].getRegClass());
349    }
350  }
351
352  for (CSRegBlockMap::iterator BI = CSRRestore.begin(),
353         BE = CSRRestore.end(); BI != BE; ++BI) {
354    MachineBasicBlock* MBB = BI->first;
355    CSRegSet restore = BI->second;
356
357    if (restore.empty())
358      continue;
359
360    blockCSI.clear();
361    for (CSRegSet::iterator RI = restore.begin(),
362           RE = restore.end(); RI != RE; ++RI) {
363      blockCSI.push_back(CSI[*RI]);
364    }
365    assert(blockCSI.size() > 0 &&
366           "Could not find callee saved register info");
367
368    // If MBB is empty and needs restores, insert at the _beginning_.
369    if (MBB->empty()) {
370      I = MBB->begin();
371    } else {
372      I = MBB->end();
373      --I;
374
375      // Skip over all terminator instructions, which are part of the
376      // return sequence.
377      if (! I->getDesc().isTerminator()) {
378        ++I;
379      } else {
380        MachineBasicBlock::iterator I2 = I;
381        while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
382          I = I2;
383      }
384    }
385
386    bool AtStart = I == MBB->begin();
387    MachineBasicBlock::iterator BeforeI = I;
388    if (!AtStart)
389      --BeforeI;
390
391    // Restore all registers immediately before the return and any
392    // terminators that preceed it.
393    for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
394      TII.loadRegFromStackSlot(*MBB, I, blockCSI[i].getReg(),
395                               blockCSI[i].getFrameIdx(),
396                               blockCSI[i].getRegClass());
397      assert(I != MBB->begin() &&
398             "loadRegFromStackSlot didn't insert any code!");
399      // Insert in reverse order.  loadRegFromStackSlot can insert
400      // multiple instructions.
401      if (AtStart)
402        I = MBB->begin();
403      else {
404        I = BeforeI;
405        ++I;
406      }
407    }
408  }
409}
410
411/// AdjustStackOffset - Helper function used to adjust the stack frame offset.
412static inline void
413AdjustStackOffset(MachineFrameInfo *FFI, int FrameIdx,
414                  bool StackGrowsDown, int64_t &Offset,
415                  unsigned &MaxAlign) {
416  // If stack grows down, we need to add size of find the lowest address of the
417  // object.
418  if (StackGrowsDown)
419    Offset += FFI->getObjectSize(FrameIdx);
420
421  unsigned Align = FFI->getObjectAlignment(FrameIdx);
422
423  // If the alignment of this object is greater than that of the stack, then
424  // increase the stack alignment to match.
425  MaxAlign = std::max(MaxAlign, Align);
426
427  // Adjust to alignment boundary.
428  Offset = (Offset + Align - 1) / Align * Align;
429
430  if (StackGrowsDown) {
431    FFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
432  } else {
433    FFI->setObjectOffset(FrameIdx, Offset);
434    Offset += FFI->getObjectSize(FrameIdx);
435  }
436}
437
438/// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
439/// abstract stack objects.
440///
441void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
442  const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
443
444  bool StackGrowsDown =
445    TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
446
447  // Loop over all of the stack objects, assigning sequential addresses...
448  MachineFrameInfo *FFI = Fn.getFrameInfo();
449
450  unsigned MaxAlign = FFI->getMaxAlignment();
451
452  // Start at the beginning of the local area.
453  // The Offset is the distance from the stack top in the direction
454  // of stack growth -- so it's always nonnegative.
455  int64_t Offset = TFI.getOffsetOfLocalArea();
456  if (StackGrowsDown)
457    Offset = -Offset;
458  assert(Offset >= 0
459         && "Local area offset should be in direction of stack growth");
460
461  // If there are fixed sized objects that are preallocated in the local area,
462  // non-fixed objects can't be allocated right at the start of local area.
463  // We currently don't support filling in holes in between fixed sized
464  // objects, so we adjust 'Offset' to point to the end of last fixed sized
465  // preallocated object.
466  for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
467    int64_t FixedOff;
468    if (StackGrowsDown) {
469      // The maximum distance from the stack pointer is at lower address of
470      // the object -- which is given by offset. For down growing stack
471      // the offset is negative, so we negate the offset to get the distance.
472      FixedOff = -FFI->getObjectOffset(i);
473    } else {
474      // The maximum distance from the start pointer is at the upper
475      // address of the object.
476      FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i);
477    }
478    if (FixedOff > Offset) Offset = FixedOff;
479  }
480
481  // First assign frame offsets to stack objects that are used to spill
482  // callee saved registers.
483  if (StackGrowsDown) {
484    for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
485      // If stack grows down, we need to add size of find the lowest
486      // address of the object.
487      Offset += FFI->getObjectSize(i);
488
489      unsigned Align = FFI->getObjectAlignment(i);
490      // If the alignment of this object is greater than that of the stack,
491      // then increase the stack alignment to match.
492      MaxAlign = std::max(MaxAlign, Align);
493      // Adjust to alignment boundary
494      Offset = (Offset+Align-1)/Align*Align;
495
496      FFI->setObjectOffset(i, -Offset);        // Set the computed offset
497    }
498  } else {
499    int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
500    for (int i = MaxCSFI; i >= MinCSFI ; --i) {
501      unsigned Align = FFI->getObjectAlignment(i);
502      // If the alignment of this object is greater than that of the stack,
503      // then increase the stack alignment to match.
504      MaxAlign = std::max(MaxAlign, Align);
505      // Adjust to alignment boundary
506      Offset = (Offset+Align-1)/Align*Align;
507
508      FFI->setObjectOffset(i, Offset);
509      Offset += FFI->getObjectSize(i);
510    }
511  }
512
513  // Make sure the special register scavenging spill slot is closest to the
514  // frame pointer if a frame pointer is required.
515  const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
516  if (RS && RegInfo->hasFP(Fn)) {
517    int SFI = RS->getScavengingFrameIndex();
518    if (SFI >= 0)
519      AdjustStackOffset(FFI, SFI, StackGrowsDown, Offset, MaxAlign);
520  }
521
522  // Make sure that the stack protector comes before the local variables on the
523  // stack.
524  if (FFI->getStackProtectorIndex() >= 0)
525    AdjustStackOffset(FFI, FFI->getStackProtectorIndex(), StackGrowsDown,
526                      Offset, MaxAlign);
527
528  // Then assign frame offsets to stack objects that are not used to spill
529  // callee saved registers.
530  for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
531    if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
532      continue;
533    if (RS && (int)i == RS->getScavengingFrameIndex())
534      continue;
535    if (FFI->isDeadObjectIndex(i))
536      continue;
537    if (FFI->getStackProtectorIndex() == (int)i)
538      continue;
539
540    AdjustStackOffset(FFI, i, StackGrowsDown, Offset, MaxAlign);
541  }
542
543  // Make sure the special register scavenging spill slot is closest to the
544  // stack pointer.
545  if (RS && !RegInfo->hasFP(Fn)) {
546    int SFI = RS->getScavengingFrameIndex();
547    if (SFI >= 0)
548      AdjustStackOffset(FFI, SFI, StackGrowsDown, Offset, MaxAlign);
549  }
550
551  // Round up the size to a multiple of the alignment, but only if there are
552  // calls or alloca's in the function.  This ensures that any calls to
553  // subroutines have their stack frames suitable aligned.
554  // Also do this if we need runtime alignment of the stack.  In this case
555  // offsets will be relative to SP not FP; round up the stack size so this
556  // works.
557  if (!RegInfo->targetHandlesStackFrameRounding() &&
558      (FFI->hasCalls() || FFI->hasVarSizedObjects() ||
559       (RegInfo->needsStackRealignment(Fn) &&
560        FFI->getObjectIndexEnd() != 0))) {
561    // If we have reserved argument space for call sites in the function
562    // immediately on entry to the current function, count it as part of the
563    // overall stack size.
564    if (RegInfo->hasReservedCallFrame(Fn))
565      Offset += FFI->getMaxCallFrameSize();
566
567    unsigned AlignMask = std::max(TFI.getStackAlignment(),MaxAlign) - 1;
568    Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
569  }
570
571  // Update frame info to pretend that this is part of the stack...
572  FFI->setStackSize(Offset+TFI.getOffsetOfLocalArea());
573
574  // Remember the required stack alignment in case targets need it to perform
575  // dynamic stack alignment.
576  FFI->setMaxAlignment(MaxAlign);
577}
578
579
580/// insertPrologEpilogCode - Scan the function for modified callee saved
581/// registers, insert spill code for these callee saved registers, then add
582/// prolog and epilog code to the function.
583///
584void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
585  const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
586
587  // Add prologue to the function...
588  TRI->emitPrologue(Fn);
589
590  // Add epilogue to restore the callee-save registers in each exiting block
591  for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
592    // If last instruction is a return instruction, add an epilogue
593    if (!I->empty() && I->back().getDesc().isReturn())
594      TRI->emitEpilogue(Fn, *I);
595  }
596}
597
598
599/// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
600/// register references and actual offsets.
601///
602void PEI::replaceFrameIndices(MachineFunction &Fn) {
603  if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
604
605  const TargetMachine &TM = Fn.getTarget();
606  assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
607  const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
608  const TargetFrameInfo *TFI = TM.getFrameInfo();
609  bool StackGrowsDown =
610    TFI->getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
611  int FrameSetupOpcode   = TRI.getCallFrameSetupOpcode();
612  int FrameDestroyOpcode = TRI.getCallFrameDestroyOpcode();
613
614  for (MachineFunction::iterator BB = Fn.begin(),
615         E = Fn.end(); BB != E; ++BB) {
616    int SPAdj = 0;  // SP offset due to call frame setup / destroy.
617    if (RS) RS->enterBasicBlock(BB);
618
619    for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
620      if (I->getOpcode() == TargetInstrInfo::DECLARE) {
621        // Ignore it.
622        ++I;
623        continue;
624      }
625
626      if (I->getOpcode() == FrameSetupOpcode ||
627          I->getOpcode() == FrameDestroyOpcode) {
628        // Remember how much SP has been adjusted to create the call
629        // frame.
630        int Size = I->getOperand(0).getImm();
631
632        if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) ||
633            (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode))
634          Size = -Size;
635
636        SPAdj += Size;
637
638        MachineBasicBlock::iterator PrevI = BB->end();
639        if (I != BB->begin()) PrevI = prior(I);
640        TRI.eliminateCallFramePseudoInstr(Fn, *BB, I);
641
642        // Visit the instructions created by eliminateCallFramePseudoInstr().
643        if (PrevI == BB->end())
644          I = BB->begin();     // The replaced instr was the first in the block.
645        else
646          I = next(PrevI);
647        continue;
648      }
649
650      MachineInstr *MI = I;
651      bool DoIncr = true;
652      for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
653        if (MI->getOperand(i).isFI()) {
654          // Some instructions (e.g. inline asm instructions) can have
655          // multiple frame indices and/or cause eliminateFrameIndex
656          // to insert more than one instruction. We need the register
657          // scavenger to go through all of these instructions so that
658          // it can update its register information. We keep the
659          // iterator at the point before insertion so that we can
660          // revisit them in full.
661          bool AtBeginning = (I == BB->begin());
662          if (!AtBeginning) --I;
663
664          // If this instruction has a FrameIndex operand, we need to
665          // use that target machine register info object to eliminate
666          // it.
667
668          TRI.eliminateFrameIndex(MI, SPAdj, RS);
669
670          // Reset the iterator if we were at the beginning of the BB.
671          if (AtBeginning) {
672            I = BB->begin();
673            DoIncr = false;
674          }
675
676          MI = 0;
677          break;
678        }
679
680      if (DoIncr && I != BB->end()) ++I;
681
682      // Update register states.
683      if (RS && MI) RS->forward(MI);
684    }
685
686    assert(SPAdj == 0 && "Unbalanced call frame setup / destroy pairs?");
687  }
688}
689
690