1 //===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass is responsible for finalizing the functions frame layout, saving
11 // callee saved registers, and for emitting prolog & epilog code for the
14 // This pass must be run after register allocation. After this pass is
15 // executed, it is illegal to construct MO_FrameIndex operands.
17 // This pass provides an optional shrink wrapping variant of prolog/epilog
18 // insertion, enabled via --shrink-wrap. See ShrinkWrapping.cpp.
20 //===----------------------------------------------------------------------===//
22 #define DEBUG_TYPE "pei"
23 #include "PrologEpilogInserter.h"
24 #include "llvm/CodeGen/MachineDominators.h"
25 #include "llvm/CodeGen/MachineLoopInfo.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineFrameInfo.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/Support/Debug.h"
37 #include "llvm/ADT/IndexedMap.h"
38 #include "llvm/ADT/SmallSet.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/ADT/STLExtras.h"
47 INITIALIZE_PASS_BEGIN(PEI, "prologepilog",
48 "Prologue/Epilogue Insertion", false, false)
49 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
50 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
51 INITIALIZE_PASS_END(PEI, "prologepilog",
52 "Prologue/Epilogue Insertion", false, false)
54 STATISTIC(NumVirtualFrameRegs, "Number of virtual frame regs encountered");
55 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
57 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
58 /// prolog and epilog code, and eliminates abstract frame references.
60 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
62 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
63 /// frame indexes with appropriate references.
65 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
66 const Function* F = Fn.getFunction();
67 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
68 const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
70 RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL;
71 FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
73 // Calculate the MaxCallFrameSize and AdjustsStack variables for the
74 // function's frame information. Also eliminates call frame pseudo
76 calculateCallsInformation(Fn);
78 // Allow the target machine to make some adjustments to the function
79 // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
80 TFI->processFunctionBeforeCalleeSavedScan(Fn, RS);
82 // Scan the function for modified callee saved registers and insert spill code
83 // for any callee saved registers that are modified.
84 calculateCalleeSavedRegisters(Fn);
86 // Determine placement of CSR spill/restore code:
87 // - With shrink wrapping, place spills and restores to tightly
88 // enclose regions in the Machine CFG of the function where
90 // - Without shink wrapping (default), place all spills in the
91 // entry block, all restores in return blocks.
92 placeCSRSpillsAndRestores(Fn);
94 // Add the code to save and restore the callee saved registers
95 if (!F->hasFnAttr(Attribute::Naked))
96 insertCSRSpillsAndRestores(Fn);
98 // Allow the target machine to make final modifications to the function
99 // before the frame layout is finalized.
100 TFI->processFunctionBeforeFrameFinalized(Fn);
102 // Calculate actual frame offsets for all abstract stack objects...
103 calculateFrameObjectOffsets(Fn);
105 // Add prolog and epilog code to the function. This function is required
106 // to align the stack frame as necessary for any stack variables or
107 // called functions. Because of this, calculateCalleeSavedRegisters()
108 // must be called before this function in order to set the AdjustsStack
109 // and MaxCallFrameSize variables.
110 if (!F->hasFnAttr(Attribute::Naked))
111 insertPrologEpilogCode(Fn);
113 // Replace all MO_FrameIndex operands with physical register references
114 // and actual offsets.
116 replaceFrameIndices(Fn);
118 // If register scavenging is needed, as we've enabled doing it as a
119 // post-pass, scavenge the virtual registers that frame index elimiation
121 if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
122 scavengeFrameVirtualRegs(Fn);
130 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
131 AU.setPreservesCFG();
132 if (ShrinkWrapping || ShrinkWrapFunc != "") {
133 AU.addRequired<MachineLoopInfo>();
134 AU.addRequired<MachineDominatorTree>();
136 AU.addPreserved<MachineLoopInfo>();
137 AU.addPreserved<MachineDominatorTree>();
138 MachineFunctionPass::getAnalysisUsage(AU);
142 /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack
143 /// variables for the function's frame information and eliminate call frame
144 /// pseudo instructions.
145 void PEI::calculateCallsInformation(MachineFunction &Fn) {
146 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
147 const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
148 MachineFrameInfo *MFI = Fn.getFrameInfo();
150 unsigned MaxCallFrameSize = 0;
151 bool AdjustsStack = MFI->adjustsStack();
153 // Get the function call frame set-up and tear-down instruction opcode
154 int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode();
155 int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
157 // Early exit for targets which have no call frame setup/destroy pseudo
159 if (FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
162 std::vector<MachineBasicBlock::iterator> FrameSDOps;
163 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
164 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
165 if (I->getOpcode() == FrameSetupOpcode ||
166 I->getOpcode() == FrameDestroyOpcode) {
167 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
168 " instructions should have a single immediate argument!");
169 unsigned Size = I->getOperand(0).getImm();
170 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
172 FrameSDOps.push_back(I);
173 } else if (I->isInlineAsm()) {
174 // Some inline asm's need a stack frame, as indicated by operand 1.
175 if (I->getOperand(1).getImm())
179 MFI->setAdjustsStack(AdjustsStack);
180 MFI->setMaxCallFrameSize(MaxCallFrameSize);
182 for (std::vector<MachineBasicBlock::iterator>::iterator
183 i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
184 MachineBasicBlock::iterator I = *i;
186 // If call frames are not being included as part of the stack frame, and
187 // the target doesn't indicate otherwise, remove the call frame pseudos
188 // here. The sub/add sp instruction pairs are still inserted, but we don't
189 // need to track the SP adjustment for frame index elimination.
190 if (TFI->canSimplifyCallFramePseudos(Fn))
191 RegInfo->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
196 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
198 void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
199 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
200 const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
201 MachineFrameInfo *MFI = Fn.getFrameInfo();
203 // Get the callee saved register list...
204 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs(&Fn);
206 // These are used to keep track the callee-save area. Initialize them.
207 MinCSFrameIndex = INT_MAX;
210 // Early exit for targets which have no callee saved registers.
211 if (CSRegs == 0 || CSRegs[0] == 0)
214 // In Naked functions we aren't going to save any registers.
215 if (Fn.getFunction()->hasFnAttr(Attribute::Naked))
218 std::vector<CalleeSavedInfo> CSI;
219 for (unsigned i = 0; CSRegs[i]; ++i) {
220 unsigned Reg = CSRegs[i];
221 if (Fn.getRegInfo().isPhysRegUsed(Reg)) {
222 // If the reg is modified, save it!
223 CSI.push_back(CalleeSavedInfo(Reg));
225 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
226 *AliasSet; ++AliasSet) { // Check alias registers too.
227 if (Fn.getRegInfo().isPhysRegUsed(*AliasSet)) {
228 CSI.push_back(CalleeSavedInfo(Reg));
236 return; // Early exit if no callee saved registers are modified!
238 unsigned NumFixedSpillSlots;
239 const TargetFrameInfo::SpillSlot *FixedSpillSlots =
240 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
242 // Now that we know which registers need to be saved and restored, allocate
243 // stack slots for them.
244 for (std::vector<CalleeSavedInfo>::iterator
245 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
246 unsigned Reg = I->getReg();
247 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
250 if (RegInfo->hasReservedSpillSlot(Fn, Reg, FrameIdx)) {
251 I->setFrameIdx(FrameIdx);
255 // Check to see if this physreg must be spilled to a particular stack slot
257 const TargetFrameInfo::SpillSlot *FixedSlot = FixedSpillSlots;
258 while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
259 FixedSlot->Reg != Reg)
262 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
263 // Nope, just spill it anywhere convenient.
264 unsigned Align = RC->getAlignment();
265 unsigned StackAlign = TFI->getStackAlignment();
267 // We may not be able to satisfy the desired alignment specification of
268 // the TargetRegisterClass if the stack alignment is smaller. Use the
270 Align = std::min(Align, StackAlign);
271 FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
272 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
273 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
275 // Spill it to the stack where we must.
276 FrameIdx = MFI->CreateFixedObject(RC->getSize(), FixedSlot->Offset, true);
279 I->setFrameIdx(FrameIdx);
282 MFI->setCalleeSavedInfo(CSI);
285 /// insertCSRSpillsAndRestores - Insert spill and restore code for
286 /// callee saved registers used in the function, handling shrink wrapping.
288 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
289 // Get callee saved register information.
290 MachineFrameInfo *MFI = Fn.getFrameInfo();
291 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
293 MFI->setCalleeSavedInfoValid(true);
295 // Early exit if no callee saved registers are modified!
299 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
300 const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
301 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
302 MachineBasicBlock::iterator I;
304 if (! ShrinkWrapThisFunction) {
305 // Spill using target interface.
306 I = EntryBlock->begin();
307 if (!TFI->spillCalleeSavedRegisters(*EntryBlock, I, CSI, TRI)) {
308 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
309 // Add the callee-saved register as live-in.
310 // It's killed at the spill.
311 EntryBlock->addLiveIn(CSI[i].getReg());
313 // Insert the spill to the stack frame.
314 unsigned Reg = CSI[i].getReg();
315 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
316 TII.storeRegToStackSlot(*EntryBlock, I, Reg, true,
317 CSI[i].getFrameIdx(), RC, TRI);
321 // Restore using target interface.
322 for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) {
323 MachineBasicBlock* MBB = ReturnBlocks[ri];
326 // Skip over all terminator instructions, which are part of the return
328 MachineBasicBlock::iterator I2 = I;
329 while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
332 bool AtStart = I == MBB->begin();
333 MachineBasicBlock::iterator BeforeI = I;
337 // Restore all registers immediately before the return and any
338 // terminators that preceed it.
339 if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
340 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
341 unsigned Reg = CSI[i].getReg();
342 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
343 TII.loadRegFromStackSlot(*MBB, I, Reg,
344 CSI[i].getFrameIdx(),
346 assert(I != MBB->begin() &&
347 "loadRegFromStackSlot didn't insert any code!");
348 // Insert in reverse order. loadRegFromStackSlot can insert
349 // multiple instructions.
363 std::vector<CalleeSavedInfo> blockCSI;
364 for (CSRegBlockMap::iterator BI = CSRSave.begin(),
365 BE = CSRSave.end(); BI != BE; ++BI) {
366 MachineBasicBlock* MBB = BI->first;
367 CSRegSet save = BI->second;
373 for (CSRegSet::iterator RI = save.begin(),
374 RE = save.end(); RI != RE; ++RI) {
375 blockCSI.push_back(CSI[*RI]);
377 assert(blockCSI.size() > 0 &&
378 "Could not collect callee saved register info");
382 // When shrink wrapping, use stack slot stores/loads.
383 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
384 // Add the callee-saved register as live-in.
385 // It's killed at the spill.
386 MBB->addLiveIn(blockCSI[i].getReg());
388 // Insert the spill to the stack frame.
389 unsigned Reg = blockCSI[i].getReg();
390 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
391 TII.storeRegToStackSlot(*MBB, I, Reg,
393 blockCSI[i].getFrameIdx(),
398 for (CSRegBlockMap::iterator BI = CSRRestore.begin(),
399 BE = CSRRestore.end(); BI != BE; ++BI) {
400 MachineBasicBlock* MBB = BI->first;
401 CSRegSet restore = BI->second;
407 for (CSRegSet::iterator RI = restore.begin(),
408 RE = restore.end(); RI != RE; ++RI) {
409 blockCSI.push_back(CSI[*RI]);
411 assert(blockCSI.size() > 0 &&
412 "Could not find callee saved register info");
414 // If MBB is empty and needs restores, insert at the _beginning_.
421 // Skip over all terminator instructions, which are part of the
423 if (! I->getDesc().isTerminator()) {
426 MachineBasicBlock::iterator I2 = I;
427 while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
432 bool AtStart = I == MBB->begin();
433 MachineBasicBlock::iterator BeforeI = I;
437 // Restore all registers immediately before the return and any
438 // terminators that preceed it.
439 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
440 unsigned Reg = blockCSI[i].getReg();
441 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
442 TII.loadRegFromStackSlot(*MBB, I, Reg,
443 blockCSI[i].getFrameIdx(),
445 assert(I != MBB->begin() &&
446 "loadRegFromStackSlot didn't insert any code!");
447 // Insert in reverse order. loadRegFromStackSlot can insert
448 // multiple instructions.
459 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
461 AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
462 bool StackGrowsDown, int64_t &Offset,
463 unsigned &MaxAlign) {
464 // If the stack grows down, add the object size to find the lowest address.
466 Offset += MFI->getObjectSize(FrameIdx);
468 unsigned Align = MFI->getObjectAlignment(FrameIdx);
470 // If the alignment of this object is greater than that of the stack, then
471 // increase the stack alignment to match.
472 MaxAlign = std::max(MaxAlign, Align);
474 // Adjust to alignment boundary.
475 Offset = (Offset + Align - 1) / Align * Align;
477 if (StackGrowsDown) {
478 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
479 MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
481 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
482 MFI->setObjectOffset(FrameIdx, Offset);
483 Offset += MFI->getObjectSize(FrameIdx);
487 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
488 /// abstract stack objects.
490 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
491 const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
493 bool StackGrowsDown =
494 TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
496 // Loop over all of the stack objects, assigning sequential addresses...
497 MachineFrameInfo *MFI = Fn.getFrameInfo();
499 // Start at the beginning of the local area.
500 // The Offset is the distance from the stack top in the direction
501 // of stack growth -- so it's always nonnegative.
502 int LocalAreaOffset = TFI.getOffsetOfLocalArea();
504 LocalAreaOffset = -LocalAreaOffset;
505 assert(LocalAreaOffset >= 0
506 && "Local area offset should be in direction of stack growth");
507 int64_t Offset = LocalAreaOffset;
509 // If there are fixed sized objects that are preallocated in the local area,
510 // non-fixed objects can't be allocated right at the start of local area.
511 // We currently don't support filling in holes in between fixed sized
512 // objects, so we adjust 'Offset' to point to the end of last fixed sized
513 // preallocated object.
514 for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
516 if (StackGrowsDown) {
517 // The maximum distance from the stack pointer is at lower address of
518 // the object -- which is given by offset. For down growing stack
519 // the offset is negative, so we negate the offset to get the distance.
520 FixedOff = -MFI->getObjectOffset(i);
522 // The maximum distance from the start pointer is at the upper
523 // address of the object.
524 FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
526 if (FixedOff > Offset) Offset = FixedOff;
529 // First assign frame offsets to stack objects that are used to spill
530 // callee saved registers.
531 if (StackGrowsDown) {
532 for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
533 // If the stack grows down, we need to add the size to find the lowest
534 // address of the object.
535 Offset += MFI->getObjectSize(i);
537 unsigned Align = MFI->getObjectAlignment(i);
538 // Adjust to alignment boundary
539 Offset = (Offset+Align-1)/Align*Align;
541 MFI->setObjectOffset(i, -Offset); // Set the computed offset
544 int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
545 for (int i = MaxCSFI; i >= MinCSFI ; --i) {
546 unsigned Align = MFI->getObjectAlignment(i);
547 // Adjust to alignment boundary
548 Offset = (Offset+Align-1)/Align*Align;
550 MFI->setObjectOffset(i, Offset);
551 Offset += MFI->getObjectSize(i);
555 unsigned MaxAlign = MFI->getMaxAlignment();
557 // Make sure the special register scavenging spill slot is closest to the
558 // frame pointer if a frame pointer is required.
559 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
560 if (RS && TFI.hasFP(Fn) && !RegInfo->needsStackRealignment(Fn)) {
561 int SFI = RS->getScavengingFrameIndex();
563 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
566 // FIXME: Once this is working, then enable flag will change to a target
567 // check for whether the frame is large enough to want to use virtual
568 // frame index registers. Functions which don't want/need this optimization
569 // will continue to use the existing code path.
570 if (MFI->getUseLocalStackAllocationBlock()) {
571 unsigned Align = MFI->getLocalFrameMaxAlign();
573 // Adjust to alignment boundary.
574 Offset = (Offset + Align - 1) / Align * Align;
576 DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
578 // Resolve offsets for objects in the local block.
579 for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) {
580 std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i);
581 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
582 DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
584 MFI->setObjectOffset(Entry.first, FIOffset);
586 // Allocate the local block
587 Offset += MFI->getLocalFrameSize();
589 MaxAlign = std::max(Align, MaxAlign);
592 // Make sure that the stack protector comes before the local variables on the
594 SmallSet<int, 16> LargeStackObjs;
595 if (MFI->getStackProtectorIndex() >= 0) {
596 AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
599 // Assign large stack objects first.
600 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
601 if (MFI->isObjectPreAllocated(i) &&
602 MFI->getUseLocalStackAllocationBlock())
604 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
606 if (RS && (int)i == RS->getScavengingFrameIndex())
608 if (MFI->isDeadObjectIndex(i))
610 if (MFI->getStackProtectorIndex() == (int)i)
612 if (!MFI->MayNeedStackProtector(i))
615 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
616 LargeStackObjs.insert(i);
620 // Then assign frame offsets to stack objects that are not used to spill
621 // callee saved registers.
622 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
623 if (MFI->isObjectPreAllocated(i) &&
624 MFI->getUseLocalStackAllocationBlock())
626 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
628 if (RS && (int)i == RS->getScavengingFrameIndex())
630 if (MFI->isDeadObjectIndex(i))
632 if (MFI->getStackProtectorIndex() == (int)i)
634 if (LargeStackObjs.count(i))
637 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
640 // Make sure the special register scavenging spill slot is closest to the
642 if (RS && (!TFI.hasFP(Fn) || RegInfo->needsStackRealignment(Fn))) {
643 int SFI = RS->getScavengingFrameIndex();
645 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
648 if (!TFI.targetHandlesStackFrameRounding()) {
649 // If we have reserved argument space for call sites in the function
650 // immediately on entry to the current function, count it as part of the
651 // overall stack size.
652 if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn))
653 Offset += MFI->getMaxCallFrameSize();
655 // Round up the size to a multiple of the alignment. If the function has
656 // any calls or alloca's, align to the target's StackAlignment value to
657 // ensure that the callee's frame or the alloca data is suitably aligned;
658 // otherwise, for leaf functions, align to the TransientStackAlignment
661 if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
662 (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
663 StackAlign = TFI.getStackAlignment();
665 StackAlign = TFI.getTransientStackAlignment();
667 // If the frame pointer is eliminated, all frame offsets will be relative to
668 // SP not FP. Align to MaxAlign so this works.
669 StackAlign = std::max(StackAlign, MaxAlign);
670 unsigned AlignMask = StackAlign - 1;
671 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
674 // Update frame info to pretend that this is part of the stack...
675 MFI->setStackSize(Offset - LocalAreaOffset);
678 /// insertPrologEpilogCode - Scan the function for modified callee saved
679 /// registers, insert spill code for these callee saved registers, then add
680 /// prolog and epilog code to the function.
682 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
683 const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
685 // Add prologue to the function...
686 TFI.emitPrologue(Fn);
688 // Add epilogue to restore the callee-save registers in each exiting block
689 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
690 // If last instruction is a return instruction, add an epilogue
691 if (!I->empty() && I->back().getDesc().isReturn())
692 TFI.emitEpilogue(Fn, *I);
696 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
697 /// register references and actual offsets.
699 void PEI::replaceFrameIndices(MachineFunction &Fn) {
700 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
702 const TargetMachine &TM = Fn.getTarget();
703 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
704 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
705 const TargetFrameInfo *TFI = TM.getFrameInfo();
706 bool StackGrowsDown =
707 TFI->getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
708 int FrameSetupOpcode = TRI.getCallFrameSetupOpcode();
709 int FrameDestroyOpcode = TRI.getCallFrameDestroyOpcode();
711 for (MachineFunction::iterator BB = Fn.begin(),
712 E = Fn.end(); BB != E; ++BB) {
714 int SPAdjCount = 0; // frame setup / destroy count.
716 int SPAdj = 0; // SP offset due to call frame setup / destroy.
717 if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
719 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
721 if (I->getOpcode() == FrameSetupOpcode ||
722 I->getOpcode() == FrameDestroyOpcode) {
724 // Track whether we see even pairs of them
725 SPAdjCount += I->getOpcode() == FrameSetupOpcode ? 1 : -1;
727 // Remember how much SP has been adjusted to create the call
729 int Size = I->getOperand(0).getImm();
731 if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) ||
732 (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode))
737 MachineBasicBlock::iterator PrevI = BB->end();
738 if (I != BB->begin()) PrevI = prior(I);
739 TRI.eliminateCallFramePseudoInstr(Fn, *BB, I);
741 // Visit the instructions created by eliminateCallFramePseudoInstr().
742 if (PrevI == BB->end())
743 I = BB->begin(); // The replaced instr was the first in the block.
745 I = llvm::next(PrevI);
749 MachineInstr *MI = I;
751 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
752 if (MI->getOperand(i).isFI()) {
753 // Some instructions (e.g. inline asm instructions) can have
754 // multiple frame indices and/or cause eliminateFrameIndex
755 // to insert more than one instruction. We need the register
756 // scavenger to go through all of these instructions so that
757 // it can update its register information. We keep the
758 // iterator at the point before insertion so that we can
759 // revisit them in full.
760 bool AtBeginning = (I == BB->begin());
761 if (!AtBeginning) --I;
763 // If this instruction has a FrameIndex operand, we need to
764 // use that target machine register info object to eliminate
766 TRI.eliminateFrameIndex(MI, SPAdj,
767 FrameIndexVirtualScavenging ? NULL : RS);
769 // Reset the iterator if we were at the beginning of the BB.
779 if (DoIncr && I != BB->end()) ++I;
781 // Update register states.
782 if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
785 // If we have evenly matched pairs of frame setup / destroy instructions,
786 // make sure the adjustments come out to zero. If we don't have matched
787 // pairs, we can't be sure the missing bit isn't in another basic block
788 // due to a custom inserter playing tricks, so just asserting SPAdj==0
789 // isn't sufficient. See tMOVCC on Thumb1, for example.
790 assert((SPAdjCount || SPAdj == 0) &&
791 "Unbalanced call frame setup / destroy pairs?");
795 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
796 /// with physical registers. Use the register scavenger to find an
797 /// appropriate register to use.
798 void PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
799 // Run through the instructions and find any virtual registers.
800 for (MachineFunction::iterator BB = Fn.begin(),
801 E = Fn.end(); BB != E; ++BB) {
802 RS->enterBasicBlock(BB);
804 unsigned VirtReg = 0;
805 unsigned ScratchReg = 0;
808 // The instruction stream may change in the loop, so check BB->end()
810 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
811 MachineInstr *MI = I;
813 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
814 if (MI->getOperand(i).isReg()) {
815 MachineOperand &MO = MI->getOperand(i);
816 unsigned Reg = MO.getReg();
819 if (!TargetRegisterInfo::isVirtualRegister(Reg))
822 ++NumVirtualFrameRegs;
824 // Have we already allocated a scratch register for this virtual?
825 if (Reg != VirtReg) {
826 // When we first encounter a new virtual register, it
827 // must be a definition.
828 assert(MI->getOperand(i).isDef() &&
829 "frame index virtual missing def!");
830 // Scavenge a new scratch register
832 const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
833 ScratchReg = RS->scavengeRegister(RC, I, SPAdj);
836 // Replace this reference to the virtual register with the
838 assert (ScratchReg && "Missing scratch register!");
839 MI->getOperand(i).setReg(ScratchReg);