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