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/InlineAsm.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/RegisterScavenging.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Target/TargetFrameLowering.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/ADT/IndexedMap.h"
39 #include "llvm/ADT/SmallSet.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/ADT/STLExtras.h"
48 INITIALIZE_PASS_BEGIN(PEI, "prologepilog",
49 "Prologue/Epilogue Insertion", false, false)
50 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
51 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
52 INITIALIZE_PASS_END(PEI, "prologepilog",
53 "Prologue/Epilogue Insertion", false, false)
55 STATISTIC(NumVirtualFrameRegs, "Number of virtual frame regs encountered");
56 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
57 STATISTIC(NumBytesStackSpace, "Number of bytes used for stack in all functions");
59 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
60 /// prolog and epilog code, and eliminates abstract frame references.
62 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
64 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
65 /// frame indexes with appropriate references.
67 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
68 const Function* F = Fn.getFunction();
69 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
70 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
72 RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL;
73 FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
75 // Calculate the MaxCallFrameSize and AdjustsStack variables for the
76 // function's frame information. Also eliminates call frame pseudo
78 calculateCallsInformation(Fn);
80 // Allow the target machine to make some adjustments to the function
81 // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
82 TFI->processFunctionBeforeCalleeSavedScan(Fn, RS);
84 // Scan the function for modified callee saved registers and insert spill code
85 // for any callee saved registers that are modified.
86 calculateCalleeSavedRegisters(Fn);
88 // Determine placement of CSR spill/restore code:
89 // - With shrink wrapping, place spills and restores to tightly
90 // enclose regions in the Machine CFG of the function where
92 // - Without shink wrapping (default), place all spills in the
93 // entry block, all restores in return blocks.
94 placeCSRSpillsAndRestores(Fn);
96 // Add the code to save and restore the callee saved registers
97 if (!F->hasFnAttr(Attribute::Naked))
98 insertCSRSpillsAndRestores(Fn);
100 // Allow the target machine to make final modifications to the function
101 // before the frame layout is finalized.
102 TFI->processFunctionBeforeFrameFinalized(Fn);
104 // Calculate actual frame offsets for all abstract stack objects...
105 calculateFrameObjectOffsets(Fn);
107 // Add prolog and epilog code to the function. This function is required
108 // to align the stack frame as necessary for any stack variables or
109 // called functions. Because of this, calculateCalleeSavedRegisters()
110 // must be called before this function in order to set the AdjustsStack
111 // and MaxCallFrameSize variables.
112 if (!F->hasFnAttr(Attribute::Naked))
113 insertPrologEpilogCode(Fn);
115 // Replace all MO_FrameIndex operands with physical register references
116 // and actual offsets.
118 replaceFrameIndices(Fn);
120 // If register scavenging is needed, as we've enabled doing it as a
121 // post-pass, scavenge the virtual registers that frame index elimiation
123 if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
124 scavengeFrameVirtualRegs(Fn);
132 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
133 AU.setPreservesCFG();
134 if (ShrinkWrapping || ShrinkWrapFunc != "") {
135 AU.addRequired<MachineLoopInfo>();
136 AU.addRequired<MachineDominatorTree>();
138 AU.addPreserved<MachineLoopInfo>();
139 AU.addPreserved<MachineDominatorTree>();
140 MachineFunctionPass::getAnalysisUsage(AU);
144 /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack
145 /// variables for the function's frame information and eliminate call frame
146 /// pseudo instructions.
147 void PEI::calculateCallsInformation(MachineFunction &Fn) {
148 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
149 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
150 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
151 MachineFrameInfo *MFI = Fn.getFrameInfo();
153 unsigned MaxCallFrameSize = 0;
154 bool AdjustsStack = MFI->adjustsStack();
156 // Get the function call frame set-up and tear-down instruction opcode
157 int FrameSetupOpcode = TII.getCallFrameSetupOpcode();
158 int FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
160 // Early exit for targets which have no call frame setup/destroy pseudo
162 if (FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
165 std::vector<MachineBasicBlock::iterator> FrameSDOps;
166 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
167 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
168 if (I->getOpcode() == FrameSetupOpcode ||
169 I->getOpcode() == FrameDestroyOpcode) {
170 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
171 " instructions should have a single immediate argument!");
172 unsigned Size = I->getOperand(0).getImm();
173 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
175 FrameSDOps.push_back(I);
176 } else if (I->isInlineAsm()) {
177 // Some inline asm's need a stack frame, as indicated by operand 1.
178 unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
179 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
183 MFI->setAdjustsStack(AdjustsStack);
184 MFI->setMaxCallFrameSize(MaxCallFrameSize);
186 for (std::vector<MachineBasicBlock::iterator>::iterator
187 i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
188 MachineBasicBlock::iterator I = *i;
190 // If call frames are not being included as part of the stack frame, and
191 // the target doesn't indicate otherwise, remove the call frame pseudos
192 // here. The sub/add sp instruction pairs are still inserted, but we don't
193 // need to track the SP adjustment for frame index elimination.
194 if (TFI->canSimplifyCallFramePseudos(Fn))
195 RegInfo->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
200 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
202 void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
203 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
204 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
205 MachineFrameInfo *MFI = Fn.getFrameInfo();
207 // Get the callee saved register list...
208 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs(&Fn);
210 // These are used to keep track the callee-save area. Initialize them.
211 MinCSFrameIndex = INT_MAX;
214 // Early exit for targets which have no callee saved registers.
215 if (CSRegs == 0 || CSRegs[0] == 0)
218 // In Naked functions we aren't going to save any registers.
219 if (Fn.getFunction()->hasFnAttr(Attribute::Naked))
222 std::vector<CalleeSavedInfo> CSI;
223 for (unsigned i = 0; CSRegs[i]; ++i) {
224 unsigned Reg = CSRegs[i];
225 if (Fn.getRegInfo().isPhysRegUsed(Reg)) {
226 // If the reg is modified, save it!
227 CSI.push_back(CalleeSavedInfo(Reg));
229 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
230 *AliasSet; ++AliasSet) { // Check alias registers too.
231 if (Fn.getRegInfo().isPhysRegUsed(*AliasSet)) {
232 CSI.push_back(CalleeSavedInfo(Reg));
240 return; // Early exit if no callee saved registers are modified!
242 unsigned NumFixedSpillSlots;
243 const TargetFrameLowering::SpillSlot *FixedSpillSlots =
244 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
246 // Now that we know which registers need to be saved and restored, allocate
247 // stack slots for them.
248 for (std::vector<CalleeSavedInfo>::iterator
249 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
250 unsigned Reg = I->getReg();
251 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
254 if (RegInfo->hasReservedSpillSlot(Fn, Reg, FrameIdx)) {
255 I->setFrameIdx(FrameIdx);
259 // Check to see if this physreg must be spilled to a particular stack slot
261 const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
262 while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
263 FixedSlot->Reg != Reg)
266 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
267 // Nope, just spill it anywhere convenient.
268 unsigned Align = RC->getAlignment();
269 unsigned StackAlign = TFI->getStackAlignment();
271 // We may not be able to satisfy the desired alignment specification of
272 // the TargetRegisterClass if the stack alignment is smaller. Use the
274 Align = std::min(Align, StackAlign);
275 FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
276 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
277 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
279 // Spill it to the stack where we must.
280 FrameIdx = MFI->CreateFixedObject(RC->getSize(), FixedSlot->Offset, true);
283 I->setFrameIdx(FrameIdx);
286 MFI->setCalleeSavedInfo(CSI);
289 /// insertCSRSpillsAndRestores - Insert spill and restore code for
290 /// callee saved registers used in the function, handling shrink wrapping.
292 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
293 // Get callee saved register information.
294 MachineFrameInfo *MFI = Fn.getFrameInfo();
295 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
297 MFI->setCalleeSavedInfoValid(true);
299 // Early exit if no callee saved registers are modified!
303 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
304 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
305 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
306 MachineBasicBlock::iterator I;
308 if (! ShrinkWrapThisFunction) {
309 // Spill using target interface.
310 I = EntryBlock->begin();
311 if (!TFI->spillCalleeSavedRegisters(*EntryBlock, I, CSI, TRI)) {
312 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
313 // Add the callee-saved register as live-in.
314 // It's killed at the spill.
315 EntryBlock->addLiveIn(CSI[i].getReg());
317 // Insert the spill to the stack frame.
318 unsigned Reg = CSI[i].getReg();
319 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
320 TII.storeRegToStackSlot(*EntryBlock, I, Reg, true,
321 CSI[i].getFrameIdx(), RC, TRI);
325 // Restore using target interface.
326 for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) {
327 MachineBasicBlock* MBB = ReturnBlocks[ri];
330 // Skip over all terminator instructions, which are part of the return
332 MachineBasicBlock::iterator I2 = I;
333 while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
336 bool AtStart = I == MBB->begin();
337 MachineBasicBlock::iterator BeforeI = I;
341 // Restore all registers immediately before the return and any
342 // terminators that precede it.
343 if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
344 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
345 unsigned Reg = CSI[i].getReg();
346 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
347 TII.loadRegFromStackSlot(*MBB, I, Reg,
348 CSI[i].getFrameIdx(),
350 assert(I != MBB->begin() &&
351 "loadRegFromStackSlot didn't insert any code!");
352 // Insert in reverse order. loadRegFromStackSlot can insert
353 // multiple instructions.
367 std::vector<CalleeSavedInfo> blockCSI;
368 for (CSRegBlockMap::iterator BI = CSRSave.begin(),
369 BE = CSRSave.end(); BI != BE; ++BI) {
370 MachineBasicBlock* MBB = BI->first;
371 CSRegSet save = BI->second;
377 for (CSRegSet::iterator RI = save.begin(),
378 RE = save.end(); RI != RE; ++RI) {
379 blockCSI.push_back(CSI[*RI]);
381 assert(blockCSI.size() > 0 &&
382 "Could not collect callee saved register info");
386 // When shrink wrapping, use stack slot stores/loads.
387 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
388 // Add the callee-saved register as live-in.
389 // It's killed at the spill.
390 MBB->addLiveIn(blockCSI[i].getReg());
392 // Insert the spill to the stack frame.
393 unsigned Reg = blockCSI[i].getReg();
394 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
395 TII.storeRegToStackSlot(*MBB, I, Reg,
397 blockCSI[i].getFrameIdx(),
402 for (CSRegBlockMap::iterator BI = CSRRestore.begin(),
403 BE = CSRRestore.end(); BI != BE; ++BI) {
404 MachineBasicBlock* MBB = BI->first;
405 CSRegSet restore = BI->second;
411 for (CSRegSet::iterator RI = restore.begin(),
412 RE = restore.end(); RI != RE; ++RI) {
413 blockCSI.push_back(CSI[*RI]);
415 assert(blockCSI.size() > 0 &&
416 "Could not find callee saved register info");
418 // If MBB is empty and needs restores, insert at the _beginning_.
425 // Skip over all terminator instructions, which are part of the
427 if (! I->getDesc().isTerminator()) {
430 MachineBasicBlock::iterator I2 = I;
431 while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
436 bool AtStart = I == MBB->begin();
437 MachineBasicBlock::iterator BeforeI = I;
441 // Restore all registers immediately before the return and any
442 // terminators that precede it.
443 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
444 unsigned Reg = blockCSI[i].getReg();
445 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
446 TII.loadRegFromStackSlot(*MBB, I, Reg,
447 blockCSI[i].getFrameIdx(),
449 assert(I != MBB->begin() &&
450 "loadRegFromStackSlot didn't insert any code!");
451 // Insert in reverse order. loadRegFromStackSlot can insert
452 // multiple instructions.
463 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
465 AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
466 bool StackGrowsDown, int64_t &Offset,
467 unsigned &MaxAlign) {
468 // If the stack grows down, add the object size to find the lowest address.
470 Offset += MFI->getObjectSize(FrameIdx);
472 unsigned Align = MFI->getObjectAlignment(FrameIdx);
474 // If the alignment of this object is greater than that of the stack, then
475 // increase the stack alignment to match.
476 MaxAlign = std::max(MaxAlign, Align);
478 // Adjust to alignment boundary.
479 Offset = (Offset + Align - 1) / Align * Align;
481 if (StackGrowsDown) {
482 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
483 MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
485 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
486 MFI->setObjectOffset(FrameIdx, Offset);
487 Offset += MFI->getObjectSize(FrameIdx);
491 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
492 /// abstract stack objects.
494 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
495 const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
497 bool StackGrowsDown =
498 TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
500 // Loop over all of the stack objects, assigning sequential addresses...
501 MachineFrameInfo *MFI = Fn.getFrameInfo();
503 // Start at the beginning of the local area.
504 // The Offset is the distance from the stack top in the direction
505 // of stack growth -- so it's always nonnegative.
506 int LocalAreaOffset = TFI.getOffsetOfLocalArea();
508 LocalAreaOffset = -LocalAreaOffset;
509 assert(LocalAreaOffset >= 0
510 && "Local area offset should be in direction of stack growth");
511 int64_t Offset = LocalAreaOffset;
513 // If there are fixed sized objects that are preallocated in the local area,
514 // non-fixed objects can't be allocated right at the start of local area.
515 // We currently don't support filling in holes in between fixed sized
516 // objects, so we adjust 'Offset' to point to the end of last fixed sized
517 // preallocated object.
518 for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
520 if (StackGrowsDown) {
521 // The maximum distance from the stack pointer is at lower address of
522 // the object -- which is given by offset. For down growing stack
523 // the offset is negative, so we negate the offset to get the distance.
524 FixedOff = -MFI->getObjectOffset(i);
526 // The maximum distance from the start pointer is at the upper
527 // address of the object.
528 FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
530 if (FixedOff > Offset) Offset = FixedOff;
533 // First assign frame offsets to stack objects that are used to spill
534 // callee saved registers.
535 if (StackGrowsDown) {
536 for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
537 // If the stack grows down, we need to add the size to find the lowest
538 // address of the object.
539 Offset += MFI->getObjectSize(i);
541 unsigned Align = MFI->getObjectAlignment(i);
542 // Adjust to alignment boundary
543 Offset = (Offset+Align-1)/Align*Align;
545 MFI->setObjectOffset(i, -Offset); // Set the computed offset
548 int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
549 for (int i = MaxCSFI; i >= MinCSFI ; --i) {
550 unsigned Align = MFI->getObjectAlignment(i);
551 // Adjust to alignment boundary
552 Offset = (Offset+Align-1)/Align*Align;
554 MFI->setObjectOffset(i, Offset);
555 Offset += MFI->getObjectSize(i);
559 unsigned MaxAlign = MFI->getMaxAlignment();
561 // Make sure the special register scavenging spill slot is closest to the
562 // frame pointer if a frame pointer is required.
563 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
564 if (RS && TFI.hasFP(Fn) && RegInfo->useFPForScavengingIndex(Fn) &&
565 !RegInfo->needsStackRealignment(Fn)) {
566 int SFI = RS->getScavengingFrameIndex();
568 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
571 // FIXME: Once this is working, then enable flag will change to a target
572 // check for whether the frame is large enough to want to use virtual
573 // frame index registers. Functions which don't want/need this optimization
574 // will continue to use the existing code path.
575 if (MFI->getUseLocalStackAllocationBlock()) {
576 unsigned Align = MFI->getLocalFrameMaxAlign();
578 // Adjust to alignment boundary.
579 Offset = (Offset + Align - 1) / Align * Align;
581 DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
583 // Resolve offsets for objects in the local block.
584 for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) {
585 std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i);
586 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
587 DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
589 MFI->setObjectOffset(Entry.first, FIOffset);
591 // Allocate the local block
592 Offset += MFI->getLocalFrameSize();
594 MaxAlign = std::max(Align, MaxAlign);
597 // Make sure that the stack protector comes before the local variables on the
599 SmallSet<int, 16> LargeStackObjs;
600 if (MFI->getStackProtectorIndex() >= 0) {
601 AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
604 // Assign large stack objects first.
605 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
606 if (MFI->isObjectPreAllocated(i) &&
607 MFI->getUseLocalStackAllocationBlock())
609 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
611 if (RS && (int)i == RS->getScavengingFrameIndex())
613 if (MFI->isDeadObjectIndex(i))
615 if (MFI->getStackProtectorIndex() == (int)i)
617 if (!MFI->MayNeedStackProtector(i))
620 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
621 LargeStackObjs.insert(i);
625 // Then assign frame offsets to stack objects that are not used to spill
626 // callee saved registers.
627 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
628 if (MFI->isObjectPreAllocated(i) &&
629 MFI->getUseLocalStackAllocationBlock())
631 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
633 if (RS && (int)i == RS->getScavengingFrameIndex())
635 if (MFI->isDeadObjectIndex(i))
637 if (MFI->getStackProtectorIndex() == (int)i)
639 if (LargeStackObjs.count(i))
642 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
645 // Make sure the special register scavenging spill slot is closest to the
647 if (RS && (!TFI.hasFP(Fn) || RegInfo->needsStackRealignment(Fn) ||
648 !RegInfo->useFPForScavengingIndex(Fn))) {
649 int SFI = RS->getScavengingFrameIndex();
651 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
654 if (!TFI.targetHandlesStackFrameRounding()) {
655 // If we have reserved argument space for call sites in the function
656 // immediately on entry to the current function, count it as part of the
657 // overall stack size.
658 if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn))
659 Offset += MFI->getMaxCallFrameSize();
661 // Round up the size to a multiple of the alignment. If the function has
662 // any calls or alloca's, align to the target's StackAlignment value to
663 // ensure that the callee's frame or the alloca data is suitably aligned;
664 // otherwise, for leaf functions, align to the TransientStackAlignment
667 if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
668 (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
669 StackAlign = TFI.getStackAlignment();
671 StackAlign = TFI.getTransientStackAlignment();
673 // If the frame pointer is eliminated, all frame offsets will be relative to
674 // SP not FP. Align to MaxAlign so this works.
675 StackAlign = std::max(StackAlign, MaxAlign);
676 unsigned AlignMask = StackAlign - 1;
677 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
680 // Update frame info to pretend that this is part of the stack...
681 int64_t StackSize = Offset - LocalAreaOffset;
682 MFI->setStackSize(StackSize);
683 NumBytesStackSpace += StackSize;
686 /// insertPrologEpilogCode - Scan the function for modified callee saved
687 /// registers, insert spill code for these callee saved registers, then add
688 /// prolog and epilog code to the function.
690 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
691 const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
693 // Add prologue to the function...
694 TFI.emitPrologue(Fn);
696 // Add epilogue to restore the callee-save registers in each exiting block
697 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
698 // If last instruction is a return instruction, add an epilogue
699 if (!I->empty() && I->back().getDesc().isReturn())
700 TFI.emitEpilogue(Fn, *I);
704 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
705 /// register references and actual offsets.
707 void PEI::replaceFrameIndices(MachineFunction &Fn) {
708 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
710 const TargetMachine &TM = Fn.getTarget();
711 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
712 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
713 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
714 const TargetFrameLowering *TFI = TM.getFrameLowering();
715 bool StackGrowsDown =
716 TFI->getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
717 int FrameSetupOpcode = TII.getCallFrameSetupOpcode();
718 int FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
720 for (MachineFunction::iterator BB = Fn.begin(),
721 E = Fn.end(); BB != E; ++BB) {
723 int SPAdjCount = 0; // frame setup / destroy count.
725 int SPAdj = 0; // SP offset due to call frame setup / destroy.
726 if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
728 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
730 if (I->getOpcode() == FrameSetupOpcode ||
731 I->getOpcode() == FrameDestroyOpcode) {
733 // Track whether we see even pairs of them
734 SPAdjCount += I->getOpcode() == FrameSetupOpcode ? 1 : -1;
736 // Remember how much SP has been adjusted to create the call
738 int Size = I->getOperand(0).getImm();
740 if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) ||
741 (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode))
746 MachineBasicBlock::iterator PrevI = BB->end();
747 if (I != BB->begin()) PrevI = prior(I);
748 TRI.eliminateCallFramePseudoInstr(Fn, *BB, I);
750 // Visit the instructions created by eliminateCallFramePseudoInstr().
751 if (PrevI == BB->end())
752 I = BB->begin(); // The replaced instr was the first in the block.
754 I = llvm::next(PrevI);
758 MachineInstr *MI = I;
760 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
761 if (MI->getOperand(i).isFI()) {
762 // Some instructions (e.g. inline asm instructions) can have
763 // multiple frame indices and/or cause eliminateFrameIndex
764 // to insert more than one instruction. We need the register
765 // scavenger to go through all of these instructions so that
766 // it can update its register information. We keep the
767 // iterator at the point before insertion so that we can
768 // revisit them in full.
769 bool AtBeginning = (I == BB->begin());
770 if (!AtBeginning) --I;
772 // If this instruction has a FrameIndex operand, we need to
773 // use that target machine register info object to eliminate
775 TRI.eliminateFrameIndex(MI, SPAdj,
776 FrameIndexVirtualScavenging ? NULL : RS);
778 // Reset the iterator if we were at the beginning of the BB.
788 if (DoIncr && I != BB->end()) ++I;
790 // Update register states.
791 if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
794 // If we have evenly matched pairs of frame setup / destroy instructions,
795 // make sure the adjustments come out to zero. If we don't have matched
796 // pairs, we can't be sure the missing bit isn't in another basic block
797 // due to a custom inserter playing tricks, so just asserting SPAdj==0
798 // isn't sufficient. See tMOVCC on Thumb1, for example.
799 assert((SPAdjCount || SPAdj == 0) &&
800 "Unbalanced call frame setup / destroy pairs?");
804 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
805 /// with physical registers. Use the register scavenger to find an
806 /// appropriate register to use.
807 void PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
808 // Run through the instructions and find any virtual registers.
809 for (MachineFunction::iterator BB = Fn.begin(),
810 E = Fn.end(); BB != E; ++BB) {
811 RS->enterBasicBlock(BB);
813 unsigned VirtReg = 0;
814 unsigned ScratchReg = 0;
817 // The instruction stream may change in the loop, so check BB->end()
819 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
820 MachineInstr *MI = I;
821 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
822 if (MI->getOperand(i).isReg()) {
823 MachineOperand &MO = MI->getOperand(i);
824 unsigned Reg = MO.getReg();
827 if (!TargetRegisterInfo::isVirtualRegister(Reg))
830 ++NumVirtualFrameRegs;
832 // Have we already allocated a scratch register for this virtual?
833 if (Reg != VirtReg) {
834 // When we first encounter a new virtual register, it
835 // must be a definition.
836 assert(MI->getOperand(i).isDef() &&
837 "frame index virtual missing def!");
838 // Scavenge a new scratch register
840 const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
841 ScratchReg = RS->scavengeRegister(RC, I, SPAdj);
844 // Replace this reference to the virtual register with the
846 assert (ScratchReg && "Missing scratch register!");
847 MI->getOperand(i).setReg(ScratchReg);