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