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 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/MachineDominators.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/Passes.h"
30 #include "llvm/CodeGen/RegisterScavenging.h"
31 #include "llvm/CodeGen/StackProtector.h"
32 #include "llvm/CodeGen/WinEHFuncInfo.h"
33 #include "llvm/IR/DiagnosticInfo.h"
34 #include "llvm/IR/InlineAsm.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.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"
43 #include "llvm/Target/TargetSubtargetInfo.h"
48 #define DEBUG_TYPE "prologepilog"
50 typedef SmallVector<MachineBasicBlock *, 4> MBBVector;
51 static void doSpillCalleeSavedRegs(MachineFunction &MF, RegScavenger *RS,
52 unsigned &MinCSFrameIndex,
53 unsigned &MaxCXFrameIndex,
54 const MBBVector &SaveBlocks,
55 const MBBVector &RestoreBlocks);
57 static void doScavengeFrameVirtualRegs(MachineFunction &MF, RegScavenger *RS);
60 class PEI : public MachineFunctionPass {
63 PEI() : MachineFunctionPass(ID) {
64 initializePEIPass(*PassRegistry::getPassRegistry());
67 void getAnalysisUsage(AnalysisUsage &AU) const override;
69 MachineFunctionProperties getRequiredProperties() const override {
70 MachineFunctionProperties MFP;
72 MFP.set(MachineFunctionProperties::Property::NoVRegs);
76 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
77 /// frame indexes with appropriate references.
79 bool runOnMachineFunction(MachineFunction &Fn) override;
82 std::function<void(MachineFunction &MF, RegScavenger *RS,
83 unsigned &MinCSFrameIndex, unsigned &MaxCSFrameIndex,
84 const MBBVector &SaveBlocks,
85 const MBBVector &RestoreBlocks)>
86 SpillCalleeSavedRegisters;
87 std::function<void(MachineFunction &MF, RegScavenger *RS)>
88 ScavengeFrameVirtualRegs;
90 bool UsesCalleeSaves = false;
94 // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved
95 // stack frame indexes.
96 unsigned MinCSFrameIndex = std::numeric_limits<unsigned>::max();
97 unsigned MaxCSFrameIndex = 0;
99 // Save and Restore blocks of the current function. Typically there is a
100 // single save block, unless Windows EH funclets are involved.
101 MBBVector SaveBlocks;
102 MBBVector RestoreBlocks;
104 // Flag to control whether to use the register scavenger to resolve
105 // frame index materialization registers. Set according to
106 // TRI->requiresFrameIndexScavenging() for the current function.
107 bool FrameIndexVirtualScavenging;
109 // Flag to control whether the scavenger should be passed even though
110 // FrameIndexVirtualScavenging is used.
111 bool FrameIndexEliminationScavenging;
113 void calculateCallFrameInfo(MachineFunction &Fn);
114 void calculateSaveRestoreBlocks(MachineFunction &Fn);
116 void calculateFrameObjectOffsets(MachineFunction &Fn);
117 void replaceFrameIndices(MachineFunction &Fn);
118 void replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
120 void insertPrologEpilogCode(MachineFunction &Fn);
125 char &llvm::PrologEpilogCodeInserterID = PEI::ID;
127 static cl::opt<unsigned>
128 WarnStackSize("warn-stack-size", cl::Hidden, cl::init((unsigned)-1),
129 cl::desc("Warn for stack size bigger than the given"
132 INITIALIZE_PASS_BEGIN(PEI, DEBUG_TYPE, "Prologue/Epilogue Insertion", false,
134 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
135 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
136 INITIALIZE_PASS_DEPENDENCY(StackProtector)
137 INITIALIZE_PASS_END(PEI, DEBUG_TYPE,
138 "Prologue/Epilogue Insertion & Frame Finalization", false,
141 MachineFunctionPass *llvm::createPrologEpilogInserterPass() {
145 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
146 STATISTIC(NumBytesStackSpace,
147 "Number of bytes used for stack in all functions");
149 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
150 AU.setPreservesCFG();
151 AU.addPreserved<MachineLoopInfo>();
152 AU.addPreserved<MachineDominatorTree>();
153 AU.addRequired<StackProtector>();
154 MachineFunctionPass::getAnalysisUsage(AU);
158 /// StackObjSet - A set of stack object indexes
159 typedef SmallSetVector<int, 8> StackObjSet;
161 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
162 /// frame indexes with appropriate references.
164 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
165 if (!SpillCalleeSavedRegisters) {
166 const TargetMachine &TM = Fn.getTarget();
167 if (!TM.usesPhysRegsForPEI()) {
168 SpillCalleeSavedRegisters = [](MachineFunction &, RegScavenger *,
169 unsigned &, unsigned &, const MBBVector &,
170 const MBBVector &) {};
171 ScavengeFrameVirtualRegs = [](MachineFunction &, RegScavenger *) {};
173 SpillCalleeSavedRegisters = doSpillCalleeSavedRegs;
174 ScavengeFrameVirtualRegs = doScavengeFrameVirtualRegs;
175 UsesCalleeSaves = true;
179 const Function* F = Fn.getFunction();
180 const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
181 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
183 RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : nullptr;
184 FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
185 FrameIndexEliminationScavenging = (RS && !FrameIndexVirtualScavenging) ||
186 TRI->requiresFrameIndexReplacementScavenging(Fn);
188 // Calculate the MaxCallFrameSize and AdjustsStack variables for the
189 // function's frame information. Also eliminates call frame pseudo
191 calculateCallFrameInfo(Fn);
193 // Determine placement of CSR spill/restore code and prolog/epilog code:
194 // place all spills in the entry block, all restores in return blocks.
195 calculateSaveRestoreBlocks(Fn);
197 // Handle CSR spilling and restoring, for targets that need it.
198 SpillCalleeSavedRegisters(Fn, RS, MinCSFrameIndex, MaxCSFrameIndex,
199 SaveBlocks, RestoreBlocks);
201 // Allow the target machine to make final modifications to the function
202 // before the frame layout is finalized.
203 TFI->processFunctionBeforeFrameFinalized(Fn, RS);
205 // Calculate actual frame offsets for all abstract stack objects...
206 calculateFrameObjectOffsets(Fn);
208 // Add prolog and epilog code to the function. This function is required
209 // to align the stack frame as necessary for any stack variables or
210 // called functions. Because of this, calculateCalleeSavedRegisters()
211 // must be called before this function in order to set the AdjustsStack
212 // and MaxCallFrameSize variables.
213 if (!F->hasFnAttribute(Attribute::Naked))
214 insertPrologEpilogCode(Fn);
216 // Replace all MO_FrameIndex operands with physical register references
217 // and actual offsets.
219 replaceFrameIndices(Fn);
221 // If register scavenging is needed, as we've enabled doing it as a
222 // post-pass, scavenge the virtual registers that frame index elimination
224 if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging) {
225 ScavengeFrameVirtualRegs(Fn, RS);
227 // Clear any vregs created by virtual scavenging.
228 Fn.getRegInfo().clearVirtRegs();
231 // Warn on stack size when we exceeds the given limit.
232 MachineFrameInfo &MFI = Fn.getFrameInfo();
233 uint64_t StackSize = MFI.getStackSize();
234 if (WarnStackSize.getNumOccurrences() > 0 && WarnStackSize < StackSize) {
235 DiagnosticInfoStackSize DiagStackSize(*F, StackSize);
236 F->getContext().diagnose(DiagStackSize);
241 RestoreBlocks.clear();
242 MFI.setSavePoint(nullptr);
243 MFI.setRestorePoint(nullptr);
247 /// Calculate the MaxCallFrameSize and AdjustsStack
248 /// variables for the function's frame information and eliminate call frame
249 /// pseudo instructions.
250 void PEI::calculateCallFrameInfo(MachineFunction &Fn) {
251 const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
252 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
253 MachineFrameInfo &MFI = Fn.getFrameInfo();
255 unsigned MaxCallFrameSize = 0;
256 bool AdjustsStack = MFI.adjustsStack();
258 // Get the function call frame set-up and tear-down instruction opcode
259 unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
260 unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
262 // Early exit for targets which have no call frame setup/destroy pseudo
264 if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
267 std::vector<MachineBasicBlock::iterator> FrameSDOps;
268 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
269 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
270 if (TII.isFrameInstr(*I)) {
271 unsigned Size = TII.getFrameSize(*I);
272 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
274 FrameSDOps.push_back(I);
275 } else if (I->isInlineAsm()) {
276 // Some inline asm's need a stack frame, as indicated by operand 1.
277 unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
278 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
282 assert(!MFI.isMaxCallFrameSizeComputed() ||
283 (MFI.getMaxCallFrameSize() == MaxCallFrameSize &&
284 MFI.adjustsStack() == AdjustsStack));
285 MFI.setAdjustsStack(AdjustsStack);
286 MFI.setMaxCallFrameSize(MaxCallFrameSize);
288 for (std::vector<MachineBasicBlock::iterator>::iterator
289 i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
290 MachineBasicBlock::iterator I = *i;
292 // If call frames are not being included as part of the stack frame, and
293 // the target doesn't indicate otherwise, remove the call frame pseudos
294 // here. The sub/add sp instruction pairs are still inserted, but we don't
295 // need to track the SP adjustment for frame index elimination.
296 if (TFI->canSimplifyCallFramePseudos(Fn))
297 TFI->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
301 /// Compute the sets of entry and return blocks for saving and restoring
302 /// callee-saved registers, and placing prolog and epilog code.
303 void PEI::calculateSaveRestoreBlocks(MachineFunction &Fn) {
304 const MachineFrameInfo &MFI = Fn.getFrameInfo();
306 // Even when we do not change any CSR, we still want to insert the
307 // prologue and epilogue of the function.
308 // So set the save points for those.
310 // Use the points found by shrink-wrapping, if any.
311 if (MFI.getSavePoint()) {
312 SaveBlocks.push_back(MFI.getSavePoint());
313 assert(MFI.getRestorePoint() && "Both restore and save must be set");
314 MachineBasicBlock *RestoreBlock = MFI.getRestorePoint();
315 // If RestoreBlock does not have any successor and is not a return block
316 // then the end point is unreachable and we do not need to insert any
318 if (!RestoreBlock->succ_empty() || RestoreBlock->isReturnBlock())
319 RestoreBlocks.push_back(RestoreBlock);
323 // Save refs to entry and return blocks.
324 SaveBlocks.push_back(&Fn.front());
325 for (MachineBasicBlock &MBB : Fn) {
326 if (MBB.isEHFuncletEntry())
327 SaveBlocks.push_back(&MBB);
328 if (MBB.isReturnBlock())
329 RestoreBlocks.push_back(&MBB);
333 static void assignCalleeSavedSpillSlots(MachineFunction &F,
334 const BitVector &SavedRegs,
335 unsigned &MinCSFrameIndex,
336 unsigned &MaxCSFrameIndex) {
337 if (SavedRegs.empty())
340 const TargetRegisterInfo *RegInfo = F.getSubtarget().getRegisterInfo();
341 const MCPhysReg *CSRegs = F.getRegInfo().getCalleeSavedRegs();
343 std::vector<CalleeSavedInfo> CSI;
344 for (unsigned i = 0; CSRegs[i]; ++i) {
345 unsigned Reg = CSRegs[i];
346 if (SavedRegs.test(Reg))
347 CSI.push_back(CalleeSavedInfo(Reg));
350 const TargetFrameLowering *TFI = F.getSubtarget().getFrameLowering();
351 MachineFrameInfo &MFI = F.getFrameInfo();
352 if (!TFI->assignCalleeSavedSpillSlots(F, RegInfo, CSI)) {
353 // If target doesn't implement this, use generic code.
356 return; // Early exit if no callee saved registers are modified!
358 unsigned NumFixedSpillSlots;
359 const TargetFrameLowering::SpillSlot *FixedSpillSlots =
360 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
362 // Now that we know which registers need to be saved and restored, allocate
363 // stack slots for them.
364 for (auto &CS : CSI) {
365 unsigned Reg = CS.getReg();
366 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
369 if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) {
370 CS.setFrameIdx(FrameIdx);
374 // Check to see if this physreg must be spilled to a particular stack slot
376 const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
377 while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots &&
378 FixedSlot->Reg != Reg)
381 unsigned Size = RegInfo->getSpillSize(*RC);
382 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
383 // Nope, just spill it anywhere convenient.
384 unsigned Align = RegInfo->getSpillAlignment(*RC);
385 unsigned StackAlign = TFI->getStackAlignment();
387 // We may not be able to satisfy the desired alignment specification of
388 // the TargetRegisterClass if the stack alignment is smaller. Use the
390 Align = std::min(Align, StackAlign);
391 FrameIdx = MFI.CreateStackObject(Size, Align, true);
392 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
393 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
395 // Spill it to the stack where we must.
396 FrameIdx = MFI.CreateFixedSpillStackObject(Size, FixedSlot->Offset);
399 CS.setFrameIdx(FrameIdx);
403 MFI.setCalleeSavedInfo(CSI);
406 /// Helper function to update the liveness information for the callee-saved
408 static void updateLiveness(MachineFunction &MF) {
409 MachineFrameInfo &MFI = MF.getFrameInfo();
410 // Visited will contain all the basic blocks that are in the region
411 // where the callee saved registers are alive:
412 // - Anything that is not Save or Restore -> LiveThrough.
414 // - Restore -> LiveOut.
415 // The live-out is not attached to the block, so no need to keep
416 // Restore in this set.
417 SmallPtrSet<MachineBasicBlock *, 8> Visited;
418 SmallVector<MachineBasicBlock *, 8> WorkList;
419 MachineBasicBlock *Entry = &MF.front();
420 MachineBasicBlock *Save = MFI.getSavePoint();
426 WorkList.push_back(Entry);
427 Visited.insert(Entry);
429 Visited.insert(Save);
431 MachineBasicBlock *Restore = MFI.getRestorePoint();
433 // By construction Restore cannot be visited, otherwise it
434 // means there exists a path to Restore that does not go
436 WorkList.push_back(Restore);
438 while (!WorkList.empty()) {
439 const MachineBasicBlock *CurBB = WorkList.pop_back_val();
440 // By construction, the region that is after the save point is
441 // dominated by the Save and post-dominated by the Restore.
442 if (CurBB == Save && Save != Restore)
444 // Enqueue all the successors not already visited.
445 // Those are by construction either before Save or after Restore.
446 for (MachineBasicBlock *SuccBB : CurBB->successors())
447 if (Visited.insert(SuccBB).second)
448 WorkList.push_back(SuccBB);
451 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
453 MachineRegisterInfo &MRI = MF.getRegInfo();
454 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
455 for (MachineBasicBlock *MBB : Visited) {
456 MCPhysReg Reg = CSI[i].getReg();
457 // Add the callee-saved register as live-in.
458 // It's killed at the spill.
459 if (!MRI.isReserved(Reg) && !MBB->isLiveIn(Reg))
465 /// insertCSRSpillsAndRestores - Insert spill and restore code for
466 /// callee saved registers used in the function.
468 static void insertCSRSpillsAndRestores(MachineFunction &Fn,
469 const MBBVector &SaveBlocks,
470 const MBBVector &RestoreBlocks) {
471 // Get callee saved register information.
472 MachineFrameInfo &MFI = Fn.getFrameInfo();
473 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
475 MFI.setCalleeSavedInfoValid(true);
477 // Early exit if no callee saved registers are modified!
481 const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
482 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
483 const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
484 MachineBasicBlock::iterator I;
486 // Spill using target interface.
487 for (MachineBasicBlock *SaveBlock : SaveBlocks) {
488 I = SaveBlock->begin();
489 if (!TFI->spillCalleeSavedRegisters(*SaveBlock, I, CSI, TRI)) {
490 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
491 // Insert the spill to the stack frame.
492 unsigned Reg = CSI[i].getReg();
493 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
494 TII.storeRegToStackSlot(*SaveBlock, I, Reg, true, CSI[i].getFrameIdx(),
498 // Update the live-in information of all the blocks up to the save point.
502 // Restore using target interface.
503 for (MachineBasicBlock *MBB : RestoreBlocks) {
506 // Skip over all terminator instructions, which are part of the return
508 MachineBasicBlock::iterator I2 = I;
509 while (I2 != MBB->begin() && (--I2)->isTerminator())
512 bool AtStart = I == MBB->begin();
513 MachineBasicBlock::iterator BeforeI = I;
517 // Restore all registers immediately before the return and any
518 // terminators that precede it.
519 if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
520 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
521 unsigned Reg = CSI[i].getReg();
522 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
523 TII.loadRegFromStackSlot(*MBB, I, Reg, CSI[i].getFrameIdx(), RC, TRI);
524 assert(I != MBB->begin() &&
525 "loadRegFromStackSlot didn't insert any code!");
526 // Insert in reverse order. loadRegFromStackSlot can insert
527 // multiple instructions.
539 static void doSpillCalleeSavedRegs(MachineFunction &Fn, RegScavenger *RS,
540 unsigned &MinCSFrameIndex,
541 unsigned &MaxCSFrameIndex,
542 const MBBVector &SaveBlocks,
543 const MBBVector &RestoreBlocks) {
544 const Function *F = Fn.getFunction();
545 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
546 MinCSFrameIndex = std::numeric_limits<unsigned>::max();
549 // Determine which of the registers in the callee save list should be saved.
551 TFI->determineCalleeSaves(Fn, SavedRegs, RS);
553 // Assign stack slots for any callee-saved registers that must be spilled.
554 assignCalleeSavedSpillSlots(Fn, SavedRegs, MinCSFrameIndex, MaxCSFrameIndex);
556 // Add the code to save and restore the callee saved registers.
557 if (!F->hasFnAttribute(Attribute::Naked))
558 insertCSRSpillsAndRestores(Fn, SaveBlocks, RestoreBlocks);
561 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
563 AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx,
564 bool StackGrowsDown, int64_t &Offset,
565 unsigned &MaxAlign, unsigned Skew) {
566 // If the stack grows down, add the object size to find the lowest address.
568 Offset += MFI.getObjectSize(FrameIdx);
570 unsigned Align = MFI.getObjectAlignment(FrameIdx);
572 // If the alignment of this object is greater than that of the stack, then
573 // increase the stack alignment to match.
574 MaxAlign = std::max(MaxAlign, Align);
576 // Adjust to alignment boundary.
577 Offset = alignTo(Offset, Align, Skew);
579 if (StackGrowsDown) {
580 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
581 MFI.setObjectOffset(FrameIdx, -Offset); // Set the computed offset
583 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
584 MFI.setObjectOffset(FrameIdx, Offset);
585 Offset += MFI.getObjectSize(FrameIdx);
589 /// Compute which bytes of fixed and callee-save stack area are unused and keep
590 /// track of them in StackBytesFree.
593 computeFreeStackSlots(MachineFrameInfo &MFI, bool StackGrowsDown,
594 unsigned MinCSFrameIndex, unsigned MaxCSFrameIndex,
595 int64_t FixedCSEnd, BitVector &StackBytesFree) {
596 // Avoid undefined int64_t -> int conversion below in extreme case.
597 if (FixedCSEnd > std::numeric_limits<int>::max())
600 StackBytesFree.resize(FixedCSEnd, true);
602 SmallVector<int, 16> AllocatedFrameSlots;
603 // Add fixed objects.
604 for (int i = MFI.getObjectIndexBegin(); i != 0; ++i)
605 AllocatedFrameSlots.push_back(i);
606 // Add callee-save objects.
607 for (int i = MinCSFrameIndex; i <= (int)MaxCSFrameIndex; ++i)
608 AllocatedFrameSlots.push_back(i);
610 for (int i : AllocatedFrameSlots) {
611 // These are converted from int64_t, but they should always fit in int
612 // because of the FixedCSEnd check above.
613 int ObjOffset = MFI.getObjectOffset(i);
614 int ObjSize = MFI.getObjectSize(i);
615 int ObjStart, ObjEnd;
616 if (StackGrowsDown) {
617 // ObjOffset is negative when StackGrowsDown is true.
618 ObjStart = -ObjOffset - ObjSize;
621 ObjStart = ObjOffset;
622 ObjEnd = ObjOffset + ObjSize;
624 // Ignore fixed holes that are in the previous stack frame.
626 StackBytesFree.reset(ObjStart, ObjEnd);
630 /// Assign frame object to an unused portion of the stack in the fixed stack
631 /// object range. Return true if the allocation was successful.
633 static inline bool scavengeStackSlot(MachineFrameInfo &MFI, int FrameIdx,
634 bool StackGrowsDown, unsigned MaxAlign,
635 BitVector &StackBytesFree) {
636 if (MFI.isVariableSizedObjectIndex(FrameIdx))
639 if (StackBytesFree.none()) {
640 // clear it to speed up later scavengeStackSlot calls to
641 // StackBytesFree.none()
642 StackBytesFree.clear();
646 unsigned ObjAlign = MFI.getObjectAlignment(FrameIdx);
647 if (ObjAlign > MaxAlign)
650 int64_t ObjSize = MFI.getObjectSize(FrameIdx);
652 for (FreeStart = StackBytesFree.find_first(); FreeStart != -1;
653 FreeStart = StackBytesFree.find_next(FreeStart)) {
655 // Check that free space has suitable alignment.
656 unsigned ObjStart = StackGrowsDown ? FreeStart + ObjSize : FreeStart;
657 if (alignTo(ObjStart, ObjAlign) != ObjStart)
660 if (FreeStart + ObjSize > StackBytesFree.size())
663 bool AllBytesFree = true;
664 for (unsigned Byte = 0; Byte < ObjSize; ++Byte)
665 if (!StackBytesFree.test(FreeStart + Byte)) {
666 AllBytesFree = false;
676 if (StackGrowsDown) {
677 int ObjStart = -(FreeStart + ObjSize);
678 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP[" << ObjStart
680 MFI.setObjectOffset(FrameIdx, ObjStart);
682 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP[" << FreeStart
684 MFI.setObjectOffset(FrameIdx, FreeStart);
687 StackBytesFree.reset(FreeStart, FreeStart + ObjSize);
691 /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
692 /// those required to be close to the Stack Protector) to stack offsets.
694 AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
695 SmallSet<int, 16> &ProtectedObjs,
696 MachineFrameInfo &MFI, bool StackGrowsDown,
697 int64_t &Offset, unsigned &MaxAlign, unsigned Skew) {
699 for (StackObjSet::const_iterator I = UnassignedObjs.begin(),
700 E = UnassignedObjs.end(); I != E; ++I) {
702 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign, Skew);
703 ProtectedObjs.insert(i);
707 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
708 /// abstract stack objects.
710 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
711 const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
712 StackProtector *SP = &getAnalysis<StackProtector>();
714 bool StackGrowsDown =
715 TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
717 // Loop over all of the stack objects, assigning sequential addresses...
718 MachineFrameInfo &MFI = Fn.getFrameInfo();
720 // Start at the beginning of the local area.
721 // The Offset is the distance from the stack top in the direction
722 // of stack growth -- so it's always nonnegative.
723 int LocalAreaOffset = TFI.getOffsetOfLocalArea();
725 LocalAreaOffset = -LocalAreaOffset;
726 assert(LocalAreaOffset >= 0
727 && "Local area offset should be in direction of stack growth");
728 int64_t Offset = LocalAreaOffset;
730 // Skew to be applied to alignment.
731 unsigned Skew = TFI.getStackAlignmentSkew(Fn);
733 // If there are fixed sized objects that are preallocated in the local area,
734 // non-fixed objects can't be allocated right at the start of local area.
735 // Adjust 'Offset' to point to the end of last fixed sized preallocated
737 for (int i = MFI.getObjectIndexBegin(); i != 0; ++i) {
739 if (StackGrowsDown) {
740 // The maximum distance from the stack pointer is at lower address of
741 // the object -- which is given by offset. For down growing stack
742 // the offset is negative, so we negate the offset to get the distance.
743 FixedOff = -MFI.getObjectOffset(i);
745 // The maximum distance from the start pointer is at the upper
746 // address of the object.
747 FixedOff = MFI.getObjectOffset(i) + MFI.getObjectSize(i);
749 if (FixedOff > Offset) Offset = FixedOff;
752 // First assign frame offsets to stack objects that are used to spill
753 // callee saved registers.
754 if (StackGrowsDown) {
755 for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
756 // If the stack grows down, we need to add the size to find the lowest
757 // address of the object.
758 Offset += MFI.getObjectSize(i);
760 unsigned Align = MFI.getObjectAlignment(i);
761 // Adjust to alignment boundary
762 Offset = alignTo(Offset, Align, Skew);
764 DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << -Offset << "]\n");
765 MFI.setObjectOffset(i, -Offset); // Set the computed offset
767 } else if (MaxCSFrameIndex >= MinCSFrameIndex) {
768 // Be careful about underflow in comparisons agains MinCSFrameIndex.
769 for (unsigned i = MaxCSFrameIndex; i != MinCSFrameIndex - 1; --i) {
770 if (MFI.isDeadObjectIndex(i))
773 unsigned Align = MFI.getObjectAlignment(i);
774 // Adjust to alignment boundary
775 Offset = alignTo(Offset, Align, Skew);
777 DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << Offset << "]\n");
778 MFI.setObjectOffset(i, Offset);
779 Offset += MFI.getObjectSize(i);
783 // FixedCSEnd is the stack offset to the end of the fixed and callee-save
785 int64_t FixedCSEnd = Offset;
786 unsigned MaxAlign = MFI.getMaxAlignment();
788 // Make sure the special register scavenging spill slot is closest to the
789 // incoming stack pointer if a frame pointer is required and is closer
790 // to the incoming rather than the final stack pointer.
791 const TargetRegisterInfo *RegInfo = Fn.getSubtarget().getRegisterInfo();
792 bool EarlyScavengingSlots = (TFI.hasFP(Fn) &&
793 TFI.isFPCloseToIncomingSP() &&
794 RegInfo->useFPForScavengingIndex(Fn) &&
795 !RegInfo->needsStackRealignment(Fn));
796 if (RS && EarlyScavengingSlots) {
797 SmallVector<int, 2> SFIs;
798 RS->getScavengingFrameIndices(SFIs);
799 for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
800 IE = SFIs.end(); I != IE; ++I)
801 AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign, Skew);
804 // FIXME: Once this is working, then enable flag will change to a target
805 // check for whether the frame is large enough to want to use virtual
806 // frame index registers. Functions which don't want/need this optimization
807 // will continue to use the existing code path.
808 if (MFI.getUseLocalStackAllocationBlock()) {
809 unsigned Align = MFI.getLocalFrameMaxAlign();
811 // Adjust to alignment boundary.
812 Offset = alignTo(Offset, Align, Skew);
814 DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
816 // Resolve offsets for objects in the local block.
817 for (unsigned i = 0, e = MFI.getLocalFrameObjectCount(); i != e; ++i) {
818 std::pair<int, int64_t> Entry = MFI.getLocalFrameObjectMap(i);
819 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
820 DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
822 MFI.setObjectOffset(Entry.first, FIOffset);
824 // Allocate the local block
825 Offset += MFI.getLocalFrameSize();
827 MaxAlign = std::max(Align, MaxAlign);
830 // Retrieve the Exception Handler registration node.
831 int EHRegNodeFrameIndex = INT_MAX;
832 if (const WinEHFuncInfo *FuncInfo = Fn.getWinEHFuncInfo())
833 EHRegNodeFrameIndex = FuncInfo->EHRegNodeFrameIndex;
835 // Make sure that the stack protector comes before the local variables on the
837 SmallSet<int, 16> ProtectedObjs;
838 if (MFI.getStackProtectorIndex() >= 0) {
839 StackObjSet LargeArrayObjs;
840 StackObjSet SmallArrayObjs;
841 StackObjSet AddrOfObjs;
843 AdjustStackOffset(MFI, MFI.getStackProtectorIndex(), StackGrowsDown,
844 Offset, MaxAlign, Skew);
846 // Assign large stack objects first.
847 for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
848 if (MFI.isObjectPreAllocated(i) &&
849 MFI.getUseLocalStackAllocationBlock())
851 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
853 if (RS && RS->isScavengingFrameIndex((int)i))
855 if (MFI.isDeadObjectIndex(i))
857 if (MFI.getStackProtectorIndex() == (int)i ||
858 EHRegNodeFrameIndex == (int)i)
861 switch (SP->getSSPLayout(MFI.getObjectAllocation(i))) {
862 case StackProtector::SSPLK_None:
864 case StackProtector::SSPLK_SmallArray:
865 SmallArrayObjs.insert(i);
867 case StackProtector::SSPLK_AddrOf:
868 AddrOfObjs.insert(i);
870 case StackProtector::SSPLK_LargeArray:
871 LargeArrayObjs.insert(i);
874 llvm_unreachable("Unexpected SSPLayoutKind.");
877 AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
878 Offset, MaxAlign, Skew);
879 AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
880 Offset, MaxAlign, Skew);
881 AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
882 Offset, MaxAlign, Skew);
885 SmallVector<int, 8> ObjectsToAllocate;
887 // Then prepare to assign frame offsets to stack objects that are not used to
888 // spill callee saved registers.
889 for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
890 if (MFI.isObjectPreAllocated(i) && MFI.getUseLocalStackAllocationBlock())
892 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
894 if (RS && RS->isScavengingFrameIndex((int)i))
896 if (MFI.isDeadObjectIndex(i))
898 if (MFI.getStackProtectorIndex() == (int)i ||
899 EHRegNodeFrameIndex == (int)i)
901 if (ProtectedObjs.count(i))
904 // Add the objects that we need to allocate to our working set.
905 ObjectsToAllocate.push_back(i);
908 // Allocate the EH registration node first if one is present.
909 if (EHRegNodeFrameIndex != INT_MAX)
910 AdjustStackOffset(MFI, EHRegNodeFrameIndex, StackGrowsDown, Offset,
913 // Give the targets a chance to order the objects the way they like it.
914 if (Fn.getTarget().getOptLevel() != CodeGenOpt::None &&
915 Fn.getTarget().Options.StackSymbolOrdering)
916 TFI.orderFrameObjects(Fn, ObjectsToAllocate);
918 // Keep track of which bytes in the fixed and callee-save range are used so we
919 // can use the holes when allocating later stack objects. Only do this if
920 // stack protector isn't being used and the target requests it and we're
922 BitVector StackBytesFree;
923 if (!ObjectsToAllocate.empty() &&
924 Fn.getTarget().getOptLevel() != CodeGenOpt::None &&
925 MFI.getStackProtectorIndex() < 0 && TFI.enableStackSlotScavenging(Fn))
926 computeFreeStackSlots(MFI, StackGrowsDown, MinCSFrameIndex, MaxCSFrameIndex,
927 FixedCSEnd, StackBytesFree);
929 // Now walk the objects and actually assign base offsets to them.
930 for (auto &Object : ObjectsToAllocate)
931 if (!scavengeStackSlot(MFI, Object, StackGrowsDown, MaxAlign,
933 AdjustStackOffset(MFI, Object, StackGrowsDown, Offset, MaxAlign, Skew);
935 // Make sure the special register scavenging spill slot is closest to the
937 if (RS && !EarlyScavengingSlots) {
938 SmallVector<int, 2> SFIs;
939 RS->getScavengingFrameIndices(SFIs);
940 for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
941 IE = SFIs.end(); I != IE; ++I)
942 AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign, Skew);
945 if (!TFI.targetHandlesStackFrameRounding()) {
946 // If we have reserved argument space for call sites in the function
947 // immediately on entry to the current function, count it as part of the
948 // overall stack size.
949 if (MFI.adjustsStack() && TFI.hasReservedCallFrame(Fn))
950 Offset += MFI.getMaxCallFrameSize();
952 // Round up the size to a multiple of the alignment. If the function has
953 // any calls or alloca's, align to the target's StackAlignment value to
954 // ensure that the callee's frame or the alloca data is suitably aligned;
955 // otherwise, for leaf functions, align to the TransientStackAlignment
958 if (MFI.adjustsStack() || MFI.hasVarSizedObjects() ||
959 (RegInfo->needsStackRealignment(Fn) && MFI.getObjectIndexEnd() != 0))
960 StackAlign = TFI.getStackAlignment();
962 StackAlign = TFI.getTransientStackAlignment();
964 // If the frame pointer is eliminated, all frame offsets will be relative to
965 // SP not FP. Align to MaxAlign so this works.
966 StackAlign = std::max(StackAlign, MaxAlign);
967 Offset = alignTo(Offset, StackAlign, Skew);
970 // Update frame info to pretend that this is part of the stack...
971 int64_t StackSize = Offset - LocalAreaOffset;
972 MFI.setStackSize(StackSize);
973 NumBytesStackSpace += StackSize;
976 /// insertPrologEpilogCode - Scan the function for modified callee saved
977 /// registers, insert spill code for these callee saved registers, then add
978 /// prolog and epilog code to the function.
980 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
981 const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
983 // Add prologue to the function...
984 for (MachineBasicBlock *SaveBlock : SaveBlocks)
985 TFI.emitPrologue(Fn, *SaveBlock);
987 // Add epilogue to restore the callee-save registers in each exiting block.
988 for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
989 TFI.emitEpilogue(Fn, *RestoreBlock);
991 for (MachineBasicBlock *SaveBlock : SaveBlocks)
992 TFI.inlineStackProbe(Fn, *SaveBlock);
994 // Emit additional code that is required to support segmented stacks, if
995 // we've been asked for it. This, when linked with a runtime with support
996 // for segmented stacks (libgcc is one), will result in allocating stack
997 // space in small chunks instead of one large contiguous block.
998 if (Fn.shouldSplitStack()) {
999 for (MachineBasicBlock *SaveBlock : SaveBlocks)
1000 TFI.adjustForSegmentedStacks(Fn, *SaveBlock);
1003 // Emit additional code that is required to explicitly handle the stack in
1004 // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
1005 // approach is rather similar to that of Segmented Stacks, but it uses a
1006 // different conditional check and another BIF for allocating more stack
1008 if (Fn.getFunction()->getCallingConv() == CallingConv::HiPE)
1009 for (MachineBasicBlock *SaveBlock : SaveBlocks)
1010 TFI.adjustForHiPEPrologue(Fn, *SaveBlock);
1013 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
1014 /// register references and actual offsets.
1016 void PEI::replaceFrameIndices(MachineFunction &Fn) {
1017 const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
1018 if (!TFI.needsFrameIndexResolution(Fn)) return;
1020 // Store SPAdj at exit of a basic block.
1021 SmallVector<int, 8> SPState;
1022 SPState.resize(Fn.getNumBlockIDs());
1023 df_iterator_default_set<MachineBasicBlock*> Reachable;
1025 // Iterate over the reachable blocks in DFS order.
1026 for (auto DFI = df_ext_begin(&Fn, Reachable), DFE = df_ext_end(&Fn, Reachable);
1027 DFI != DFE; ++DFI) {
1029 // Check the exit state of the DFS stack predecessor.
1030 if (DFI.getPathLength() >= 2) {
1031 MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
1032 assert(Reachable.count(StackPred) &&
1033 "DFS stack predecessor is already visited.\n");
1034 SPAdj = SPState[StackPred->getNumber()];
1036 MachineBasicBlock *BB = *DFI;
1037 replaceFrameIndices(BB, Fn, SPAdj);
1038 SPState[BB->getNumber()] = SPAdj;
1041 // Handle the unreachable blocks.
1042 for (auto &BB : Fn) {
1043 if (Reachable.count(&BB))
1044 // Already handled in DFS traversal.
1047 replaceFrameIndices(&BB, Fn, SPAdj);
1051 void PEI::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
1053 assert(Fn.getSubtarget().getRegisterInfo() &&
1054 "getRegisterInfo() must be implemented!");
1055 const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
1056 const TargetRegisterInfo &TRI = *Fn.getSubtarget().getRegisterInfo();
1057 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
1059 if (RS && FrameIndexEliminationScavenging)
1060 RS->enterBasicBlock(*BB);
1062 bool InsideCallSequence = false;
1064 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
1066 if (TII.isFrameInstr(*I)) {
1067 InsideCallSequence = TII.isFrameSetup(*I);
1068 SPAdj += TII.getSPAdjust(*I);
1069 I = TFI->eliminateCallFramePseudoInstr(Fn, *BB, I);
1073 MachineInstr &MI = *I;
1075 bool DidFinishLoop = true;
1076 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1077 if (!MI.getOperand(i).isFI())
1080 // Frame indices in debug values are encoded in a target independent
1081 // way with simply the frame index and offset rather than any
1082 // target-specific addressing mode.
1083 if (MI.isDebugValue()) {
1084 assert(i == 0 && "Frame indices can only appear as the first "
1085 "operand of a DBG_VALUE machine instruction");
1087 MachineOperand &Offset = MI.getOperand(1);
1090 TFI->getFrameIndexReference(Fn, MI.getOperand(0).getIndex(), Reg));
1091 MI.getOperand(0).ChangeToRegister(Reg, false /*isDef*/);
1095 // TODO: This code should be commoned with the code for
1096 // PATCHPOINT. There's no good reason for the difference in
1097 // implementation other than historical accident. The only
1098 // remaining difference is the unconditional use of the stack
1099 // pointer as the base register.
1100 if (MI.getOpcode() == TargetOpcode::STATEPOINT) {
1101 assert((!MI.isDebugValue() || i == 0) &&
1102 "Frame indicies can only appear as the first operand of a "
1103 "DBG_VALUE machine instruction");
1105 MachineOperand &Offset = MI.getOperand(i + 1);
1106 int refOffset = TFI->getFrameIndexReferencePreferSP(
1107 Fn, MI.getOperand(i).getIndex(), Reg, /*IgnoreSPUpdates*/ false);
1108 Offset.setImm(Offset.getImm() + refOffset);
1109 MI.getOperand(i).ChangeToRegister(Reg, false /*isDef*/);
1113 // Some instructions (e.g. inline asm instructions) can have
1114 // multiple frame indices and/or cause eliminateFrameIndex
1115 // to insert more than one instruction. We need the register
1116 // scavenger to go through all of these instructions so that
1117 // it can update its register information. We keep the
1118 // iterator at the point before insertion so that we can
1119 // revisit them in full.
1120 bool AtBeginning = (I == BB->begin());
1121 if (!AtBeginning) --I;
1123 // If this instruction has a FrameIndex operand, we need to
1124 // use that target machine register info object to eliminate
1126 TRI.eliminateFrameIndex(MI, SPAdj, i,
1127 FrameIndexEliminationScavenging ? RS : nullptr);
1129 // Reset the iterator if we were at the beginning of the BB.
1135 DidFinishLoop = false;
1139 // If we are looking at a call sequence, we need to keep track of
1140 // the SP adjustment made by each instruction in the sequence.
1141 // This includes both the frame setup/destroy pseudos (handled above),
1142 // as well as other instructions that have side effects w.r.t the SP.
1143 // Note that this must come after eliminateFrameIndex, because
1144 // if I itself referred to a frame index, we shouldn't count its own
1146 if (DidFinishLoop && InsideCallSequence)
1147 SPAdj += TII.getSPAdjust(MI);
1149 if (DoIncr && I != BB->end()) ++I;
1151 // Update register states.
1152 if (RS && FrameIndexEliminationScavenging && DidFinishLoop)
1157 /// doScavengeFrameVirtualRegs - Replace all frame index virtual registers
1158 /// with physical registers. Use the register scavenger to find an
1159 /// appropriate register to use.
1161 /// FIXME: Iterating over the instruction stream is unnecessary. We can simply
1162 /// iterate over the vreg use list, which at this point only contains machine
1163 /// operands for which eliminateFrameIndex need a new scratch reg.
1165 doScavengeFrameVirtualRegs(MachineFunction &MF, RegScavenger *RS) {
1166 // Run through the instructions and find any virtual registers.
1167 MachineRegisterInfo &MRI = MF.getRegInfo();
1168 for (MachineBasicBlock &MBB : MF) {
1169 RS->enterBasicBlock(MBB);
1173 // The instruction stream may change in the loop, so check MBB.end()
1175 for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ) {
1176 // We might end up here again with a NULL iterator if we scavenged a
1177 // register for which we inserted spill code for definition by what was
1178 // originally the first instruction in MBB.
1179 if (I == MachineBasicBlock::iterator(nullptr))
1182 const MachineInstr &MI = *I;
1183 MachineBasicBlock::iterator J = std::next(I);
1184 MachineBasicBlock::iterator P =
1185 I == MBB.begin() ? MachineBasicBlock::iterator(nullptr)
1188 // RS should process this instruction before we might scavenge at this
1189 // location. This is because we might be replacing a virtual register
1190 // defined by this instruction, and if so, registers killed by this
1191 // instruction are available, and defined registers are not.
1194 for (const MachineOperand &MO : MI.operands()) {
1197 unsigned Reg = MO.getReg();
1198 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1201 // When we first encounter a new virtual register, it
1202 // must be a definition.
1203 assert(MO.isDef() && "frame index virtual missing def!");
1204 // Scavenge a new scratch register
1205 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
1206 unsigned ScratchReg = RS->scavengeRegister(RC, J, SPAdj);
1210 // Replace this reference to the virtual register with the
1211 // scratch register.
1212 assert(ScratchReg && "Missing scratch register!");
1213 MRI.replaceRegWith(Reg, ScratchReg);
1215 // Because this instruction was processed by the RS before this
1216 // register was allocated, make sure that the RS now records the
1217 // register as being used.
1218 RS->setRegUsed(ScratchReg);
1221 // If the scavenger needed to use one of its spill slots, the
1222 // spill code will have been inserted in between I and J. This is a
1223 // problem because we need the spill code before I: Move I to just
1225 if (I != std::prev(J)) {
1226 MBB.splice(J, &MBB, I);
1228 // Before we move I, we need to prepare the RS to visit I again.
1229 // Specifically, RS will assert if it sees uses of registers that
1230 // it believes are undefined. Because we have already processed
1231 // register kills in I, when it visits I again, it will believe that
1232 // those registers are undefined. To avoid this situation, unprocess
1233 // the instruction I.
1234 assert(RS->getCurrentPosition() == I &&
1235 "The register scavenger has an unexpected position");
1243 MF.getProperties().set(MachineFunctionProperties::Property::NoVRegs);