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