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 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "pei"
20 #include "PrologEpilogInserter.h"
21 #include "llvm/ADT/IndexedMap.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineModuleInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/RegisterScavenging.h"
32 #include "llvm/IR/InlineAsm.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/DiagnosticInfo.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetFrameLowering.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
48 char &llvm::PrologEpilogCodeInserterID = PEI::ID;
50 static cl::opt<unsigned>
51 WarnStackSize("warn-stack-size", cl::Hidden, cl::init((unsigned)-1),
52 cl::desc("Warn for stack size bigger than the given"
55 INITIALIZE_PASS_BEGIN(PEI, "prologepilog",
56 "Prologue/Epilogue Insertion", false, false)
57 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
58 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
59 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
60 INITIALIZE_PASS_END(PEI, "prologepilog",
61 "Prologue/Epilogue Insertion & Frame Finalization",
64 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
65 STATISTIC(NumBytesStackSpace,
66 "Number of bytes used for stack in all functions");
68 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
70 AU.addPreserved<MachineLoopInfo>();
71 AU.addPreserved<MachineDominatorTree>();
72 AU.addRequired<TargetPassConfig>();
73 MachineFunctionPass::getAnalysisUsage(AU);
76 bool PEI::isReturnBlock(MachineBasicBlock* MBB) {
77 return (MBB && !MBB->empty() && MBB->back().isReturn());
80 /// Compute the set of return blocks
81 void PEI::calculateSets(MachineFunction &Fn) {
82 // Sets used to compute spill, restore placement sets.
83 const std::vector<CalleeSavedInfo> &CSI =
84 Fn.getFrameInfo()->getCalleeSavedInfo();
86 // If no CSRs used, we are done.
90 // Save refs to entry and return blocks.
91 EntryBlock = Fn.begin();
92 for (MachineFunction::iterator MBB = Fn.begin(), E = Fn.end();
94 if (isReturnBlock(MBB))
95 ReturnBlocks.push_back(MBB);
100 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
101 /// frame indexes with appropriate references.
103 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
104 const Function* F = Fn.getFunction();
105 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
106 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
108 assert(!Fn.getRegInfo().getNumVirtRegs() && "Regalloc must assign all vregs");
110 RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL;
111 FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
113 // Calculate the MaxCallFrameSize and AdjustsStack variables for the
114 // function's frame information. Also eliminates call frame pseudo
116 calculateCallsInformation(Fn);
118 // Allow the target machine to make some adjustments to the function
119 // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
120 TFI->processFunctionBeforeCalleeSavedScan(Fn, RS);
122 // Scan the function for modified callee saved registers and insert spill code
123 // for any callee saved registers that are modified.
124 calculateCalleeSavedRegisters(Fn);
126 // Determine placement of CSR spill/restore code:
127 // place all spills in the entry block, all restores in return blocks.
130 // Add the code to save and restore the callee saved registers
131 if (!F->hasFnAttribute(Attribute::Naked))
132 insertCSRSpillsAndRestores(Fn);
134 // Allow the target machine to make final modifications to the function
135 // before the frame layout is finalized.
136 TFI->processFunctionBeforeFrameFinalized(Fn, RS);
138 // Calculate actual frame offsets for all abstract stack objects...
139 calculateFrameObjectOffsets(Fn);
141 // Add prolog and epilog code to the function. This function is required
142 // to align the stack frame as necessary for any stack variables or
143 // called functions. Because of this, calculateCalleeSavedRegisters()
144 // must be called before this function in order to set the AdjustsStack
145 // and MaxCallFrameSize variables.
146 if (!F->hasFnAttribute(Attribute::Naked))
147 insertPrologEpilogCode(Fn);
149 // Replace all MO_FrameIndex operands with physical register references
150 // and actual offsets.
152 replaceFrameIndices(Fn);
154 // If register scavenging is needed, as we've enabled doing it as a
155 // post-pass, scavenge the virtual registers that frame index elimiation
157 if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
158 scavengeFrameVirtualRegs(Fn);
160 // Clear any vregs created by virtual scavenging.
161 Fn.getRegInfo().clearVirtRegs();
163 // Warn on stack size when we exceeds the given limit.
164 MachineFrameInfo *MFI = Fn.getFrameInfo();
165 uint64_t StackSize = MFI->getStackSize();
166 if (WarnStackSize.getNumOccurrences() > 0 && WarnStackSize < StackSize) {
167 DiagnosticInfoStackSize DiagStackSize(*F, StackSize);
168 F->getContext().diagnose(DiagStackSize);
172 ReturnBlocks.clear();
176 /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack
177 /// variables for the function's frame information and eliminate call frame
178 /// pseudo instructions.
179 void PEI::calculateCallsInformation(MachineFunction &Fn) {
180 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
181 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
182 MachineFrameInfo *MFI = Fn.getFrameInfo();
184 unsigned MaxCallFrameSize = 0;
185 bool AdjustsStack = MFI->adjustsStack();
187 // Get the function call frame set-up and tear-down instruction opcode
188 int FrameSetupOpcode = TII.getCallFrameSetupOpcode();
189 int FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
191 // Early exit for targets which have no call frame setup/destroy pseudo
193 if (FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
196 std::vector<MachineBasicBlock::iterator> FrameSDOps;
197 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
198 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
199 if (I->getOpcode() == FrameSetupOpcode ||
200 I->getOpcode() == FrameDestroyOpcode) {
201 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
202 " instructions should have a single immediate argument!");
203 unsigned Size = I->getOperand(0).getImm();
204 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
206 FrameSDOps.push_back(I);
207 } else if (I->isInlineAsm()) {
208 // Some inline asm's need a stack frame, as indicated by operand 1.
209 unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
210 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
214 MFI->setAdjustsStack(AdjustsStack);
215 MFI->setMaxCallFrameSize(MaxCallFrameSize);
217 for (std::vector<MachineBasicBlock::iterator>::iterator
218 i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
219 MachineBasicBlock::iterator I = *i;
221 // If call frames are not being included as part of the stack frame, and
222 // the target doesn't indicate otherwise, remove the call frame pseudos
223 // here. The sub/add sp instruction pairs are still inserted, but we don't
224 // need to track the SP adjustment for frame index elimination.
225 if (TFI->canSimplifyCallFramePseudos(Fn))
226 TFI->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
231 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
233 void PEI::calculateCalleeSavedRegisters(MachineFunction &F) {
234 const TargetRegisterInfo *RegInfo = F.getTarget().getRegisterInfo();
235 const TargetFrameLowering *TFI = F.getTarget().getFrameLowering();
236 MachineFrameInfo *MFI = F.getFrameInfo();
238 // Get the callee saved register list...
239 const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs(&F);
241 // These are used to keep track the callee-save area. Initialize them.
242 MinCSFrameIndex = INT_MAX;
245 // Early exit for targets which have no callee saved registers.
246 if (CSRegs == 0 || CSRegs[0] == 0)
249 // In Naked functions we aren't going to save any registers.
250 if (F.getFunction()->hasFnAttribute(Attribute::Naked))
253 std::vector<CalleeSavedInfo> CSI;
254 for (unsigned i = 0; CSRegs[i]; ++i) {
255 unsigned Reg = CSRegs[i];
256 // Functions which call __builtin_unwind_init get all their registers saved.
257 if (F.getRegInfo().isPhysRegUsed(Reg) || F.getMMI().callsUnwindInit()) {
258 // If the reg is modified, save it!
259 CSI.push_back(CalleeSavedInfo(Reg));
264 return; // Early exit if no callee saved registers are modified!
266 unsigned NumFixedSpillSlots;
267 const TargetFrameLowering::SpillSlot *FixedSpillSlots =
268 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
270 // Now that we know which registers need to be saved and restored, allocate
271 // stack slots for them.
272 for (std::vector<CalleeSavedInfo>::iterator
273 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
274 unsigned Reg = I->getReg();
275 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
278 if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) {
279 I->setFrameIdx(FrameIdx);
283 // Check to see if this physreg must be spilled to a particular stack slot
285 const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
286 while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
287 FixedSlot->Reg != Reg)
290 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
291 // Nope, just spill it anywhere convenient.
292 unsigned Align = RC->getAlignment();
293 unsigned StackAlign = TFI->getStackAlignment();
295 // We may not be able to satisfy the desired alignment specification of
296 // the TargetRegisterClass if the stack alignment is smaller. Use the
298 Align = std::min(Align, StackAlign);
299 FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
300 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
301 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
303 // Spill it to the stack where we must.
304 FrameIdx = MFI->CreateFixedObject(RC->getSize(), FixedSlot->Offset, true);
307 I->setFrameIdx(FrameIdx);
310 MFI->setCalleeSavedInfo(CSI);
313 /// insertCSRSpillsAndRestores - Insert spill and restore code for
314 /// callee saved registers used in the function.
316 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
317 // Get callee saved register information.
318 MachineFrameInfo *MFI = Fn.getFrameInfo();
319 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
321 MFI->setCalleeSavedInfoValid(true);
323 // Early exit if no callee saved registers are modified!
327 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
328 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
329 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
330 MachineBasicBlock::iterator I;
332 // Spill using target interface.
333 I = EntryBlock->begin();
334 if (!TFI->spillCalleeSavedRegisters(*EntryBlock, I, CSI, TRI)) {
335 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
336 // Add the callee-saved register as live-in.
337 // It's killed at the spill.
338 EntryBlock->addLiveIn(CSI[i].getReg());
340 // Insert the spill to the stack frame.
341 unsigned Reg = CSI[i].getReg();
342 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
343 TII.storeRegToStackSlot(*EntryBlock, I, Reg, true, CSI[i].getFrameIdx(),
348 // Restore using target interface.
349 for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) {
350 MachineBasicBlock *MBB = ReturnBlocks[ri];
354 // Skip over all terminator instructions, which are part of the return
356 MachineBasicBlock::iterator I2 = I;
357 while (I2 != MBB->begin() && (--I2)->isTerminator())
360 bool AtStart = I == MBB->begin();
361 MachineBasicBlock::iterator BeforeI = I;
365 // Restore all registers immediately before the return and any
366 // terminators that precede it.
367 if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
368 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
369 unsigned Reg = CSI[i].getReg();
370 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
371 TII.loadRegFromStackSlot(*MBB, I, Reg, CSI[i].getFrameIdx(), RC, TRI);
372 assert(I != MBB->begin() &&
373 "loadRegFromStackSlot didn't insert any code!");
374 // Insert in reverse order. loadRegFromStackSlot can insert
375 // multiple instructions.
387 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
389 AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
390 bool StackGrowsDown, int64_t &Offset,
391 unsigned &MaxAlign) {
392 // If the stack grows down, add the object size to find the lowest address.
394 Offset += MFI->getObjectSize(FrameIdx);
396 unsigned Align = MFI->getObjectAlignment(FrameIdx);
398 // If the alignment of this object is greater than that of the stack, then
399 // increase the stack alignment to match.
400 MaxAlign = std::max(MaxAlign, Align);
402 // Adjust to alignment boundary.
403 Offset = (Offset + Align - 1) / Align * Align;
405 if (StackGrowsDown) {
406 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
407 MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
409 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
410 MFI->setObjectOffset(FrameIdx, Offset);
411 Offset += MFI->getObjectSize(FrameIdx);
415 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
416 /// abstract stack objects.
418 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
419 const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
421 bool StackGrowsDown =
422 TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
424 // Loop over all of the stack objects, assigning sequential addresses...
425 MachineFrameInfo *MFI = Fn.getFrameInfo();
427 // Start at the beginning of the local area.
428 // The Offset is the distance from the stack top in the direction
429 // of stack growth -- so it's always nonnegative.
430 int LocalAreaOffset = TFI.getOffsetOfLocalArea();
432 LocalAreaOffset = -LocalAreaOffset;
433 assert(LocalAreaOffset >= 0
434 && "Local area offset should be in direction of stack growth");
435 int64_t Offset = LocalAreaOffset;
437 // If there are fixed sized objects that are preallocated in the local area,
438 // non-fixed objects can't be allocated right at the start of local area.
439 // We currently don't support filling in holes in between fixed sized
440 // objects, so we adjust 'Offset' to point to the end of last fixed sized
441 // preallocated object.
442 for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
444 if (StackGrowsDown) {
445 // The maximum distance from the stack pointer is at lower address of
446 // the object -- which is given by offset. For down growing stack
447 // the offset is negative, so we negate the offset to get the distance.
448 FixedOff = -MFI->getObjectOffset(i);
450 // The maximum distance from the start pointer is at the upper
451 // address of the object.
452 FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
454 if (FixedOff > Offset) Offset = FixedOff;
457 // First assign frame offsets to stack objects that are used to spill
458 // callee saved registers.
459 if (StackGrowsDown) {
460 for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
461 // If the stack grows down, we need to add the size to find the lowest
462 // address of the object.
463 Offset += MFI->getObjectSize(i);
465 unsigned Align = MFI->getObjectAlignment(i);
466 // Adjust to alignment boundary
467 Offset = (Offset+Align-1)/Align*Align;
469 MFI->setObjectOffset(i, -Offset); // Set the computed offset
472 int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
473 for (int i = MaxCSFI; i >= MinCSFI ; --i) {
474 unsigned Align = MFI->getObjectAlignment(i);
475 // Adjust to alignment boundary
476 Offset = (Offset+Align-1)/Align*Align;
478 MFI->setObjectOffset(i, Offset);
479 Offset += MFI->getObjectSize(i);
483 unsigned MaxAlign = MFI->getMaxAlignment();
485 // Make sure the special register scavenging spill slot is closest to the
486 // incoming stack pointer if a frame pointer is required and is closer
487 // to the incoming rather than the final stack pointer.
488 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
489 bool EarlyScavengingSlots = (TFI.hasFP(Fn) &&
490 TFI.isFPCloseToIncomingSP() &&
491 RegInfo->useFPForScavengingIndex(Fn) &&
492 !RegInfo->needsStackRealignment(Fn));
493 if (RS && EarlyScavengingSlots) {
494 SmallVector<int, 2> SFIs;
495 RS->getScavengingFrameIndices(SFIs);
496 for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
497 IE = SFIs.end(); I != IE; ++I)
498 AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign);
501 // FIXME: Once this is working, then enable flag will change to a target
502 // check for whether the frame is large enough to want to use virtual
503 // frame index registers. Functions which don't want/need this optimization
504 // will continue to use the existing code path.
505 if (MFI->getUseLocalStackAllocationBlock()) {
506 unsigned Align = MFI->getLocalFrameMaxAlign();
508 // Adjust to alignment boundary.
509 Offset = (Offset + Align - 1) / Align * Align;
511 DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
513 // Resolve offsets for objects in the local block.
514 for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) {
515 std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i);
516 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
517 DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
519 MFI->setObjectOffset(Entry.first, FIOffset);
521 // Allocate the local block
522 Offset += MFI->getLocalFrameSize();
524 MaxAlign = std::max(Align, MaxAlign);
527 // Make sure that the stack protector comes before the local variables on the
529 SmallSet<int, 16> LargeStackObjs;
530 if (MFI->getStackProtectorIndex() >= 0) {
531 AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
534 // Assign large stack objects first.
535 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
536 if (MFI->isObjectPreAllocated(i) &&
537 MFI->getUseLocalStackAllocationBlock())
539 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
541 if (RS && RS->isScavengingFrameIndex((int)i))
543 if (MFI->isDeadObjectIndex(i))
545 if (MFI->getStackProtectorIndex() == (int)i)
547 if (!MFI->MayNeedStackProtector(i))
550 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
551 LargeStackObjs.insert(i);
555 // Then assign frame offsets to stack objects that are not used to spill
556 // callee saved registers.
557 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
558 if (MFI->isObjectPreAllocated(i) &&
559 MFI->getUseLocalStackAllocationBlock())
561 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
563 if (RS && RS->isScavengingFrameIndex((int)i))
565 if (MFI->isDeadObjectIndex(i))
567 if (MFI->getStackProtectorIndex() == (int)i)
569 if (LargeStackObjs.count(i))
572 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
575 // Make sure the special register scavenging spill slot is closest to the
577 if (RS && !EarlyScavengingSlots) {
578 SmallVector<int, 2> SFIs;
579 RS->getScavengingFrameIndices(SFIs);
580 for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
581 IE = SFIs.end(); I != IE; ++I)
582 AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign);
585 if (!TFI.targetHandlesStackFrameRounding()) {
586 // If we have reserved argument space for call sites in the function
587 // immediately on entry to the current function, count it as part of the
588 // overall stack size.
589 if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn))
590 Offset += MFI->getMaxCallFrameSize();
592 // Round up the size to a multiple of the alignment. If the function has
593 // any calls or alloca's, align to the target's StackAlignment value to
594 // ensure that the callee's frame or the alloca data is suitably aligned;
595 // otherwise, for leaf functions, align to the TransientStackAlignment
598 if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
599 (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
600 StackAlign = TFI.getStackAlignment();
602 StackAlign = TFI.getTransientStackAlignment();
604 // If the frame pointer is eliminated, all frame offsets will be relative to
605 // SP not FP. Align to MaxAlign so this works.
606 StackAlign = std::max(StackAlign, MaxAlign);
607 unsigned AlignMask = StackAlign - 1;
608 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
611 // Update frame info to pretend that this is part of the stack...
612 int64_t StackSize = Offset - LocalAreaOffset;
613 MFI->setStackSize(StackSize);
614 NumBytesStackSpace += StackSize;
617 /// insertPrologEpilogCode - Scan the function for modified callee saved
618 /// registers, insert spill code for these callee saved registers, then add
619 /// prolog and epilog code to the function.
621 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
622 const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
624 // Add prologue to the function...
625 TFI.emitPrologue(Fn);
627 // Add epilogue to restore the callee-save registers in each exiting block
628 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
629 // If last instruction is a return instruction, add an epilogue
630 if (!I->empty() && I->back().isReturn())
631 TFI.emitEpilogue(Fn, *I);
634 // Emit additional code that is required to support segmented stacks, if
635 // we've been asked for it. This, when linked with a runtime with support
636 // for segmented stacks (libgcc is one), will result in allocating stack
637 // space in small chunks instead of one large contiguous block.
638 if (Fn.getTarget().Options.EnableSegmentedStacks)
639 TFI.adjustForSegmentedStacks(Fn);
641 // Emit additional code that is required to explicitly handle the stack in
642 // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
643 // approach is rather similar to that of Segmented Stacks, but it uses a
644 // different conditional check and another BIF for allocating more stack
646 if (Fn.getFunction()->getCallingConv() == CallingConv::HiPE)
647 TFI.adjustForHiPEPrologue(Fn);
650 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
651 /// register references and actual offsets.
653 void PEI::replaceFrameIndices(MachineFunction &Fn) {
654 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
656 // Store SPAdj at exit of a basic block.
657 SmallVector<int, 8> SPState;
658 SPState.resize(Fn.getNumBlockIDs());
659 SmallPtrSet<MachineBasicBlock*, 8> Reachable;
661 // Iterate over the reachable blocks in DFS order.
662 for (df_ext_iterator<MachineFunction*, SmallPtrSet<MachineBasicBlock*, 8> >
663 DFI = df_ext_begin(&Fn, Reachable), DFE = df_ext_end(&Fn, Reachable);
666 // Check the exit state of the DFS stack predecessor.
667 if (DFI.getPathLength() >= 2) {
668 MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
669 assert(Reachable.count(StackPred) &&
670 "DFS stack predecessor is already visited.\n");
671 SPAdj = SPState[StackPred->getNumber()];
673 MachineBasicBlock *BB = *DFI;
674 replaceFrameIndices(BB, Fn, SPAdj);
675 SPState[BB->getNumber()] = SPAdj;
678 // Handle the unreachable blocks.
679 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
680 if (Reachable.count(BB))
681 // Already handled in DFS traversal.
684 replaceFrameIndices(BB, Fn, SPAdj);
688 void PEI::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
690 const TargetMachine &TM = Fn.getTarget();
691 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
692 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
693 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
694 const TargetFrameLowering *TFI = TM.getFrameLowering();
695 bool StackGrowsDown =
696 TFI->getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
697 int FrameSetupOpcode = TII.getCallFrameSetupOpcode();
698 int FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
700 if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
702 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
704 if (I->getOpcode() == FrameSetupOpcode ||
705 I->getOpcode() == FrameDestroyOpcode) {
706 // Remember how much SP has been adjusted to create the call
708 int Size = I->getOperand(0).getImm();
710 if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) ||
711 (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode))
716 MachineBasicBlock::iterator PrevI = BB->end();
717 if (I != BB->begin()) PrevI = prior(I);
718 TFI->eliminateCallFramePseudoInstr(Fn, *BB, I);
720 // Visit the instructions created by eliminateCallFramePseudoInstr().
721 if (PrevI == BB->end())
722 I = BB->begin(); // The replaced instr was the first in the block.
724 I = llvm::next(PrevI);
728 MachineInstr *MI = I;
730 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
731 if (!MI->getOperand(i).isFI())
734 // Frame indicies in debug values are encoded in a target independent
735 // way with simply the frame index and offset rather than any
736 // target-specific addressing mode.
737 if (MI->isDebugValue() ||
738 MI->getOpcode() == TargetOpcode::STACKMAP ||
739 MI->getOpcode() == TargetOpcode::PATCHPOINT) {
740 assert((!MI->isDebugValue() || i == 0) &&
741 "Frame indicies can only appear as the first operand of a "
742 "DBG_VALUE machine instruction");
744 MachineOperand &Offset = MI->getOperand(i + 1);
745 Offset.setImm(Offset.getImm() +
746 TFI->getFrameIndexReference(
747 Fn, MI->getOperand(i).getIndex(), Reg));
748 MI->getOperand(i).ChangeToRegister(Reg, false /*isDef*/);
752 // Some instructions (e.g. inline asm instructions) can have
753 // multiple frame indices and/or cause eliminateFrameIndex
754 // to insert more than one instruction. We need the register
755 // scavenger to go through all of these instructions so that
756 // it can update its register information. We keep the
757 // iterator at the point before insertion so that we can
758 // revisit them in full.
759 bool AtBeginning = (I == BB->begin());
760 if (!AtBeginning) --I;
762 // If this instruction has a FrameIndex operand, we need to
763 // use that target machine register info object to eliminate
765 TRI.eliminateFrameIndex(MI, SPAdj, i,
766 FrameIndexVirtualScavenging ? NULL : RS);
768 // Reset the iterator if we were at the beginning of the BB.
778 if (DoIncr && I != BB->end()) ++I;
780 // Update register states.
781 if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
785 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
786 /// with physical registers. Use the register scavenger to find an
787 /// appropriate register to use.
789 /// FIXME: Iterating over the instruction stream is unnecessary. We can simply
790 /// iterate over the vreg use list, which at this point only contains machine
791 /// operands for which eliminateFrameIndex need a new scratch reg.
792 void PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
793 // Run through the instructions and find any virtual registers.
794 for (MachineFunction::iterator BB = Fn.begin(),
795 E = Fn.end(); BB != E; ++BB) {
796 RS->enterBasicBlock(BB);
800 // The instruction stream may change in the loop, so check BB->end()
802 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
803 // We might end up here again with a NULL iterator if we scavenged a
804 // register for which we inserted spill code for definition by what was
805 // originally the first instruction in BB.
806 if (I == MachineBasicBlock::iterator(NULL))
809 MachineInstr *MI = I;
810 MachineBasicBlock::iterator J = llvm::next(I);
811 MachineBasicBlock::iterator P = I == BB->begin() ?
812 MachineBasicBlock::iterator(NULL) : llvm::prior(I);
814 // RS should process this instruction before we might scavenge at this
815 // location. This is because we might be replacing a virtual register
816 // defined by this instruction, and if so, registers killed by this
817 // instruction are available, and defined registers are not.
820 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
821 if (MI->getOperand(i).isReg()) {
822 MachineOperand &MO = MI->getOperand(i);
823 unsigned Reg = MO.getReg();
826 if (!TargetRegisterInfo::isVirtualRegister(Reg))
829 // When we first encounter a new virtual register, it
830 // must be a definition.
831 assert(MI->getOperand(i).isDef() &&
832 "frame index virtual missing def!");
833 // Scavenge a new scratch register
834 const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
835 unsigned ScratchReg = RS->scavengeRegister(RC, J, SPAdj);
839 // Replace this reference to the virtual register with the
841 assert (ScratchReg && "Missing scratch register!");
842 Fn.getRegInfo().replaceRegWith(Reg, ScratchReg);
844 // Because this instruction was processed by the RS before this
845 // register was allocated, make sure that the RS now records the
846 // register as being used.
847 RS->setUsed(ScratchReg);
851 // If the scavenger needed to use one of its spill slots, the
852 // spill code will have been inserted in between I and J. This is a
853 // problem because we need the spill code before I: Move I to just
855 if (I != llvm::prior(J)) {
856 BB->splice(J, BB, I);
858 // Before we move I, we need to prepare the RS to visit I again.
859 // Specifically, RS will assert if it sees uses of registers that
860 // it believes are undefined. Because we have already processed
861 // register kills in I, when it visits I again, it will believe that
862 // those registers are undefined. To avoid this situation, unprocess
863 // the instruction I.
864 assert(RS->getCurrentPosition() == I &&
865 "The register scavenger has an unexpected position");