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