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