PrologEpilogInserter.cpp revision ce48c1de828688b34cf5c2038fde23368a0a45f4
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    const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
209    if (Fn.getRegInfo().isPhysRegUsed(Reg)) {
210      // If the reg is modified, save it!
211      CSI.push_back(CalleeSavedInfo(Reg, RC));
212    } else {
213      for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
214           *AliasSet; ++AliasSet) {  // Check alias registers too.
215        if (Fn.getRegInfo().isPhysRegUsed(*AliasSet)) {
216          CSI.push_back(CalleeSavedInfo(Reg, RC));
217          break;
218        }
219      }
220    }
221  }
222
223  if (CSI.empty())
224    return;   // Early exit if no callee saved registers are modified!
225
226  unsigned NumFixedSpillSlots;
227  const TargetFrameInfo::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 = I->getRegClass();
236
237    int FrameIdx;
238    if (RegInfo->hasReservedSpillSlot(Fn, 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 TargetFrameInfo::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,
265                                        true, false);
266    }
267
268    I->setFrameIdx(FrameIdx);
269  }
270
271  MFI->setCalleeSavedInfo(CSI);
272}
273
274/// insertCSRSpillsAndRestores - Insert spill and restore code for
275/// callee saved registers used in the function, handling shrink wrapping.
276///
277void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
278  // Get callee saved register information.
279  MachineFrameInfo *MFI = Fn.getFrameInfo();
280  const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
281
282  MFI->setCalleeSavedInfoValid(true);
283
284  // Early exit if no callee saved registers are modified!
285  if (CSI.empty())
286    return;
287
288  const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
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 (!TII.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        TII.storeRegToStackSlot(*EntryBlock, I, CSI[i].getReg(), true,
303                                CSI[i].getFrameIdx(), CSI[i].getRegClass(),TRI);
304      }
305    }
306
307    // Restore using target interface.
308    for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) {
309      MachineBasicBlock* MBB = ReturnBlocks[ri];
310      I = MBB->end(); --I;
311
312      // Skip over all terminator instructions, which are part of the return
313      // sequence.
314      MachineBasicBlock::iterator I2 = I;
315      while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
316        I = I2;
317
318      bool AtStart = I == MBB->begin();
319      MachineBasicBlock::iterator BeforeI = I;
320      if (!AtStart)
321        --BeforeI;
322
323      // Restore all registers immediately before the return and any
324      // terminators that preceed it.
325      if (!TII.restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
326        for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
327          TII.loadRegFromStackSlot(*MBB, I, CSI[i].getReg(),
328                                   CSI[i].getFrameIdx(),
329                                   CSI[i].getRegClass(), TRI);
330          assert(I != MBB->begin() &&
331                 "loadRegFromStackSlot didn't insert any code!");
332          // Insert in reverse order.  loadRegFromStackSlot can insert
333          // multiple instructions.
334          if (AtStart)
335            I = MBB->begin();
336          else {
337            I = BeforeI;
338            ++I;
339          }
340        }
341      }
342    }
343    return;
344  }
345
346  // Insert spills.
347  std::vector<CalleeSavedInfo> blockCSI;
348  for (CSRegBlockMap::iterator BI = CSRSave.begin(),
349         BE = CSRSave.end(); BI != BE; ++BI) {
350    MachineBasicBlock* MBB = BI->first;
351    CSRegSet save = BI->second;
352
353    if (save.empty())
354      continue;
355
356    blockCSI.clear();
357    for (CSRegSet::iterator RI = save.begin(),
358           RE = save.end(); RI != RE; ++RI) {
359      blockCSI.push_back(CSI[*RI]);
360    }
361    assert(blockCSI.size() > 0 &&
362           "Could not collect callee saved register info");
363
364    I = MBB->begin();
365
366    // When shrink wrapping, use stack slot stores/loads.
367    for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
368      // Add the callee-saved register as live-in.
369      // It's killed at the spill.
370      MBB->addLiveIn(blockCSI[i].getReg());
371
372      // Insert the spill to the stack frame.
373      TII.storeRegToStackSlot(*MBB, I, blockCSI[i].getReg(),
374                              true,
375                              blockCSI[i].getFrameIdx(),
376                              blockCSI[i].getRegClass(), TRI);
377    }
378  }
379
380  for (CSRegBlockMap::iterator BI = CSRRestore.begin(),
381         BE = CSRRestore.end(); BI != BE; ++BI) {
382    MachineBasicBlock* MBB = BI->first;
383    CSRegSet restore = BI->second;
384
385    if (restore.empty())
386      continue;
387
388    blockCSI.clear();
389    for (CSRegSet::iterator RI = restore.begin(),
390           RE = restore.end(); RI != RE; ++RI) {
391      blockCSI.push_back(CSI[*RI]);
392    }
393    assert(blockCSI.size() > 0 &&
394           "Could not find callee saved register info");
395
396    // If MBB is empty and needs restores, insert at the _beginning_.
397    if (MBB->empty()) {
398      I = MBB->begin();
399    } else {
400      I = MBB->end();
401      --I;
402
403      // Skip over all terminator instructions, which are part of the
404      // return sequence.
405      if (! I->getDesc().isTerminator()) {
406        ++I;
407      } else {
408        MachineBasicBlock::iterator I2 = I;
409        while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
410          I = I2;
411      }
412    }
413
414    bool AtStart = I == MBB->begin();
415    MachineBasicBlock::iterator BeforeI = I;
416    if (!AtStart)
417      --BeforeI;
418
419    // Restore all registers immediately before the return and any
420    // terminators that preceed it.
421    for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
422      TII.loadRegFromStackSlot(*MBB, I, blockCSI[i].getReg(),
423                               blockCSI[i].getFrameIdx(),
424                               blockCSI[i].getRegClass(), TRI);
425      assert(I != MBB->begin() &&
426             "loadRegFromStackSlot didn't insert any code!");
427      // Insert in reverse order.  loadRegFromStackSlot can insert
428      // multiple instructions.
429      if (AtStart)
430        I = MBB->begin();
431      else {
432        I = BeforeI;
433        ++I;
434      }
435    }
436  }
437}
438
439/// AdjustStackOffset - Helper function used to adjust the stack frame offset.
440static inline void
441AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
442                  bool StackGrowsDown, int64_t &Offset,
443                  unsigned &MaxAlign) {
444  // If the stack grows down, add the object size to find the lowest address.
445  if (StackGrowsDown)
446    Offset += MFI->getObjectSize(FrameIdx);
447
448  unsigned Align = MFI->getObjectAlignment(FrameIdx);
449
450  // If the alignment of this object is greater than that of the stack, then
451  // increase the stack alignment to match.
452  MaxAlign = std::max(MaxAlign, Align);
453
454  // Adjust to alignment boundary.
455  Offset = (Offset + Align - 1) / Align * Align;
456
457  if (StackGrowsDown) {
458    MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
459  } else {
460    MFI->setObjectOffset(FrameIdx, Offset);
461    Offset += MFI->getObjectSize(FrameIdx);
462  }
463}
464
465/// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
466/// abstract stack objects.
467///
468void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
469  const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
470
471  bool StackGrowsDown =
472    TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
473
474  // Loop over all of the stack objects, assigning sequential addresses...
475  MachineFrameInfo *MFI = Fn.getFrameInfo();
476
477  // Start at the beginning of the local area.
478  // The Offset is the distance from the stack top in the direction
479  // of stack growth -- so it's always nonnegative.
480  int LocalAreaOffset = TFI.getOffsetOfLocalArea();
481  if (StackGrowsDown)
482    LocalAreaOffset = -LocalAreaOffset;
483  assert(LocalAreaOffset >= 0
484         && "Local area offset should be in direction of stack growth");
485  int64_t Offset = LocalAreaOffset;
486
487  // If there are fixed sized objects that are preallocated in the local area,
488  // non-fixed objects can't be allocated right at the start of local area.
489  // We currently don't support filling in holes in between fixed sized
490  // objects, so we adjust 'Offset' to point to the end of last fixed sized
491  // preallocated object.
492  for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
493    int64_t FixedOff;
494    if (StackGrowsDown) {
495      // The maximum distance from the stack pointer is at lower address of
496      // the object -- which is given by offset. For down growing stack
497      // the offset is negative, so we negate the offset to get the distance.
498      FixedOff = -MFI->getObjectOffset(i);
499    } else {
500      // The maximum distance from the start pointer is at the upper
501      // address of the object.
502      FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
503    }
504    if (FixedOff > Offset) Offset = FixedOff;
505  }
506
507  // First assign frame offsets to stack objects that are used to spill
508  // callee saved registers.
509  if (StackGrowsDown) {
510    for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
511      // If the stack grows down, we need to add the size to find the lowest
512      // address of the object.
513      Offset += MFI->getObjectSize(i);
514
515      unsigned Align = MFI->getObjectAlignment(i);
516      // Adjust to alignment boundary
517      Offset = (Offset+Align-1)/Align*Align;
518
519      MFI->setObjectOffset(i, -Offset);        // Set the computed offset
520    }
521  } else {
522    int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
523    for (int i = MaxCSFI; i >= MinCSFI ; --i) {
524      unsigned Align = MFI->getObjectAlignment(i);
525      // Adjust to alignment boundary
526      Offset = (Offset+Align-1)/Align*Align;
527
528      MFI->setObjectOffset(i, Offset);
529      Offset += MFI->getObjectSize(i);
530    }
531  }
532
533  unsigned MaxAlign = MFI->getMaxAlignment();
534
535  // Make sure the special register scavenging spill slot is closest to the
536  // frame pointer if a frame pointer is required.
537  const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
538  if (RS && RegInfo->hasFP(Fn) && !RegInfo->needsStackRealignment(Fn)) {
539    int SFI = RS->getScavengingFrameIndex();
540    if (SFI >= 0)
541      AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
542  }
543
544  // Make sure that the stack protector comes before the local variables on the
545  // stack.
546  if (MFI->getStackProtectorIndex() >= 0)
547    AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
548                      Offset, MaxAlign);
549
550  // Then assign frame offsets to stack objects that are not used to spill
551  // callee saved registers.
552  for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
553    if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
554      continue;
555    if (RS && (int)i == RS->getScavengingFrameIndex())
556      continue;
557    if (MFI->isDeadObjectIndex(i))
558      continue;
559    if (MFI->getStackProtectorIndex() == (int)i)
560      continue;
561
562    AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
563  }
564
565  // Make sure the special register scavenging spill slot is closest to the
566  // stack pointer.
567  if (RS && (!RegInfo->hasFP(Fn) || RegInfo->needsStackRealignment(Fn))) {
568    int SFI = RS->getScavengingFrameIndex();
569    if (SFI >= 0)
570      AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
571  }
572
573  if (!RegInfo->targetHandlesStackFrameRounding()) {
574    // If we have reserved argument space for call sites in the function
575    // immediately on entry to the current function, count it as part of the
576    // overall stack size.
577    if (MFI->adjustsStack() && RegInfo->hasReservedCallFrame(Fn))
578      Offset += MFI->getMaxCallFrameSize();
579
580    // Round up the size to a multiple of the alignment.  If the function has
581    // any calls or alloca's, align to the target's StackAlignment value to
582    // ensure that the callee's frame or the alloca data is suitably aligned;
583    // otherwise, for leaf functions, align to the TransientStackAlignment
584    // value.
585    unsigned StackAlign;
586    if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
587        (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
588      StackAlign = TFI.getStackAlignment();
589    else
590      StackAlign = TFI.getTransientStackAlignment();
591
592    // If the frame pointer is eliminated, all frame offsets will be relative to
593    // SP not FP. Align to MaxAlign so this works.
594    StackAlign = std::max(StackAlign, MaxAlign);
595    unsigned AlignMask = StackAlign - 1;
596    Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
597  }
598
599  // Update frame info to pretend that this is part of the stack...
600  MFI->setStackSize(Offset - LocalAreaOffset);
601}
602
603/// insertPrologEpilogCode - Scan the function for modified callee saved
604/// registers, insert spill code for these callee saved registers, then add
605/// prolog and epilog code to the function.
606///
607void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
608  const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
609
610  // Add prologue to the function...
611  TRI->emitPrologue(Fn);
612
613  // Add epilogue to restore the callee-save registers in each exiting block
614  for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
615    // If last instruction is a return instruction, add an epilogue
616    if (!I->empty() && I->back().getDesc().isReturn())
617      TRI->emitEpilogue(Fn, *I);
618  }
619}
620
621/// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
622/// register references and actual offsets.
623///
624void PEI::replaceFrameIndices(MachineFunction &Fn) {
625  if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
626
627  const TargetMachine &TM = Fn.getTarget();
628  assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
629  const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
630  const TargetFrameInfo *TFI = TM.getFrameInfo();
631  bool StackGrowsDown =
632    TFI->getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
633  int FrameSetupOpcode   = TRI.getCallFrameSetupOpcode();
634  int FrameDestroyOpcode = TRI.getCallFrameDestroyOpcode();
635
636  for (MachineFunction::iterator BB = Fn.begin(),
637         E = Fn.end(); BB != E; ++BB) {
638    int SPAdj = 0;  // SP offset due to call frame setup / destroy.
639    if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
640
641    for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
642
643      if (I->getOpcode() == FrameSetupOpcode ||
644          I->getOpcode() == FrameDestroyOpcode) {
645        // Remember how much SP has been adjusted to create the call
646        // frame.
647        int Size = I->getOperand(0).getImm();
648
649        if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) ||
650            (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode))
651          Size = -Size;
652
653        SPAdj += Size;
654
655        MachineBasicBlock::iterator PrevI = BB->end();
656        if (I != BB->begin()) PrevI = prior(I);
657        TRI.eliminateCallFramePseudoInstr(Fn, *BB, I);
658
659        // Visit the instructions created by eliminateCallFramePseudoInstr().
660        if (PrevI == BB->end())
661          I = BB->begin();     // The replaced instr was the first in the block.
662        else
663          I = llvm::next(PrevI);
664        continue;
665      }
666
667      MachineInstr *MI = I;
668      bool DoIncr = true;
669      for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
670        if (MI->getOperand(i).isFI()) {
671          // Some instructions (e.g. inline asm instructions) can have
672          // multiple frame indices and/or cause eliminateFrameIndex
673          // to insert more than one instruction. We need the register
674          // scavenger to go through all of these instructions so that
675          // it can update its register information. We keep the
676          // iterator at the point before insertion so that we can
677          // revisit them in full.
678          bool AtBeginning = (I == BB->begin());
679          if (!AtBeginning) --I;
680
681          // If this instruction has a FrameIndex operand, we need to
682          // use that target machine register info object to eliminate
683          // it.
684          TargetRegisterInfo::FrameIndexValue Value;
685          unsigned VReg =
686            TRI.eliminateFrameIndex(MI, SPAdj, &Value,
687                                    FrameIndexVirtualScavenging ?  NULL : RS);
688          if (VReg) {
689            assert (FrameIndexVirtualScavenging &&
690                    "Not scavenging, but virtual returned from "
691                    "eliminateFrameIndex()!");
692            FrameConstantRegMap[VReg] = FrameConstantEntry(Value, SPAdj);
693          }
694
695          // Reset the iterator if we were at the beginning of the BB.
696          if (AtBeginning) {
697            I = BB->begin();
698            DoIncr = false;
699          }
700
701          MI = 0;
702          break;
703        }
704
705      if (DoIncr && I != BB->end()) ++I;
706
707      // Update register states.
708      if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
709    }
710
711    assert(SPAdj == 0 && "Unbalanced call frame setup / destroy pairs?");
712  }
713}
714
715/// findLastUseReg - find the killing use of the specified register within
716/// the instruciton range. Return the operand number of the kill in Operand.
717static MachineBasicBlock::iterator
718findLastUseReg(MachineBasicBlock::iterator I, MachineBasicBlock::iterator ME,
719               unsigned Reg) {
720  // Scan forward to find the last use of this virtual register
721  for (++I; I != ME; ++I) {
722    MachineInstr *MI = I;
723    bool isDefInsn = false;
724    bool isKillInsn = false;
725    for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
726      if (MI->getOperand(i).isReg()) {
727        unsigned OpReg = MI->getOperand(i).getReg();
728        if (OpReg == 0 || !TargetRegisterInfo::isVirtualRegister(OpReg))
729          continue;
730        assert (OpReg == Reg
731                && "overlapping use of scavenged index register!");
732        // If this is the killing use, we have a candidate.
733        if (MI->getOperand(i).isKill())
734          isKillInsn = true;
735        else if (MI->getOperand(i).isDef())
736          isDefInsn = true;
737      }
738    if (isKillInsn && !isDefInsn)
739      return I;
740  }
741  // If we hit the end of the basic block, there was no kill of
742  // the virtual register, which is wrong.
743  assert (0 && "scavenged index register never killed!");
744  return ME;
745}
746
747/// scavengeFrameVirtualRegs - Replace all frame index virtual registers
748/// with physical registers. Use the register scavenger to find an
749/// appropriate register to use.
750void PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
751  // Run through the instructions and find any virtual registers.
752  for (MachineFunction::iterator BB = Fn.begin(),
753       E = Fn.end(); BB != E; ++BB) {
754    RS->enterBasicBlock(BB);
755
756    // FIXME: The logic flow in this function is still too convoluted.
757    // It needs a cleanup refactoring. Do that in preparation for tracking
758    // more than one scratch register value and using ranges to find
759    // available scratch registers.
760    unsigned CurrentVirtReg = 0;
761    unsigned CurrentScratchReg = 0;
762    bool havePrevValue = false;
763    TargetRegisterInfo::FrameIndexValue PrevValue(0,0);
764    TargetRegisterInfo::FrameIndexValue Value(0,0);
765    MachineInstr *PrevLastUseMI = NULL;
766    unsigned PrevLastUseOp = 0;
767    bool trackingCurrentValue = false;
768    int SPAdj = 0;
769
770    // The instruction stream may change in the loop, so check BB->end()
771    // directly.
772    for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
773      MachineInstr *MI = I;
774      bool isDefInsn = false;
775      bool isKillInsn = false;
776      bool clobbersScratchReg = false;
777      bool DoIncr = true;
778      for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
779        if (MI->getOperand(i).isReg()) {
780          MachineOperand &MO = MI->getOperand(i);
781          unsigned Reg = MO.getReg();
782          if (Reg == 0)
783            continue;
784          if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
785            // If we have a previous scratch reg, check and see if anything
786            // here kills whatever value is in there.
787            if (Reg == CurrentScratchReg) {
788              if (MO.isUse()) {
789                // Two-address operands implicitly kill
790                if (MO.isKill() || MI->isRegTiedToDefOperand(i))
791                  clobbersScratchReg = true;
792              } else {
793                assert (MO.isDef());
794                clobbersScratchReg = true;
795              }
796            }
797            continue;
798          }
799          // If this is a def, remember that this insn defines the value.
800          // This lets us properly consider insns which re-use the scratch
801          // register, such as r2 = sub r2, #imm, in the middle of the
802          // scratch range.
803          if (MO.isDef())
804            isDefInsn = true;
805
806          // Have we already allocated a scratch register for this virtual?
807          if (Reg != CurrentVirtReg) {
808            // When we first encounter a new virtual register, it
809            // must be a definition.
810            assert(MI->getOperand(i).isDef() &&
811                   "frame index virtual missing def!");
812            // We can't have nested virtual register live ranges because
813            // there's only a guarantee of one scavenged register at a time.
814            assert (CurrentVirtReg == 0 &&
815                    "overlapping frame index virtual registers!");
816
817            // If the target gave us information about what's in the register,
818            // we can use that to re-use scratch regs.
819            DenseMap<unsigned, FrameConstantEntry>::iterator Entry =
820              FrameConstantRegMap.find(Reg);
821            trackingCurrentValue = Entry != FrameConstantRegMap.end();
822            if (trackingCurrentValue) {
823              SPAdj = (*Entry).second.second;
824              Value = (*Entry).second.first;
825            } else {
826              SPAdj = 0;
827              Value.first = 0;
828              Value.second = 0;
829            }
830
831            // If the scratch register from the last allocation is still
832            // available, see if the value matches. If it does, just re-use it.
833            if (trackingCurrentValue && havePrevValue && PrevValue == Value) {
834              // FIXME: This assumes that the instructions in the live range
835              // for the virtual register are exclusively for the purpose
836              // of populating the value in the register. That's reasonable
837              // for these frame index registers, but it's still a very, very
838              // strong assumption. rdar://7322732. Better would be to
839              // explicitly check each instruction in the range for references
840              // to the virtual register. Only delete those insns that
841              // touch the virtual register.
842
843              // Find the last use of the new virtual register. Remove all
844              // instruction between here and there, and update the current
845              // instruction to reference the last use insn instead.
846              MachineBasicBlock::iterator LastUseMI =
847                findLastUseReg(I, BB->end(), Reg);
848
849              // Remove all instructions up 'til the last use, since they're
850              // just calculating the value we already have.
851              BB->erase(I, LastUseMI);
852              I = LastUseMI;
853
854              // Extend the live range of the scratch register
855              PrevLastUseMI->getOperand(PrevLastUseOp).setIsKill(false);
856              RS->setUsed(CurrentScratchReg);
857              CurrentVirtReg = Reg;
858
859              // We deleted the instruction we were scanning the operands of.
860              // Jump back to the instruction iterator loop. Don't increment
861              // past this instruction since we updated the iterator already.
862              DoIncr = false;
863              break;
864            }
865
866            // Scavenge a new scratch register
867            CurrentVirtReg = Reg;
868            const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
869            CurrentScratchReg = RS->FindUnusedReg(RC);
870            if (CurrentScratchReg == 0)
871              // No register is "free". Scavenge a register.
872              CurrentScratchReg = RS->scavengeRegister(RC, I, SPAdj);
873
874            PrevValue = Value;
875          }
876          // replace this reference to the virtual register with the
877          // scratch register.
878          assert (CurrentScratchReg && "Missing scratch register!");
879          MI->getOperand(i).setReg(CurrentScratchReg);
880
881          if (MI->getOperand(i).isKill()) {
882            isKillInsn = true;
883            PrevLastUseOp = i;
884            PrevLastUseMI = MI;
885          }
886        }
887      }
888      // If this is the last use of the scratch, stop tracking it. The
889      // last use will be a kill operand in an instruction that does
890      // not also define the scratch register.
891      if (isKillInsn && !isDefInsn) {
892        CurrentVirtReg = 0;
893        havePrevValue = trackingCurrentValue;
894      }
895      // Similarly, notice if instruction clobbered the value in the
896      // register we're tracking for possible later reuse. This is noted
897      // above, but enforced here since the value is still live while we
898      // process the rest of the operands of the instruction.
899      if (clobbersScratchReg) {
900        havePrevValue = false;
901        CurrentScratchReg = 0;
902      }
903      if (DoIncr) {
904        RS->forward(I);
905        ++I;
906      }
907    }
908  }
909}
910