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