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