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