- Rename stackprotector_{prologue,epilogue} to stackprotector_{create,check}.
[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 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/RegisterScavenging.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Target/TargetFrameInfo.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include <climits>
33 using namespace llvm;
34
35 namespace {
36   struct VISIBILITY_HIDDEN PEI : public MachineFunctionPass {
37     static char ID;
38     PEI() : MachineFunctionPass(&ID) {}
39
40     const char *getPassName() const {
41       return "Prolog/Epilog Insertion & Frame Finalization";
42     }
43
44     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
45       AU.addPreservedID(MachineLoopInfoID);
46       AU.addPreservedID(MachineDominatorsID);
47       MachineFunctionPass::getAnalysisUsage(AU);
48     }
49
50     /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
51     /// frame indexes with appropriate references.
52     ///
53     bool runOnMachineFunction(MachineFunction &Fn) {
54       const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
55       RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL;
56
57       // Get MachineModuleInfo so that we can track the construction of the
58       // frame.
59       if (MachineModuleInfo *MMI = getAnalysisToUpdate<MachineModuleInfo>())
60         Fn.getFrameInfo()->setMachineModuleInfo(MMI);
61
62       // Allow the target machine to make some adjustments to the function
63       // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
64       TRI->processFunctionBeforeCalleeSavedScan(Fn, RS);
65
66       // Scan the function for modified callee saved registers and insert spill
67       // code for any callee saved registers that are modified.  Also calculate
68       // the MaxCallFrameSize and HasCalls variables for the function's frame
69       // information and eliminates call frame pseudo instructions.
70       calculateCalleeSavedRegisters(Fn);
71
72       // Add the code to save and restore the callee saved registers
73       saveCalleeSavedRegisters(Fn);
74
75       // Allow the target machine to make final modifications to the function
76       // before the frame layout is finalized.
77       TRI->processFunctionBeforeFrameFinalized(Fn);
78
79       // Calculate actual frame offsets for all of the abstract stack objects...
80       calculateFrameObjectOffsets(Fn);
81
82       // Add prolog and epilog code to the function.  This function is required
83       // to align the stack frame as necessary for any stack variables or
84       // called functions.  Because of this, calculateCalleeSavedRegisters
85       // must be called before this function in order to set the HasCalls
86       // and MaxCallFrameSize variables.
87       insertPrologEpilogCode(Fn);
88
89       // Replace all MO_FrameIndex operands with physical register references
90       // and actual offsets.
91       //
92       replaceFrameIndices(Fn);
93
94       delete RS;
95       return true;
96     }
97   
98   private:
99     RegScavenger *RS;
100
101     // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved
102     // stack frame indexes.
103     unsigned MinCSFrameIndex, MaxCSFrameIndex;
104
105     void calculateCalleeSavedRegisters(MachineFunction &Fn);
106     void saveCalleeSavedRegisters(MachineFunction &Fn);
107     void calculateFrameObjectOffsets(MachineFunction &Fn);
108     void replaceFrameIndices(MachineFunction &Fn);
109     void insertPrologEpilogCode(MachineFunction &Fn);
110   };
111   char PEI::ID = 0;
112 }
113
114
115 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
116 /// prolog and epilog code, and eliminates abstract frame references.
117 ///
118 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
119
120
121 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
122 /// registers.  Also calculate the MaxCallFrameSize and HasCalls variables for
123 /// the function's frame information and eliminates call frame pseudo
124 /// instructions.
125 ///
126 void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
127   const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
128   const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
129
130   // Get the callee saved register list...
131   const unsigned *CSRegs = RegInfo->getCalleeSavedRegs(&Fn);
132
133   // Get the function call frame set-up and tear-down instruction opcode
134   int FrameSetupOpcode   = RegInfo->getCallFrameSetupOpcode();
135   int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
136
137   // These are used to keep track the callee-save area. Initialize them.
138   MinCSFrameIndex = INT_MAX;
139   MaxCSFrameIndex = 0;
140
141   // Early exit for targets which have no callee saved registers and no call
142   // frame setup/destroy pseudo instructions.
143   if ((CSRegs == 0 || CSRegs[0] == 0) &&
144       FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
145     return;
146
147   unsigned MaxCallFrameSize = 0;
148   bool HasCalls = false;
149
150   std::vector<MachineBasicBlock::iterator> FrameSDOps;
151   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
152     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
153       if (I->getOpcode() == FrameSetupOpcode ||
154           I->getOpcode() == FrameDestroyOpcode) {
155         assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
156                " instructions should have a single immediate argument!");
157         unsigned Size = I->getOperand(0).getImm();
158         if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
159         HasCalls = true;
160         FrameSDOps.push_back(I);
161       }
162
163   MachineFrameInfo *FFI = Fn.getFrameInfo();
164   FFI->setHasCalls(HasCalls);
165   FFI->setMaxCallFrameSize(MaxCallFrameSize);
166
167   for (unsigned i = 0, e = FrameSDOps.size(); i != e; ++i) {
168     MachineBasicBlock::iterator I = FrameSDOps[i];
169     // If call frames are not being included as part of the stack frame,
170     // and there is no dynamic allocation (therefore referencing frame slots
171     // off sp), leave the pseudo ops alone. We'll eliminate them later.
172     if (RegInfo->hasReservedCallFrame(Fn) || RegInfo->hasFP(Fn))
173       RegInfo->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
174   }
175
176   // Now figure out which *callee saved* registers are modified by the current
177   // function, thus needing to be saved and restored in the prolog/epilog.
178   //
179   const TargetRegisterClass* const *CSRegClasses =
180     RegInfo->getCalleeSavedRegClasses(&Fn);
181   std::vector<CalleeSavedInfo> CSI;
182   for (unsigned i = 0; CSRegs[i]; ++i) {
183     unsigned Reg = CSRegs[i];
184     if (Fn.getRegInfo().isPhysRegUsed(Reg)) {
185         // If the reg is modified, save it!
186       CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
187     } else {
188       for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
189            *AliasSet; ++AliasSet) {  // Check alias registers too.
190         if (Fn.getRegInfo().isPhysRegUsed(*AliasSet)) {
191           CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
192           break;
193         }
194       }
195     }
196   }
197
198   if (CSI.empty())
199     return;   // Early exit if no callee saved registers are modified!
200
201   unsigned NumFixedSpillSlots;
202   const std::pair<unsigned,int> *FixedSpillSlots =
203     TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
204
205   // Now that we know which registers need to be saved and restored, allocate
206   // stack slots for them.
207   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
208     unsigned Reg = CSI[i].getReg();
209     const TargetRegisterClass *RC = CSI[i].getRegClass();
210
211     // Check to see if this physreg must be spilled to a particular stack slot
212     // on this target.
213     const std::pair<unsigned,int> *FixedSlot = FixedSpillSlots;
214     while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
215            FixedSlot->first != Reg)
216       ++FixedSlot;
217
218     int FrameIdx;
219     if (FixedSlot == FixedSpillSlots+NumFixedSpillSlots) {
220       // Nope, just spill it anywhere convenient.
221       unsigned Align = RC->getAlignment();
222       unsigned StackAlign = TFI->getStackAlignment();
223       // We may not be able to sastify the desired alignment specification of
224       // the TargetRegisterClass if the stack alignment is smaller. Use the min.
225       Align = std::min(Align, StackAlign);
226       FrameIdx = FFI->CreateStackObject(RC->getSize(), Align);
227       if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
228       if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
229     } else {
230       // Spill it to the stack where we must.
231       FrameIdx = FFI->CreateFixedObject(RC->getSize(), FixedSlot->second);
232     }
233     CSI[i].setFrameIdx(FrameIdx);
234   }
235
236   FFI->setCalleeSavedInfo(CSI);
237 }
238
239 /// saveCalleeSavedRegisters -  Insert spill code for any callee saved registers
240 /// that are modified in the function.
241 ///
242 void PEI::saveCalleeSavedRegisters(MachineFunction &Fn) {
243   // Get callee saved register information.
244   MachineFrameInfo *FFI = Fn.getFrameInfo();
245   const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
246   
247   // Early exit if no callee saved registers are modified!
248   if (CSI.empty())
249     return;
250
251   const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
252
253   // Now that we have a stack slot for each register to be saved, insert spill
254   // code into the entry block.
255   MachineBasicBlock *MBB = Fn.begin();
256   MachineBasicBlock::iterator I = MBB->begin();
257
258   if (!TII.spillCalleeSavedRegisters(*MBB, I, CSI)) {
259     for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
260       // Add the callee-saved register as live-in. It's killed at the spill.
261       MBB->addLiveIn(CSI[i].getReg());
262
263       // Insert the spill to the stack frame.
264       TII.storeRegToStackSlot(*MBB, I, CSI[i].getReg(), true,
265                                    CSI[i].getFrameIdx(), CSI[i].getRegClass());
266     }
267   }
268
269   // Add code to restore the callee-save registers in each exiting block.
270   for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI)
271     // If last instruction is a return instruction, add an epilogue.
272     if (!FI->empty() && FI->back().getDesc().isReturn()) {
273       MBB = FI;
274       I = MBB->end(); --I;
275
276       // Skip over all terminator instructions, which are part of the return
277       // sequence.
278       MachineBasicBlock::iterator I2 = I;
279       while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
280         I = I2;
281
282       bool AtStart = I == MBB->begin();
283       MachineBasicBlock::iterator BeforeI = I;
284       if (!AtStart)
285         --BeforeI;
286       
287       // Restore all registers immediately before the return and any terminators
288       // that preceed it.
289       if (!TII.restoreCalleeSavedRegisters(*MBB, I, CSI)) {
290         for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
291           TII.loadRegFromStackSlot(*MBB, I, CSI[i].getReg(),
292                                         CSI[i].getFrameIdx(),
293                                         CSI[i].getRegClass());
294           assert(I != MBB->begin() &&
295                  "loadRegFromStackSlot didn't insert any code!");
296           // Insert in reverse order.  loadRegFromStackSlot can insert multiple
297           // instructions.
298           if (AtStart)
299             I = MBB->begin();
300           else {
301             I = BeforeI;
302             ++I;
303           }
304         }
305       }
306     }
307 }
308
309
310 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
311 /// abstract stack objects.
312 ///
313 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
314   const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
315
316   bool StackGrowsDown =
317     TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
318
319   // Loop over all of the stack objects, assigning sequential addresses...
320   MachineFrameInfo *FFI = Fn.getFrameInfo();
321
322   unsigned MaxAlign = FFI->getMaxAlignment();
323
324   // Start at the beginning of the local area.
325   // The Offset is the distance from the stack top in the direction
326   // of stack growth -- so it's always nonnegative.
327   int64_t Offset = TFI.getOffsetOfLocalArea();
328   if (StackGrowsDown)
329     Offset = -Offset;
330   assert(Offset >= 0
331          && "Local area offset should be in direction of stack growth");
332
333   // If there are fixed sized objects that are preallocated in the local area,
334   // non-fixed objects can't be allocated right at the start of local area.
335   // We currently don't support filling in holes in between fixed sized objects,
336   // so we adjust 'Offset' to point to the end of last fixed sized
337   // preallocated object.
338   for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
339     int64_t FixedOff;
340     if (StackGrowsDown) {
341       // The maximum distance from the stack pointer is at lower address of
342       // the object -- which is given by offset. For down growing stack
343       // the offset is negative, so we negate the offset to get the distance.
344       FixedOff = -FFI->getObjectOffset(i);
345     } else {
346       // The maximum distance from the start pointer is at the upper
347       // address of the object.
348       FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i);
349     }
350     if (FixedOff > Offset) Offset = FixedOff;
351   }
352
353   // First assign frame offsets to stack objects that are used to spill
354   // callee saved registers.
355   if (StackGrowsDown) {
356     for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
357       // If stack grows down, we need to add size of find the lowest
358       // address of the object.
359       Offset += FFI->getObjectSize(i);
360
361       unsigned Align = FFI->getObjectAlignment(i);
362       // If the alignment of this object is greater than that of the stack, then
363       // increase the stack alignment to match.
364       MaxAlign = std::max(MaxAlign, Align);
365       // Adjust to alignment boundary
366       Offset = (Offset+Align-1)/Align*Align;
367
368       FFI->setObjectOffset(i, -Offset);        // Set the computed offset
369     }
370   } else {
371     int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
372     for (int i = MaxCSFI; i >= MinCSFI ; --i) {
373       unsigned Align = FFI->getObjectAlignment(i);
374       // If the alignment of this object is greater than that of the stack, then
375       // increase the stack alignment to match.
376       MaxAlign = std::max(MaxAlign, Align);
377       // Adjust to alignment boundary
378       Offset = (Offset+Align-1)/Align*Align;
379
380       FFI->setObjectOffset(i, Offset);
381       Offset += FFI->getObjectSize(i);
382     }
383   }
384
385   // Make sure the special register scavenging spill slot is closest to the
386   // frame pointer if a frame pointer is required.
387   const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
388   if (RS && RegInfo->hasFP(Fn)) {
389     int SFI = RS->getScavengingFrameIndex();
390     if (SFI >= 0) {
391       // If stack grows down, we need to add size of the lowest
392       // address of the object.
393       if (StackGrowsDown)
394         Offset += FFI->getObjectSize(SFI);
395
396       unsigned Align = FFI->getObjectAlignment(SFI);
397       // Adjust to alignment boundary
398       Offset = (Offset+Align-1)/Align*Align;
399
400       if (StackGrowsDown) {
401         FFI->setObjectOffset(SFI, -Offset);        // Set the computed offset
402       } else {
403         FFI->setObjectOffset(SFI, Offset);
404         Offset += FFI->getObjectSize(SFI);
405       }
406     }
407   }
408
409   // Make sure that the stack protector comes before the local variables on the
410   // stack.
411   if (FFI->getStackProtectorIndex() >= 0) {
412     int FI = FFI->getStackProtectorIndex();
413
414     // If stack grows down, we need to add size of find the lowest
415     // address of the object.
416     if (StackGrowsDown)
417       Offset += FFI->getObjectSize(FI);
418
419     unsigned Align = FFI->getObjectAlignment(FI);
420
421     // If the alignment of this object is greater than that of the stack, then
422     // increase the stack alignment to match.
423     MaxAlign = std::max(MaxAlign, Align);
424
425     // Adjust to alignment boundary.
426     Offset = (Offset + Align - 1) / Align * Align;
427
428     if (StackGrowsDown) {
429       FFI->setObjectOffset(FI, -Offset); // Set the computed offset
430     } else {
431       FFI->setObjectOffset(FI, Offset);
432       Offset += FFI->getObjectSize(FI);
433     }
434   }
435
436   // Then assign frame offsets to stack objects that are not used to spill
437   // callee saved registers.
438   for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
439     if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
440       continue;
441     if (RS && (int)i == RS->getScavengingFrameIndex())
442       continue;
443     if (FFI->isDeadObjectIndex(i))
444       continue;
445
446     // If stack grows down, we need to add size of find the lowest
447     // address of the object.
448     if (StackGrowsDown)
449       Offset += FFI->getObjectSize(i);
450
451     unsigned Align = FFI->getObjectAlignment(i);
452     // If the alignment of this object is greater than that of the stack, then
453     // increase the stack alignment to match.
454     MaxAlign = std::max(MaxAlign, Align);
455     // Adjust to alignment boundary
456     Offset = (Offset+Align-1)/Align*Align;
457
458     if (StackGrowsDown) {
459       FFI->setObjectOffset(i, -Offset);        // Set the computed offset
460     } else {
461       FFI->setObjectOffset(i, Offset);
462       Offset += FFI->getObjectSize(i);
463     }
464   }
465
466   // Make sure the special register scavenging spill slot is closest to the
467   // stack pointer.
468   if (RS && !RegInfo->hasFP(Fn)) {
469     int SFI = RS->getScavengingFrameIndex();
470     if (SFI >= 0) {
471       // If stack grows down, we need to add size of find the lowest
472       // address of the object.
473       if (StackGrowsDown)
474         Offset += FFI->getObjectSize(SFI);
475
476       unsigned Align = FFI->getObjectAlignment(SFI);
477       // If the alignment of this object is greater than that of the
478       // stack, then increase the stack alignment to match.
479       MaxAlign = std::max(MaxAlign, Align);
480       // Adjust to alignment boundary
481       Offset = (Offset+Align-1)/Align*Align;
482
483       if (StackGrowsDown) {
484         FFI->setObjectOffset(SFI, -Offset);        // Set the computed offset
485       } else {
486         FFI->setObjectOffset(SFI, Offset);
487         Offset += FFI->getObjectSize(SFI);
488       }
489     }
490   }
491
492   // Round up the size to a multiple of the alignment, but only if there are
493   // calls or alloca's in the function.  This ensures that any calls to
494   // subroutines have their stack frames suitable aligned.
495   // Also do this if we need runtime alignment of the stack.  In this case
496   // offsets will be relative to SP not FP; round up the stack size so this
497   // works.
498   if (!RegInfo->targetHandlesStackFrameRounding() &&
499       (FFI->hasCalls() || FFI->hasVarSizedObjects() || 
500        (RegInfo->needsStackRealignment(Fn) &&
501         FFI->getObjectIndexEnd() != 0))) {
502     // If we have reserved argument space for call sites in the function
503     // immediately on entry to the current function, count it as part of the
504     // overall stack size.
505     if (RegInfo->hasReservedCallFrame(Fn))
506       Offset += FFI->getMaxCallFrameSize();
507
508     unsigned AlignMask = std::max(TFI.getStackAlignment(),MaxAlign) - 1;
509     Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
510   }
511
512   // Update frame info to pretend that this is part of the stack...
513   FFI->setStackSize(Offset+TFI.getOffsetOfLocalArea());
514
515   // Remember the required stack alignment in case targets need it to perform
516   // dynamic stack alignment.
517   FFI->setMaxAlignment(MaxAlign);
518 }
519
520
521 /// insertPrologEpilogCode - Scan the function for modified callee saved
522 /// registers, insert spill code for these callee saved registers, then add
523 /// prolog and epilog code to the function.
524 ///
525 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
526   const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
527
528   // Add prologue to the function...
529   TRI->emitPrologue(Fn);
530
531   // Add epilogue to restore the callee-save registers in each exiting block
532   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
533     // If last instruction is a return instruction, add an epilogue
534     if (!I->empty() && I->back().getDesc().isReturn())
535       TRI->emitEpilogue(Fn, *I);
536   }
537 }
538
539
540 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
541 /// register references and actual offsets.
542 ///
543 void PEI::replaceFrameIndices(MachineFunction &Fn) {
544   if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
545
546   const TargetMachine &TM = Fn.getTarget();
547   assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
548   const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
549   const TargetFrameInfo *TFI = TM.getFrameInfo();
550   bool StackGrowsDown =
551     TFI->getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
552   int FrameSetupOpcode   = TRI.getCallFrameSetupOpcode();
553   int FrameDestroyOpcode = TRI.getCallFrameDestroyOpcode();
554
555   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
556     int SPAdj = 0;  // SP offset due to call frame setup / destroy.
557     if (RS) RS->enterBasicBlock(BB);
558     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
559       MachineInstr *MI = I;
560
561       if (I->getOpcode() == TargetInstrInfo::DECLARE) {
562         // Ignore it.
563         ++I;
564         continue;
565       }
566
567       if (I->getOpcode() == FrameSetupOpcode ||
568           I->getOpcode() == FrameDestroyOpcode) {
569         // Remember how much SP has been adjusted to create the call
570         // frame.
571         int Size = I->getOperand(0).getImm();
572
573         if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) ||
574             (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode))
575           Size = -Size;
576
577         SPAdj += Size;
578
579         MachineBasicBlock::iterator PrevI = prior(I);
580         TRI.eliminateCallFramePseudoInstr(Fn, *BB, I);
581
582         // Visit the instructions created by eliminateCallFramePseudoInstr().
583         I = next(PrevI);
584         continue;
585       }
586
587       bool DoIncr = true;
588
589       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
590         if (MI->getOperand(i).isFI()) {
591           // Some instructions (e.g. inline asm instructions) can have
592           // multiple frame indices and/or cause eliminateFrameIndex
593           // to insert more than one instruction. We need the register
594           // scavenger to go through all of these instructions so that
595           // it can update its register information. We keep the
596           // iterator at the point before insertion so that we can
597           // revisit them in full.
598           bool AtBeginning = (I == BB->begin());
599           if (!AtBeginning) --I;
600
601           // If this instruction has a FrameIndex operand, we need to
602           // use that target machine register info object to eliminate
603           // it.
604           TRI.eliminateFrameIndex(MI, SPAdj, RS);
605
606           // Reset the iterator if we were at the beginning of the BB.
607           if (AtBeginning) {
608             I = BB->begin();
609             DoIncr = false;
610           }
611
612           MI = 0;
613           break;
614         }
615
616       if (DoIncr) ++I;
617
618       // Update register states.
619       if (RS && MI) RS->forward(MI);
620     }
621
622     assert(SPAdj == 0 && "Unbalanced call frame setup / destroy pairs?");
623   }
624 }