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 #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/CommandLine.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/ADT/IndexedMap.h"
37 #include "llvm/ADT/STLExtras.h"
44 static RegisterPass<PEI>
45 X("prologepilog", "Prologue/Epilogue Insertion");
47 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
48 /// prolog and epilog code, and eliminates abstract frame references.
50 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
52 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
53 /// frame indexes with appropriate references.
55 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
56 const Function* F = Fn.getFunction();
57 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
58 RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL;
59 FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
61 // Get MachineModuleInfo so that we can track the construction of the
63 if (MachineModuleInfo *MMI = getAnalysisIfAvailable<MachineModuleInfo>())
64 Fn.getFrameInfo()->setMachineModuleInfo(MMI);
66 // Calculate the MaxCallFrameSize and HasCalls variables for the function's
67 // frame information. Also eliminates call frame pseudo instructions.
68 calculateCallsInformation(Fn);
70 // Allow the target machine to make some adjustments to the function
71 // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
72 TRI->processFunctionBeforeCalleeSavedScan(Fn, RS);
74 // Scan the function for modified callee saved registers and insert spill code
75 // for any callee saved registers that are modified.
76 calculateCalleeSavedRegisters(Fn);
78 // Determine placement of CSR spill/restore code:
79 // - with shrink wrapping, place spills and restores to tightly
80 // enclose regions in the Machine CFG of the function where
81 // they are used. Without shrink wrapping
82 // - default (no shrink wrapping), place all spills in the
83 // entry block, all restores in return blocks.
84 placeCSRSpillsAndRestores(Fn);
86 // Add the code to save and restore the callee saved registers
87 if (!F->hasFnAttr(Attribute::Naked))
88 insertCSRSpillsAndRestores(Fn);
90 // Allow the target machine to make final modifications to the function
91 // before the frame layout is finalized.
92 TRI->processFunctionBeforeFrameFinalized(Fn);
94 // Calculate actual frame offsets for all abstract stack objects...
95 calculateFrameObjectOffsets(Fn);
97 // Add prolog and epilog code to the function. This function is required
98 // to align the stack frame as necessary for any stack variables or
99 // called functions. Because of this, calculateCalleeSavedRegisters
100 // must be called before this function in order to set the HasCalls
101 // and MaxCallFrameSize variables.
102 if (!F->hasFnAttr(Attribute::Naked))
103 insertPrologEpilogCode(Fn);
105 // Replace all MO_FrameIndex operands with physical register references
106 // and actual offsets.
108 replaceFrameIndices(Fn);
110 // If register scavenging is needed, as we've enabled doing it as a
111 // post-pass, scavenge the virtual registers that frame index elimiation
113 if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
114 scavengeFrameVirtualRegs(Fn);
122 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
123 AU.setPreservesCFG();
124 if (ShrinkWrapping || ShrinkWrapFunc != "") {
125 AU.addRequired<MachineLoopInfo>();
126 AU.addRequired<MachineDominatorTree>();
128 AU.addPreserved<MachineLoopInfo>();
129 AU.addPreserved<MachineDominatorTree>();
130 MachineFunctionPass::getAnalysisUsage(AU);
134 /// calculateCallsInformation - Calculate the MaxCallFrameSize and HasCalls
135 /// variables for the function's frame information and eliminate call frame
136 /// pseudo instructions.
137 void PEI::calculateCallsInformation(MachineFunction &Fn) {
138 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
140 unsigned MaxCallFrameSize = 0;
141 bool HasCalls = false;
143 // Get the function call frame set-up and tear-down instruction opcode
144 int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode();
145 int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
147 // Early exit for targets which have no call frame setup/destroy pseudo
149 if (FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
152 std::vector<MachineBasicBlock::iterator> FrameSDOps;
153 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
154 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
155 if (I->getOpcode() == FrameSetupOpcode ||
156 I->getOpcode() == FrameDestroyOpcode) {
157 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
158 " instructions should have a single immediate argument!");
159 unsigned Size = I->getOperand(0).getImm();
160 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
162 FrameSDOps.push_back(I);
163 } else if (I->getOpcode() == TargetInstrInfo::INLINEASM) {
164 // An InlineAsm might be a call; assume it is to get the stack frame
165 // aligned correctly for calls.
169 MachineFrameInfo *FFI = Fn.getFrameInfo();
170 FFI->setHasCalls(HasCalls);
171 FFI->setMaxCallFrameSize(MaxCallFrameSize);
173 for (std::vector<MachineBasicBlock::iterator>::iterator
174 i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
175 MachineBasicBlock::iterator I = *i;
177 // If call frames are not being included as part of the stack frame, and
178 // there is no dynamic allocation (therefore referencing frame slots off
179 // sp), leave the pseudo ops alone. We'll eliminate them later.
180 if (RegInfo->hasReservedCallFrame(Fn) || RegInfo->hasFP(Fn))
181 RegInfo->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
186 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
188 void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
189 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
190 const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
191 MachineFrameInfo *FFI = Fn.getFrameInfo();
193 // Get the callee saved register list...
194 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs(&Fn);
196 // These are used to keep track the callee-save area. Initialize them.
197 MinCSFrameIndex = INT_MAX;
200 // Early exit for targets which have no callee saved registers.
201 if (CSRegs == 0 || CSRegs[0] == 0)
204 // Figure out which *callee saved* registers are modified by the current
205 // function, thus needing to be saved and restored in the prolog/epilog.
206 const TargetRegisterClass * const *CSRegClasses =
207 RegInfo->getCalleeSavedRegClasses(&Fn);
209 std::vector<CalleeSavedInfo> CSI;
210 for (unsigned i = 0; CSRegs[i]; ++i) {
211 unsigned Reg = CSRegs[i];
212 if (Fn.getRegInfo().isPhysRegUsed(Reg)) {
213 // If the reg is modified, save it!
214 CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
216 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
217 *AliasSet; ++AliasSet) { // Check alias registers too.
218 if (Fn.getRegInfo().isPhysRegUsed(*AliasSet)) {
219 CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
227 return; // Early exit if no callee saved registers are modified!
229 unsigned NumFixedSpillSlots;
230 const TargetFrameInfo::SpillSlot *FixedSpillSlots =
231 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
233 // Now that we know which registers need to be saved and restored, allocate
234 // stack slots for them.
235 for (std::vector<CalleeSavedInfo>::iterator
236 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
237 unsigned Reg = I->getReg();
238 const TargetRegisterClass *RC = I->getRegClass();
241 if (RegInfo->hasReservedSpillSlot(Fn, Reg, FrameIdx)) {
242 I->setFrameIdx(FrameIdx);
246 // Check to see if this physreg must be spilled to a particular stack slot
248 const TargetFrameInfo::SpillSlot *FixedSlot = FixedSpillSlots;
249 while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
250 FixedSlot->Reg != Reg)
253 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
254 // Nope, just spill it anywhere convenient.
255 unsigned Align = RC->getAlignment();
256 unsigned StackAlign = TFI->getStackAlignment();
258 // We may not be able to satisfy the desired alignment specification of
259 // the TargetRegisterClass if the stack alignment is smaller. Use the
261 Align = std::min(Align, StackAlign);
262 FrameIdx = FFI->CreateStackObject(RC->getSize(), Align, true);
263 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
264 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
266 // Spill it to the stack where we must.
267 FrameIdx = FFI->CreateFixedObject(RC->getSize(), FixedSlot->Offset);
270 I->setFrameIdx(FrameIdx);
273 FFI->setCalleeSavedInfo(CSI);
276 /// insertCSRSpillsAndRestores - Insert spill and restore code for
277 /// callee saved registers used in the function, handling shrink wrapping.
279 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
280 // Get callee saved register information.
281 MachineFrameInfo *FFI = Fn.getFrameInfo();
282 const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
284 FFI->setCalleeSavedInfoValid(true);
286 // Early exit if no callee saved registers are modified!
290 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
291 MachineBasicBlock::iterator I;
293 if (! ShrinkWrapThisFunction) {
294 // Spill using target interface.
295 I = EntryBlock->begin();
296 if (!TII.spillCalleeSavedRegisters(*EntryBlock, I, CSI)) {
297 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
298 // Add the callee-saved register as live-in.
299 // It's killed at the spill.
300 EntryBlock->addLiveIn(CSI[i].getReg());
302 // Insert the spill to the stack frame.
303 TII.storeRegToStackSlot(*EntryBlock, I, CSI[i].getReg(), true,
304 CSI[i].getFrameIdx(), CSI[i].getRegClass());
308 // Restore using target interface.
309 for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) {
310 MachineBasicBlock* MBB = ReturnBlocks[ri];
313 // Skip over all terminator instructions, which are part of the return
315 MachineBasicBlock::iterator I2 = I;
316 while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
319 bool AtStart = I == MBB->begin();
320 MachineBasicBlock::iterator BeforeI = I;
324 // Restore all registers immediately before the return and any
325 // terminators that preceed it.
326 if (!TII.restoreCalleeSavedRegisters(*MBB, I, CSI)) {
327 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
328 TII.loadRegFromStackSlot(*MBB, I, CSI[i].getReg(),
329 CSI[i].getFrameIdx(),
330 CSI[i].getRegClass());
331 assert(I != MBB->begin() &&
332 "loadRegFromStackSlot didn't insert any code!");
333 // Insert in reverse order. loadRegFromStackSlot can insert
334 // multiple instructions.
348 std::vector<CalleeSavedInfo> blockCSI;
349 for (CSRegBlockMap::iterator BI = CSRSave.begin(),
350 BE = CSRSave.end(); BI != BE; ++BI) {
351 MachineBasicBlock* MBB = BI->first;
352 CSRegSet save = BI->second;
358 for (CSRegSet::iterator RI = save.begin(),
359 RE = save.end(); RI != RE; ++RI) {
360 blockCSI.push_back(CSI[*RI]);
362 assert(blockCSI.size() > 0 &&
363 "Could not collect callee saved register info");
367 // When shrink wrapping, use stack slot stores/loads.
368 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
369 // Add the callee-saved register as live-in.
370 // It's killed at the spill.
371 MBB->addLiveIn(blockCSI[i].getReg());
373 // Insert the spill to the stack frame.
374 TII.storeRegToStackSlot(*MBB, I, blockCSI[i].getReg(),
376 blockCSI[i].getFrameIdx(),
377 blockCSI[i].getRegClass());
381 for (CSRegBlockMap::iterator BI = CSRRestore.begin(),
382 BE = CSRRestore.end(); BI != BE; ++BI) {
383 MachineBasicBlock* MBB = BI->first;
384 CSRegSet restore = BI->second;
390 for (CSRegSet::iterator RI = restore.begin(),
391 RE = restore.end(); RI != RE; ++RI) {
392 blockCSI.push_back(CSI[*RI]);
394 assert(blockCSI.size() > 0 &&
395 "Could not find callee saved register info");
397 // If MBB is empty and needs restores, insert at the _beginning_.
404 // Skip over all terminator instructions, which are part of the
406 if (! I->getDesc().isTerminator()) {
409 MachineBasicBlock::iterator I2 = I;
410 while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
415 bool AtStart = I == MBB->begin();
416 MachineBasicBlock::iterator BeforeI = I;
420 // Restore all registers immediately before the return and any
421 // terminators that preceed it.
422 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
423 TII.loadRegFromStackSlot(*MBB, I, blockCSI[i].getReg(),
424 blockCSI[i].getFrameIdx(),
425 blockCSI[i].getRegClass());
426 assert(I != MBB->begin() &&
427 "loadRegFromStackSlot didn't insert any code!");
428 // Insert in reverse order. loadRegFromStackSlot can insert
429 // multiple instructions.
440 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
442 AdjustStackOffset(MachineFrameInfo *FFI, int FrameIdx,
443 bool StackGrowsDown, int64_t &Offset,
444 unsigned &MaxAlign) {
445 // If the stack grows down, add the object size to find the lowest address.
447 Offset += FFI->getObjectSize(FrameIdx);
449 unsigned Align = FFI->getObjectAlignment(FrameIdx);
451 // If the alignment of this object is greater than that of the stack, then
452 // increase the stack alignment to match.
453 MaxAlign = std::max(MaxAlign, Align);
455 // Adjust to alignment boundary.
456 Offset = (Offset + Align - 1) / Align * Align;
458 if (StackGrowsDown) {
459 FFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
461 FFI->setObjectOffset(FrameIdx, Offset);
462 Offset += FFI->getObjectSize(FrameIdx);
466 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
467 /// abstract stack objects.
469 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
470 const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
472 bool StackGrowsDown =
473 TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
475 // Loop over all of the stack objects, assigning sequential addresses...
476 MachineFrameInfo *FFI = Fn.getFrameInfo();
478 unsigned MaxAlign = 1;
480 // Start at the beginning of the local area.
481 // The Offset is the distance from the stack top in the direction
482 // of stack growth -- so it's always nonnegative.
483 int LocalAreaOffset = TFI.getOffsetOfLocalArea();
485 LocalAreaOffset = -LocalAreaOffset;
486 assert(LocalAreaOffset >= 0
487 && "Local area offset should be in direction of stack growth");
488 int64_t Offset = LocalAreaOffset;
490 // If there are fixed sized objects that are preallocated in the local area,
491 // non-fixed objects can't be allocated right at the start of local area.
492 // We currently don't support filling in holes in between fixed sized
493 // objects, so we adjust 'Offset' to point to the end of last fixed sized
494 // preallocated object.
495 for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
497 if (StackGrowsDown) {
498 // The maximum distance from the stack pointer is at lower address of
499 // the object -- which is given by offset. For down growing stack
500 // the offset is negative, so we negate the offset to get the distance.
501 FixedOff = -FFI->getObjectOffset(i);
503 // The maximum distance from the start pointer is at the upper
504 // address of the object.
505 FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i);
507 if (FixedOff > Offset) Offset = FixedOff;
510 // First assign frame offsets to stack objects that are used to spill
511 // callee saved registers.
512 if (StackGrowsDown) {
513 for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
514 // If stack grows down, we need to add size of find the lowest
515 // address of the object.
516 Offset += FFI->getObjectSize(i);
518 unsigned Align = FFI->getObjectAlignment(i);
519 // If the alignment of this object is greater than that of the stack,
520 // then increase the stack alignment to match.
521 MaxAlign = std::max(MaxAlign, Align);
522 // Adjust to alignment boundary
523 Offset = (Offset+Align-1)/Align*Align;
525 FFI->setObjectOffset(i, -Offset); // Set the computed offset
528 int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
529 for (int i = MaxCSFI; i >= MinCSFI ; --i) {
530 unsigned Align = FFI->getObjectAlignment(i);
531 // If the alignment of this object is greater than that of the stack,
532 // then increase the stack alignment to match.
533 MaxAlign = std::max(MaxAlign, Align);
534 // Adjust to alignment boundary
535 Offset = (Offset+Align-1)/Align*Align;
537 FFI->setObjectOffset(i, Offset);
538 Offset += FFI->getObjectSize(i);
542 // Make sure the special register scavenging spill slot is closest to the
543 // frame pointer if a frame pointer is required.
544 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
545 if (RS && RegInfo->hasFP(Fn)) {
546 int SFI = RS->getScavengingFrameIndex();
548 AdjustStackOffset(FFI, SFI, StackGrowsDown, Offset, MaxAlign);
551 // Make sure that the stack protector comes before the local variables on the
553 if (FFI->getStackProtectorIndex() >= 0)
554 AdjustStackOffset(FFI, FFI->getStackProtectorIndex(), StackGrowsDown,
557 // Then assign frame offsets to stack objects that are not used to spill
558 // callee saved registers.
559 for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
560 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
562 if (RS && (int)i == RS->getScavengingFrameIndex())
564 if (FFI->isDeadObjectIndex(i))
566 if (FFI->getStackProtectorIndex() == (int)i)
569 AdjustStackOffset(FFI, i, StackGrowsDown, Offset, MaxAlign);
572 // Make sure the special register scavenging spill slot is closest to the
574 if (RS && !RegInfo->hasFP(Fn)) {
575 int SFI = RS->getScavengingFrameIndex();
577 AdjustStackOffset(FFI, SFI, StackGrowsDown, Offset, MaxAlign);
580 if (!RegInfo->targetHandlesStackFrameRounding()) {
581 // If we have reserved argument space for call sites in the function
582 // immediately on entry to the current function, count it as part of the
583 // overall stack size.
584 if (FFI->hasCalls() && RegInfo->hasReservedCallFrame(Fn))
585 Offset += FFI->getMaxCallFrameSize();
587 // Round up the size to a multiple of the alignment. If the function has
588 // any calls or alloca's, align to the target's StackAlignment value to
589 // ensure that the callee's frame or the alloca data is suitably aligned;
590 // otherwise, for leaf functions, align to the TransientStackAlignment
593 if (FFI->hasCalls() || FFI->hasVarSizedObjects() ||
594 (RegInfo->needsStackRealignment(Fn) && FFI->getObjectIndexEnd() != 0))
595 StackAlign = TFI.getStackAlignment();
597 StackAlign = TFI.getTransientStackAlignment();
598 // If the frame pointer is eliminated, all frame offsets will be relative
599 // to SP not FP; align to MaxAlign so this works.
600 StackAlign = std::max(StackAlign, MaxAlign);
601 unsigned AlignMask = StackAlign - 1;
602 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
605 // Update frame info to pretend that this is part of the stack...
606 FFI->setStackSize(Offset - LocalAreaOffset);
608 // Remember the required stack alignment in case targets need it to perform
609 // dynamic stack alignment.
610 if (MaxAlign > FFI->getMaxAlignment())
611 FFI->setMaxAlignment(MaxAlign);
615 /// insertPrologEpilogCode - Scan the function for modified callee saved
616 /// registers, insert spill code for these callee saved registers, then add
617 /// prolog and epilog code to the function.
619 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
620 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
622 // Add prologue to the function...
623 TRI->emitPrologue(Fn);
625 // Add epilogue to restore the callee-save registers in each exiting block
626 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
627 // If last instruction is a return instruction, add an epilogue
628 if (!I->empty() && I->back().getDesc().isReturn())
629 TRI->emitEpilogue(Fn, *I);
634 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
635 /// register references and actual offsets.
637 void PEI::replaceFrameIndices(MachineFunction &Fn) {
638 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
640 const TargetMachine &TM = Fn.getTarget();
641 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
642 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
643 const TargetFrameInfo *TFI = TM.getFrameInfo();
644 bool StackGrowsDown =
645 TFI->getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
646 int FrameSetupOpcode = TRI.getCallFrameSetupOpcode();
647 int FrameDestroyOpcode = TRI.getCallFrameDestroyOpcode();
649 for (MachineFunction::iterator BB = Fn.begin(),
650 E = Fn.end(); BB != E; ++BB) {
651 int SPAdj = 0; // SP offset due to call frame setup / destroy.
652 if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
654 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
656 if (I->getOpcode() == FrameSetupOpcode ||
657 I->getOpcode() == FrameDestroyOpcode) {
658 // Remember how much SP has been adjusted to create the call
660 int Size = I->getOperand(0).getImm();
662 if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) ||
663 (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode))
668 MachineBasicBlock::iterator PrevI = BB->end();
669 if (I != BB->begin()) PrevI = prior(I);
670 TRI.eliminateCallFramePseudoInstr(Fn, *BB, I);
672 // Visit the instructions created by eliminateCallFramePseudoInstr().
673 if (PrevI == BB->end())
674 I = BB->begin(); // The replaced instr was the first in the block.
680 MachineInstr *MI = I;
682 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
683 if (MI->getOperand(i).isFI()) {
684 // Some instructions (e.g. inline asm instructions) can have
685 // multiple frame indices and/or cause eliminateFrameIndex
686 // to insert more than one instruction. We need the register
687 // scavenger to go through all of these instructions so that
688 // it can update its register information. We keep the
689 // iterator at the point before insertion so that we can
690 // revisit them in full.
691 bool AtBeginning = (I == BB->begin());
692 if (!AtBeginning) --I;
694 // If this instruction has a FrameIndex operand, we need to
695 // use that target machine register info object to eliminate
699 TRI.eliminateFrameIndex(MI, SPAdj, &Value,
700 FrameIndexVirtualScavenging ? NULL : RS);
702 assert (FrameIndexVirtualScavenging &&
703 "Not scavenging, but virtual returned from "
704 "eliminateFrameIndex()!");
705 FrameConstantRegMap[VReg] = FrameConstantEntry(Value, SPAdj);
708 // Reset the iterator if we were at the beginning of the BB.
718 if (DoIncr && I != BB->end()) ++I;
720 // Update register states.
721 if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
724 assert(SPAdj == 0 && "Unbalanced call frame setup / destroy pairs?");
728 /// findLastUseReg - find the killing use of the specified register within
729 /// the instruciton range. Return the operand number of the kill in Operand.
730 static MachineBasicBlock::iterator
731 findLastUseReg(MachineBasicBlock::iterator I, MachineBasicBlock::iterator ME,
732 unsigned Reg, unsigned *Operand) {
733 // Scan forward to find the last use of this virtual register
734 for (++I; I != ME; ++I) {
735 MachineInstr *MI = I;
736 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
737 if (MI->getOperand(i).isReg()) {
738 unsigned OpReg = MI->getOperand(i).getReg();
739 if (OpReg == 0 || !TargetRegisterInfo::isVirtualRegister(OpReg))
742 && "overlapping use of scavenged index register!");
743 // If this is the killing use, we're done
744 if (MI->getOperand(i).isKill()) {
751 // If we hit the end of the basic block, there was no kill of
752 // the virtual register, which is wrong.
753 assert (0 && "scavenged index register never killed!");
757 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
758 /// with physical registers. Use the register scavenger to find an
759 /// appropriate register to use.
760 void PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
761 // Run through the instructions and find any virtual registers.
762 for (MachineFunction::iterator BB = Fn.begin(),
763 E = Fn.end(); BB != E; ++BB) {
764 RS->enterBasicBlock(BB);
766 unsigned CurrentVirtReg = 0;
767 unsigned CurrentScratchReg = 0;
768 bool havePrevValue = false;
769 unsigned PrevScratchReg = 0;
771 MachineInstr *PrevLastUseMI = NULL;
772 unsigned PrevLastUseOp = 0;
773 bool trackingCurrentValue = false;
777 // The instruction stream may change in the loop, so check BB->end()
779 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
780 MachineInstr *MI = I;
781 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
782 if (MI->getOperand(i).isReg()) {
783 MachineOperand &MO = MI->getOperand(i);
784 unsigned Reg = MO.getReg();
787 if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
788 // If we have a previous scratch reg, check and see if anything
789 // here kills whatever value is in there.
790 if (Reg == PrevScratchReg) {
792 // Two-address operands implicitly kill
793 if (MO.isKill() || MI->isRegTiedToDefOperand(i)) {
794 havePrevValue = false;
799 havePrevValue = false;
806 // Have we already allocated a scratch register for this virtual?
807 if (Reg != CurrentVirtReg) {
808 // When we first encounter a new virtual register, it
809 // must be a definition.
810 assert(MI->getOperand(i).isDef() &&
811 "frame index virtual missing def!");
812 // We can't have nested virtual register live ranges because
813 // there's only a guarantee of one scavenged register at a time.
814 assert (CurrentVirtReg == 0 &&
815 "overlapping frame index virtual registers!");
817 // If the target gave us information about what's in the register,
818 // we can use that to re-use scratch regs.
819 DenseMap<unsigned, FrameConstantEntry>::iterator Entry =
820 FrameConstantRegMap.find(Reg);
821 trackingCurrentValue = Entry != FrameConstantRegMap.end();
822 if (trackingCurrentValue) {
823 SPAdj = (*Entry).second.second;
824 Value = (*Entry).second.first;
828 // If the scratch register from the last allocation is still
829 // available, see if the value matches. If it does, just re-use it.
830 if (trackingCurrentValue && havePrevValue && PrevValue == Value) {
831 // FIXME: This assumes that the instructions in the live range
832 // for the virtual register are exclusively for the purpose
833 // of populating the value in the register. That's reasonable
834 // for these frame index registers, but it's still a very, very
835 // strong assumption. Perhaps this implies that the frame index
836 // elimination should be before register allocation, with
837 // conservative heuristics since we'll know less then, and
838 // the reuse calculations done directly when doing the code-gen?
840 // Find the last use of the new virtual register. Remove all
841 // instruction between here and there, and update the current
842 // instruction to reference the last use insn instead.
843 MachineBasicBlock::iterator LastUseMI =
844 findLastUseReg(I, BB->end(), Reg, &i);
845 // Remove all instructions up 'til the last use, since they're
846 // just calculating the value we already have.
847 BB->erase(I, LastUseMI);
849 e = MI->getNumOperands();
851 CurrentScratchReg = PrevScratchReg;
852 // Extend the live range of the register
853 PrevLastUseMI->getOperand(PrevLastUseOp).setIsKill(false);
854 RS->setUsed(CurrentScratchReg);
856 CurrentVirtReg = Reg;
857 const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
858 CurrentScratchReg = RS->FindUnusedReg(RC);
859 if (CurrentScratchReg == 0)
860 // No register is "free". Scavenge a register.
861 CurrentScratchReg = RS->scavengeRegister(RC, I, SPAdj);
866 assert (CurrentScratchReg && "Missing scratch register!");
867 MI->getOperand(i).setReg(CurrentScratchReg);
869 // If this is the last use of the register, stop tracking it.
870 if (MI->getOperand(i).isKill()) {
871 PrevScratchReg = CurrentScratchReg;
874 CurrentScratchReg = CurrentVirtReg = 0;
875 havePrevValue = trackingCurrentValue;