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