PrologEpilogInserter.cpp revision e81abfd30b7c81735e9f3d79006c2653690aa592
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#define DEBUG_TYPE "pei"
23#include "PrologEpilogInserter.h"
24#include "llvm/InlineAsm.h"
25#include "llvm/CodeGen/MachineDominators.h"
26#include "llvm/CodeGen/MachineLoopInfo.h"
27#include "llvm/CodeGen/MachineInstr.h"
28#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineRegisterInfo.h"
30#include "llvm/CodeGen/RegisterScavenging.h"
31#include "llvm/Target/TargetMachine.h"
32#include "llvm/Target/TargetOptions.h"
33#include "llvm/Target/TargetRegisterInfo.h"
34#include "llvm/Target/TargetFrameLowering.h"
35#include "llvm/Target/TargetInstrInfo.h"
36#include "llvm/Support/CommandLine.h"
37#include "llvm/Support/Compiler.h"
38#include "llvm/Support/Debug.h"
39#include "llvm/ADT/IndexedMap.h"
40#include "llvm/ADT/SmallSet.h"
41#include "llvm/ADT/Statistic.h"
42#include "llvm/ADT/STLExtras.h"
43#include <climits>
44
45using namespace llvm;
46
47char PEI::ID = 0;
48
49INITIALIZE_PASS_BEGIN(PEI, "prologepilog",
50                "Prologue/Epilogue Insertion", false, false)
51INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
52INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
53INITIALIZE_PASS_END(PEI, "prologepilog",
54                "Prologue/Epilogue Insertion", false, false)
55
56STATISTIC(NumVirtualFrameRegs, "Number of virtual frame regs encountered");
57STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
58STATISTIC(NumBytesStackSpace, "Number of bytes used for stack in all functions");
59
60/// createPrologEpilogCodeInserter - This function returns a pass that inserts
61/// prolog and epilog code, and eliminates abstract frame references.
62///
63FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
64
65/// runOnMachineFunction - Insert prolog/epilog code and replace abstract
66/// frame indexes with appropriate references.
67///
68bool PEI::runOnMachineFunction(MachineFunction &Fn) {
69  const Function* F = Fn.getFunction();
70  const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
71  const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
72
73  RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL;
74  FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
75
76  // Calculate the MaxCallFrameSize and AdjustsStack variables for the
77  // function's frame information. Also eliminates call frame pseudo
78  // instructions.
79  calculateCallsInformation(Fn);
80
81  // Allow the target machine to make some adjustments to the function
82  // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
83  TFI->processFunctionBeforeCalleeSavedScan(Fn, RS);
84
85  // Scan the function for modified callee saved registers and insert spill code
86  // for any callee saved registers that are modified.
87  calculateCalleeSavedRegisters(Fn);
88
89  // Determine placement of CSR spill/restore code:
90  //  - With shrink wrapping, place spills and restores to tightly
91  //    enclose regions in the Machine CFG of the function where
92  //    they are used.
93  //  - Without shink wrapping (default), place all spills in the
94  //    entry block, all restores in return blocks.
95  placeCSRSpillsAndRestores(Fn);
96
97  // Add the code to save and restore the callee saved registers
98  if (!F->hasFnAttr(Attribute::Naked))
99    insertCSRSpillsAndRestores(Fn);
100
101  // Allow the target machine to make final modifications to the function
102  // before the frame layout is finalized.
103  TFI->processFunctionBeforeFrameFinalized(Fn);
104
105  // Calculate actual frame offsets for all abstract stack objects...
106  calculateFrameObjectOffsets(Fn);
107
108  // Add prolog and epilog code to the function.  This function is required
109  // to align the stack frame as necessary for any stack variables or
110  // called functions.  Because of this, calculateCalleeSavedRegisters()
111  // must be called before this function in order to set the AdjustsStack
112  // and MaxCallFrameSize variables.
113  if (!F->hasFnAttr(Attribute::Naked))
114    insertPrologEpilogCode(Fn);
115
116  // Replace all MO_FrameIndex operands with physical register references
117  // and actual offsets.
118  //
119  replaceFrameIndices(Fn);
120
121  // If register scavenging is needed, as we've enabled doing it as a
122  // post-pass, scavenge the virtual registers that frame index elimiation
123  // inserted.
124  if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
125    scavengeFrameVirtualRegs(Fn);
126
127  delete RS;
128  clearAllSets();
129  return true;
130}
131
132#if 0
133void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
134  AU.setPreservesCFG();
135  if (ShrinkWrapping || ShrinkWrapFunc != "") {
136    AU.addRequired<MachineLoopInfo>();
137    AU.addRequired<MachineDominatorTree>();
138  }
139  AU.addPreserved<MachineLoopInfo>();
140  AU.addPreserved<MachineDominatorTree>();
141  MachineFunctionPass::getAnalysisUsage(AU);
142}
143#endif
144
145/// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack
146/// variables for the function's frame information and eliminate call frame
147/// pseudo instructions.
148void PEI::calculateCallsInformation(MachineFunction &Fn) {
149  const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
150  const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
151  const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
152  MachineFrameInfo *MFI = Fn.getFrameInfo();
153
154  unsigned MaxCallFrameSize = 0;
155  bool AdjustsStack = MFI->adjustsStack();
156
157  // Get the function call frame set-up and tear-down instruction opcode
158  int FrameSetupOpcode   = TII.getCallFrameSetupOpcode();
159  int FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
160
161  // Early exit for targets which have no call frame setup/destroy pseudo
162  // instructions.
163  if (FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
164    return;
165
166  std::vector<MachineBasicBlock::iterator> FrameSDOps;
167  for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
168    for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
169      if (I->getOpcode() == FrameSetupOpcode ||
170          I->getOpcode() == FrameDestroyOpcode) {
171        assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
172               " instructions should have a single immediate argument!");
173        unsigned Size = I->getOperand(0).getImm();
174        if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
175        AdjustsStack = true;
176        FrameSDOps.push_back(I);
177      } else if (I->isInlineAsm()) {
178        // Some inline asm's need a stack frame, as indicated by operand 1.
179        unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
180        if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
181          AdjustsStack = true;
182      }
183
184  MFI->setAdjustsStack(AdjustsStack);
185  MFI->setMaxCallFrameSize(MaxCallFrameSize);
186
187  for (std::vector<MachineBasicBlock::iterator>::iterator
188         i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
189    MachineBasicBlock::iterator I = *i;
190
191    // If call frames are not being included as part of the stack frame, and
192    // the target doesn't indicate otherwise, remove the call frame pseudos
193    // here. The sub/add sp instruction pairs are still inserted, but we don't
194    // need to track the SP adjustment for frame index elimination.
195    if (TFI->canSimplifyCallFramePseudos(Fn))
196      RegInfo->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
197  }
198}
199
200
201/// calculateCalleeSavedRegisters - Scan the function for modified callee saved
202/// registers.
203void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
204  const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
205  const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
206  MachineFrameInfo *MFI = Fn.getFrameInfo();
207
208  // Get the callee saved register list...
209  const unsigned *CSRegs = RegInfo->getCalleeSavedRegs(&Fn);
210
211  // These are used to keep track the callee-save area. Initialize them.
212  MinCSFrameIndex = INT_MAX;
213  MaxCSFrameIndex = 0;
214
215  // Early exit for targets which have no callee saved registers.
216  if (CSRegs == 0 || CSRegs[0] == 0)
217    return;
218
219  // In Naked functions we aren't going to save any registers.
220  if (Fn.getFunction()->hasFnAttr(Attribute::Naked))
221    return;
222
223  std::vector<CalleeSavedInfo> CSI;
224  for (unsigned i = 0; CSRegs[i]; ++i) {
225    unsigned Reg = CSRegs[i];
226    if (Fn.getRegInfo().isPhysRegUsed(Reg)) {
227      // If the reg is modified, save it!
228      CSI.push_back(CalleeSavedInfo(Reg));
229    } else {
230      for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
231           *AliasSet; ++AliasSet) {  // Check alias registers too.
232        if (Fn.getRegInfo().isPhysRegUsed(*AliasSet)) {
233          CSI.push_back(CalleeSavedInfo(Reg));
234          break;
235        }
236      }
237    }
238  }
239
240  if (CSI.empty())
241    return;   // Early exit if no callee saved registers are modified!
242
243  unsigned NumFixedSpillSlots;
244  const TargetFrameLowering::SpillSlot *FixedSpillSlots =
245    TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
246
247  // Now that we know which registers need to be saved and restored, allocate
248  // stack slots for them.
249  for (std::vector<CalleeSavedInfo>::iterator
250         I = CSI.begin(), E = CSI.end(); I != E; ++I) {
251    unsigned Reg = I->getReg();
252    const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
253
254    int FrameIdx;
255    if (RegInfo->hasReservedSpillSlot(Fn, Reg, FrameIdx)) {
256      I->setFrameIdx(FrameIdx);
257      continue;
258    }
259
260    // Check to see if this physreg must be spilled to a particular stack slot
261    // on this target.
262    const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
263    while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
264           FixedSlot->Reg != Reg)
265      ++FixedSlot;
266
267    if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
268      // Nope, just spill it anywhere convenient.
269      unsigned Align = RC->getAlignment();
270      unsigned StackAlign = TFI->getStackAlignment();
271
272      // We may not be able to satisfy the desired alignment specification of
273      // the TargetRegisterClass if the stack alignment is smaller. Use the
274      // min.
275      Align = std::min(Align, StackAlign);
276      FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
277      if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
278      if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
279    } else {
280      // Spill it to the stack where we must.
281      FrameIdx = MFI->CreateFixedObject(RC->getSize(), FixedSlot->Offset, true);
282    }
283
284    I->setFrameIdx(FrameIdx);
285  }
286
287  MFI->setCalleeSavedInfo(CSI);
288}
289
290/// insertCSRSpillsAndRestores - Insert spill and restore code for
291/// callee saved registers used in the function, handling shrink wrapping.
292///
293void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
294  // Get callee saved register information.
295  MachineFrameInfo *MFI = Fn.getFrameInfo();
296  const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
297
298  MFI->setCalleeSavedInfoValid(true);
299
300  // Early exit if no callee saved registers are modified!
301  if (CSI.empty())
302    return;
303
304  const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
305  const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
306  const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
307  MachineBasicBlock::iterator I;
308
309  if (! ShrinkWrapThisFunction) {
310    // Spill using target interface.
311    I = EntryBlock->begin();
312    if (!TFI->spillCalleeSavedRegisters(*EntryBlock, I, CSI, TRI)) {
313      for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
314        // Add the callee-saved register as live-in.
315        // It's killed at the spill.
316        EntryBlock->addLiveIn(CSI[i].getReg());
317
318        // Insert the spill to the stack frame.
319        unsigned Reg = CSI[i].getReg();
320        const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
321        TII.storeRegToStackSlot(*EntryBlock, I, Reg, true,
322                                CSI[i].getFrameIdx(), RC, TRI);
323      }
324    }
325
326    // Restore using target interface.
327    for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) {
328      MachineBasicBlock* MBB = ReturnBlocks[ri];
329      I = MBB->end(); --I;
330
331      // Skip over all terminator instructions, which are part of the return
332      // sequence.
333      MachineBasicBlock::iterator I2 = I;
334      while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
335        I = I2;
336
337      bool AtStart = I == MBB->begin();
338      MachineBasicBlock::iterator BeforeI = I;
339      if (!AtStart)
340        --BeforeI;
341
342      // Restore all registers immediately before the return and any
343      // terminators that precede it.
344      if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
345        for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
346          unsigned Reg = CSI[i].getReg();
347          const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
348          TII.loadRegFromStackSlot(*MBB, I, Reg,
349                                   CSI[i].getFrameIdx(),
350                                   RC, TRI);
351          assert(I != MBB->begin() &&
352                 "loadRegFromStackSlot didn't insert any code!");
353          // Insert in reverse order.  loadRegFromStackSlot can insert
354          // multiple instructions.
355          if (AtStart)
356            I = MBB->begin();
357          else {
358            I = BeforeI;
359            ++I;
360          }
361        }
362      }
363    }
364    return;
365  }
366
367  // Insert spills.
368  std::vector<CalleeSavedInfo> blockCSI;
369  for (CSRegBlockMap::iterator BI = CSRSave.begin(),
370         BE = CSRSave.end(); BI != BE; ++BI) {
371    MachineBasicBlock* MBB = BI->first;
372    CSRegSet save = BI->second;
373
374    if (save.empty())
375      continue;
376
377    blockCSI.clear();
378    for (CSRegSet::iterator RI = save.begin(),
379           RE = save.end(); RI != RE; ++RI) {
380      blockCSI.push_back(CSI[*RI]);
381    }
382    assert(blockCSI.size() > 0 &&
383           "Could not collect callee saved register info");
384
385    I = MBB->begin();
386
387    // When shrink wrapping, use stack slot stores/loads.
388    for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
389      // Add the callee-saved register as live-in.
390      // It's killed at the spill.
391      MBB->addLiveIn(blockCSI[i].getReg());
392
393      // Insert the spill to the stack frame.
394      unsigned Reg = blockCSI[i].getReg();
395      const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
396      TII.storeRegToStackSlot(*MBB, I, Reg,
397                              true,
398                              blockCSI[i].getFrameIdx(),
399                              RC, TRI);
400    }
401  }
402
403  for (CSRegBlockMap::iterator BI = CSRRestore.begin(),
404         BE = CSRRestore.end(); BI != BE; ++BI) {
405    MachineBasicBlock* MBB = BI->first;
406    CSRegSet restore = BI->second;
407
408    if (restore.empty())
409      continue;
410
411    blockCSI.clear();
412    for (CSRegSet::iterator RI = restore.begin(),
413           RE = restore.end(); RI != RE; ++RI) {
414      blockCSI.push_back(CSI[*RI]);
415    }
416    assert(blockCSI.size() > 0 &&
417           "Could not find callee saved register info");
418
419    // If MBB is empty and needs restores, insert at the _beginning_.
420    if (MBB->empty()) {
421      I = MBB->begin();
422    } else {
423      I = MBB->end();
424      --I;
425
426      // Skip over all terminator instructions, which are part of the
427      // return sequence.
428      if (! I->getDesc().isTerminator()) {
429        ++I;
430      } else {
431        MachineBasicBlock::iterator I2 = I;
432        while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
433          I = I2;
434      }
435    }
436
437    bool AtStart = I == MBB->begin();
438    MachineBasicBlock::iterator BeforeI = I;
439    if (!AtStart)
440      --BeforeI;
441
442    // Restore all registers immediately before the return and any
443    // terminators that precede it.
444    for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
445      unsigned Reg = blockCSI[i].getReg();
446      const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
447      TII.loadRegFromStackSlot(*MBB, I, Reg,
448                               blockCSI[i].getFrameIdx(),
449                               RC, TRI);
450      assert(I != MBB->begin() &&
451             "loadRegFromStackSlot didn't insert any code!");
452      // Insert in reverse order.  loadRegFromStackSlot can insert
453      // multiple instructions.
454      if (AtStart)
455        I = MBB->begin();
456      else {
457        I = BeforeI;
458        ++I;
459      }
460    }
461  }
462}
463
464/// AdjustStackOffset - Helper function used to adjust the stack frame offset.
465static inline void
466AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
467                  bool StackGrowsDown, int64_t &Offset,
468                  unsigned &MaxAlign) {
469  // If the stack grows down, add the object size to find the lowest address.
470  if (StackGrowsDown)
471    Offset += MFI->getObjectSize(FrameIdx);
472
473  unsigned Align = MFI->getObjectAlignment(FrameIdx);
474
475  // If the alignment of this object is greater than that of the stack, then
476  // increase the stack alignment to match.
477  MaxAlign = std::max(MaxAlign, Align);
478
479  // Adjust to alignment boundary.
480  Offset = (Offset + Align - 1) / Align * Align;
481
482  if (StackGrowsDown) {
483    DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
484    MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
485  } else {
486    DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
487    MFI->setObjectOffset(FrameIdx, Offset);
488    Offset += MFI->getObjectSize(FrameIdx);
489  }
490}
491
492/// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
493/// abstract stack objects.
494///
495void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
496  const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
497
498  bool StackGrowsDown =
499    TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
500
501  // Loop over all of the stack objects, assigning sequential addresses...
502  MachineFrameInfo *MFI = Fn.getFrameInfo();
503
504  // Start at the beginning of the local area.
505  // The Offset is the distance from the stack top in the direction
506  // of stack growth -- so it's always nonnegative.
507  int LocalAreaOffset = TFI.getOffsetOfLocalArea();
508  if (StackGrowsDown)
509    LocalAreaOffset = -LocalAreaOffset;
510  assert(LocalAreaOffset >= 0
511         && "Local area offset should be in direction of stack growth");
512  int64_t Offset = LocalAreaOffset;
513
514  // If there are fixed sized objects that are preallocated in the local area,
515  // non-fixed objects can't be allocated right at the start of local area.
516  // We currently don't support filling in holes in between fixed sized
517  // objects, so we adjust 'Offset' to point to the end of last fixed sized
518  // preallocated object.
519  for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
520    int64_t FixedOff;
521    if (StackGrowsDown) {
522      // The maximum distance from the stack pointer is at lower address of
523      // the object -- which is given by offset. For down growing stack
524      // the offset is negative, so we negate the offset to get the distance.
525      FixedOff = -MFI->getObjectOffset(i);
526    } else {
527      // The maximum distance from the start pointer is at the upper
528      // address of the object.
529      FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
530    }
531    if (FixedOff > Offset) Offset = FixedOff;
532  }
533
534  // First assign frame offsets to stack objects that are used to spill
535  // callee saved registers.
536  if (StackGrowsDown) {
537    for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
538      // If the stack grows down, we need to add the size to find the lowest
539      // address of the object.
540      Offset += MFI->getObjectSize(i);
541
542      unsigned Align = MFI->getObjectAlignment(i);
543      // Adjust to alignment boundary
544      Offset = (Offset+Align-1)/Align*Align;
545
546      MFI->setObjectOffset(i, -Offset);        // Set the computed offset
547    }
548  } else {
549    int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
550    for (int i = MaxCSFI; i >= MinCSFI ; --i) {
551      unsigned Align = MFI->getObjectAlignment(i);
552      // Adjust to alignment boundary
553      Offset = (Offset+Align-1)/Align*Align;
554
555      MFI->setObjectOffset(i, Offset);
556      Offset += MFI->getObjectSize(i);
557    }
558  }
559
560  unsigned MaxAlign = MFI->getMaxAlignment();
561
562  // Make sure the special register scavenging spill slot is closest to the
563  // frame pointer if a frame pointer is required.
564  const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
565  if (RS && TFI.hasFP(Fn) && RegInfo->useFPForScavengingIndex(Fn) &&
566      !RegInfo->needsStackRealignment(Fn)) {
567    int SFI = RS->getScavengingFrameIndex();
568    if (SFI >= 0)
569      AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
570  }
571
572  // FIXME: Once this is working, then enable flag will change to a target
573  // check for whether the frame is large enough to want to use virtual
574  // frame index registers. Functions which don't want/need this optimization
575  // will continue to use the existing code path.
576  if (MFI->getUseLocalStackAllocationBlock()) {
577    unsigned Align = MFI->getLocalFrameMaxAlign();
578
579    // Adjust to alignment boundary.
580    Offset = (Offset + Align - 1) / Align * Align;
581
582    DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
583
584    // Resolve offsets for objects in the local block.
585    for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) {
586      std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i);
587      int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
588      DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
589            FIOffset << "]\n");
590      MFI->setObjectOffset(Entry.first, FIOffset);
591    }
592    // Allocate the local block
593    Offset += MFI->getLocalFrameSize();
594
595    MaxAlign = std::max(Align, MaxAlign);
596  }
597
598  // Make sure that the stack protector comes before the local variables on the
599  // stack.
600  SmallSet<int, 16> LargeStackObjs;
601  if (MFI->getStackProtectorIndex() >= 0) {
602    AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
603                      Offset, MaxAlign);
604
605    // Assign large stack objects first.
606    for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
607      if (MFI->isObjectPreAllocated(i) &&
608          MFI->getUseLocalStackAllocationBlock())
609        continue;
610      if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
611        continue;
612      if (RS && (int)i == RS->getScavengingFrameIndex())
613        continue;
614      if (MFI->isDeadObjectIndex(i))
615        continue;
616      if (MFI->getStackProtectorIndex() == (int)i)
617        continue;
618      if (!MFI->MayNeedStackProtector(i))
619        continue;
620
621      AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
622      LargeStackObjs.insert(i);
623    }
624  }
625
626  // Then assign frame offsets to stack objects that are not used to spill
627  // callee saved registers.
628  for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
629    if (MFI->isObjectPreAllocated(i) &&
630        MFI->getUseLocalStackAllocationBlock())
631      continue;
632    if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
633      continue;
634    if (RS && (int)i == RS->getScavengingFrameIndex())
635      continue;
636    if (MFI->isDeadObjectIndex(i))
637      continue;
638    if (MFI->getStackProtectorIndex() == (int)i)
639      continue;
640    if (LargeStackObjs.count(i))
641      continue;
642
643    AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
644  }
645
646  // Make sure the special register scavenging spill slot is closest to the
647  // stack pointer.
648  if (RS && (!TFI.hasFP(Fn) || RegInfo->needsStackRealignment(Fn) ||
649             !RegInfo->useFPForScavengingIndex(Fn))) {
650    int SFI = RS->getScavengingFrameIndex();
651    if (SFI >= 0)
652      AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
653  }
654
655  if (!TFI.targetHandlesStackFrameRounding()) {
656    // If we have reserved argument space for call sites in the function
657    // immediately on entry to the current function, count it as part of the
658    // overall stack size.
659    if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn))
660      Offset += MFI->getMaxCallFrameSize();
661
662    // Round up the size to a multiple of the alignment.  If the function has
663    // any calls or alloca's, align to the target's StackAlignment value to
664    // ensure that the callee's frame or the alloca data is suitably aligned;
665    // otherwise, for leaf functions, align to the TransientStackAlignment
666    // value.
667    unsigned StackAlign;
668    if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
669        (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
670      StackAlign = TFI.getStackAlignment();
671    else
672      StackAlign = TFI.getTransientStackAlignment();
673
674    // If the frame pointer is eliminated, all frame offsets will be relative to
675    // SP not FP. Align to MaxAlign so this works.
676    StackAlign = std::max(StackAlign, MaxAlign);
677    unsigned AlignMask = StackAlign - 1;
678    Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
679  }
680
681  // Update frame info to pretend that this is part of the stack...
682  int64_t StackSize = Offset - LocalAreaOffset;
683  MFI->setStackSize(StackSize);
684  NumBytesStackSpace += StackSize;
685}
686
687/// insertPrologEpilogCode - Scan the function for modified callee saved
688/// registers, insert spill code for these callee saved registers, then add
689/// prolog and epilog code to the function.
690///
691void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
692  const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
693
694  // Add prologue to the function...
695  TFI.emitPrologue(Fn);
696
697  // Add epilogue to restore the callee-save registers in each exiting block
698  for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
699    // If last instruction is a return instruction, add an epilogue
700    if (!I->empty() && I->back().getDesc().isReturn())
701      TFI.emitEpilogue(Fn, *I);
702  }
703
704  // Emit additional code that is required to support segmented stacks, if
705  // we've been asked for it.  This, when linked with a runtime with support
706  // for segmented stacks (libgcc is one), will result in allocating stack
707  // space in small chunks instead of one large contiguous block.
708  if (EnableSegmentedStacks)
709    TFI.adjustForSegmentedStacks(Fn);
710}
711
712/// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
713/// register references and actual offsets.
714///
715void PEI::replaceFrameIndices(MachineFunction &Fn) {
716  if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
717
718  const TargetMachine &TM = Fn.getTarget();
719  assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
720  const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
721  const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
722  const TargetFrameLowering *TFI = TM.getFrameLowering();
723  bool StackGrowsDown =
724    TFI->getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
725  int FrameSetupOpcode   = TII.getCallFrameSetupOpcode();
726  int FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
727
728  for (MachineFunction::iterator BB = Fn.begin(),
729         E = Fn.end(); BB != E; ++BB) {
730#ifndef NDEBUG
731    int SPAdjCount = 0; // frame setup / destroy count.
732#endif
733    int SPAdj = 0;  // SP offset due to call frame setup / destroy.
734    if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
735
736    for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
737
738      if (I->getOpcode() == FrameSetupOpcode ||
739          I->getOpcode() == FrameDestroyOpcode) {
740#ifndef NDEBUG
741        // Track whether we see even pairs of them
742        SPAdjCount += I->getOpcode() == FrameSetupOpcode ? 1 : -1;
743#endif
744        // Remember how much SP has been adjusted to create the call
745        // frame.
746        int Size = I->getOperand(0).getImm();
747
748        if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) ||
749            (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode))
750          Size = -Size;
751
752        SPAdj += Size;
753
754        MachineBasicBlock::iterator PrevI = BB->end();
755        if (I != BB->begin()) PrevI = prior(I);
756        TRI.eliminateCallFramePseudoInstr(Fn, *BB, I);
757
758        // Visit the instructions created by eliminateCallFramePseudoInstr().
759        if (PrevI == BB->end())
760          I = BB->begin();     // The replaced instr was the first in the block.
761        else
762          I = llvm::next(PrevI);
763        continue;
764      }
765
766      MachineInstr *MI = I;
767      bool DoIncr = true;
768      for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
769        if (MI->getOperand(i).isFI()) {
770          // Some instructions (e.g. inline asm instructions) can have
771          // multiple frame indices and/or cause eliminateFrameIndex
772          // to insert more than one instruction. We need the register
773          // scavenger to go through all of these instructions so that
774          // it can update its register information. We keep the
775          // iterator at the point before insertion so that we can
776          // revisit them in full.
777          bool AtBeginning = (I == BB->begin());
778          if (!AtBeginning) --I;
779
780          // If this instruction has a FrameIndex operand, we need to
781          // use that target machine register info object to eliminate
782          // it.
783          TRI.eliminateFrameIndex(MI, SPAdj,
784                                  FrameIndexVirtualScavenging ?  NULL : RS);
785
786          // Reset the iterator if we were at the beginning of the BB.
787          if (AtBeginning) {
788            I = BB->begin();
789            DoIncr = false;
790          }
791
792          MI = 0;
793          break;
794        }
795
796      if (DoIncr && I != BB->end()) ++I;
797
798      // Update register states.
799      if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
800    }
801
802    // If we have evenly matched pairs of frame setup / destroy instructions,
803    // make sure the adjustments come out to zero. If we don't have matched
804    // pairs, we can't be sure the missing bit isn't in another basic block
805    // due to a custom inserter playing tricks, so just asserting SPAdj==0
806    // isn't sufficient. See tMOVCC on Thumb1, for example.
807    assert((SPAdjCount || SPAdj == 0) &&
808           "Unbalanced call frame setup / destroy pairs?");
809  }
810}
811
812/// scavengeFrameVirtualRegs - Replace all frame index virtual registers
813/// with physical registers. Use the register scavenger to find an
814/// appropriate register to use.
815void PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
816  // Run through the instructions and find any virtual registers.
817  for (MachineFunction::iterator BB = Fn.begin(),
818       E = Fn.end(); BB != E; ++BB) {
819    RS->enterBasicBlock(BB);
820
821    unsigned VirtReg = 0;
822    unsigned ScratchReg = 0;
823    int SPAdj = 0;
824
825    // The instruction stream may change in the loop, so check BB->end()
826    // directly.
827    for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
828      MachineInstr *MI = I;
829      for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
830        if (MI->getOperand(i).isReg()) {
831          MachineOperand &MO = MI->getOperand(i);
832          unsigned Reg = MO.getReg();
833          if (Reg == 0)
834            continue;
835          if (!TargetRegisterInfo::isVirtualRegister(Reg))
836            continue;
837
838          ++NumVirtualFrameRegs;
839
840          // Have we already allocated a scratch register for this virtual?
841          if (Reg != VirtReg) {
842            // When we first encounter a new virtual register, it
843            // must be a definition.
844            assert(MI->getOperand(i).isDef() &&
845                   "frame index virtual missing def!");
846            // Scavenge a new scratch register
847            VirtReg = Reg;
848            const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
849            ScratchReg = RS->scavengeRegister(RC, I, SPAdj);
850            ++NumScavengedRegs;
851          }
852          // Replace this reference to the virtual register with the
853          // scratch register.
854          assert (ScratchReg && "Missing scratch register!");
855          MI->getOperand(i).setReg(ScratchReg);
856
857        }
858      }
859      RS->forward(I);
860      ++I;
861    }
862  }
863}
864