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