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