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