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