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/IndexedMap.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/MachineDominators.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineLoopInfo.h"
28 #include "llvm/CodeGen/MachineModuleInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/Passes.h"
31 #include "llvm/CodeGen/RegisterScavenging.h"
32 #include "llvm/CodeGen/StackProtector.h"
33 #include "llvm/CodeGen/WinEHFuncInfo.h"
34 #include "llvm/IR/DiagnosticInfo.h"
35 #include "llvm/IR/InlineAsm.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetFrameLowering.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetRegisterInfo.h"
45 #include "llvm/Target/TargetSubtargetInfo.h"
50 #define DEBUG_TYPE "pei"
53 class PEI : public MachineFunctionPass {
56 PEI() : MachineFunctionPass(ID) {
57 initializePEIPass(*PassRegistry::getPassRegistry());
60 void getAnalysisUsage(AnalysisUsage &AU) const override;
62 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
63 /// frame indexes with appropriate references.
65 bool runOnMachineFunction(MachineFunction &Fn) override;
70 // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved
71 // stack frame indexes.
72 unsigned MinCSFrameIndex, MaxCSFrameIndex;
74 // Save and Restore blocks of the current function. Typically there is a
75 // single save block, unless Windows EH funclets are involved.
76 SmallVector<MachineBasicBlock *, 1> SaveBlocks;
77 SmallVector<MachineBasicBlock *, 4> RestoreBlocks;
79 // Flag to control whether to use the register scavenger to resolve
80 // frame index materialization registers. Set according to
81 // TRI->requiresFrameIndexScavenging() for the current function.
82 bool FrameIndexVirtualScavenging;
84 void calculateSets(MachineFunction &Fn);
85 void calculateCallsInformation(MachineFunction &Fn);
86 void assignCalleeSavedSpillSlots(MachineFunction &Fn,
87 const BitVector &SavedRegs);
88 void insertCSRSpillsAndRestores(MachineFunction &Fn);
89 void calculateFrameObjectOffsets(MachineFunction &Fn);
90 void replaceFrameIndices(MachineFunction &Fn);
91 void replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
93 void scavengeFrameVirtualRegs(MachineFunction &Fn);
94 void insertPrologEpilogCode(MachineFunction &Fn);
99 char &llvm::PrologEpilogCodeInserterID = PEI::ID;
101 static cl::opt<unsigned>
102 WarnStackSize("warn-stack-size", cl::Hidden, cl::init((unsigned)-1),
103 cl::desc("Warn for stack size bigger than the given"
106 INITIALIZE_PASS_BEGIN(PEI, "prologepilog",
107 "Prologue/Epilogue Insertion", false, false)
108 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
109 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
110 INITIALIZE_PASS_DEPENDENCY(StackProtector)
111 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
112 INITIALIZE_PASS_END(PEI, "prologepilog",
113 "Prologue/Epilogue Insertion & Frame Finalization",
116 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
117 STATISTIC(NumBytesStackSpace,
118 "Number of bytes used for stack in all functions");
120 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
121 AU.setPreservesCFG();
122 AU.addPreserved<MachineLoopInfo>();
123 AU.addPreserved<MachineDominatorTree>();
124 AU.addRequired<StackProtector>();
125 AU.addRequired<TargetPassConfig>();
126 MachineFunctionPass::getAnalysisUsage(AU);
129 /// Compute the set of return blocks
130 void PEI::calculateSets(MachineFunction &Fn) {
131 const MachineFrameInfo *MFI = Fn.getFrameInfo();
133 // Even when we do not change any CSR, we still want to insert the
134 // prologue and epilogue of the function.
135 // So set the save points for those.
137 // Use the points found by shrink-wrapping, if any.
138 if (MFI->getSavePoint()) {
139 SaveBlocks.push_back(MFI->getSavePoint());
140 assert(MFI->getRestorePoint() && "Both restore and save must be set");
141 MachineBasicBlock *RestoreBlock = MFI->getRestorePoint();
142 // If RestoreBlock does not have any successor and is not a return block
143 // then the end point is unreachable and we do not need to insert any
145 if (!RestoreBlock->succ_empty() || RestoreBlock->isReturnBlock())
146 RestoreBlocks.push_back(RestoreBlock);
150 // Save refs to entry and return blocks.
151 SaveBlocks.push_back(Fn.begin());
152 for (MachineBasicBlock &MBB : Fn) {
153 if (MBB.isEHFuncletEntry())
154 SaveBlocks.push_back(&MBB);
155 if (MBB.isReturnBlock())
156 RestoreBlocks.push_back(&MBB);
160 /// StackObjSet - A set of stack object indexes
161 typedef SmallSetVector<int, 8> StackObjSet;
163 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
164 /// frame indexes with appropriate references.
166 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
167 const Function* F = Fn.getFunction();
168 const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
169 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
171 assert(!Fn.getRegInfo().getNumVirtRegs() && "Regalloc must assign all vregs");
173 RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : nullptr;
174 FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
176 // Calculate the MaxCallFrameSize and AdjustsStack variables for the
177 // function's frame information. Also eliminates call frame pseudo
179 calculateCallsInformation(Fn);
181 // Determine which of the registers in the callee save list should be saved.
183 TFI->determineCalleeSaves(Fn, SavedRegs, RS);
185 // Insert spill code for any callee saved registers that are modified.
186 assignCalleeSavedSpillSlots(Fn, SavedRegs);
188 // Determine placement of CSR spill/restore code:
189 // place all spills in the entry block, all restores in return blocks.
192 // Add the code to save and restore the callee saved registers.
193 if (!F->hasFnAttribute(Attribute::Naked))
194 insertCSRSpillsAndRestores(Fn);
196 // Allow the target machine to make final modifications to the function
197 // before the frame layout is finalized.
198 TFI->processFunctionBeforeFrameFinalized(Fn, RS);
200 // Calculate actual frame offsets for all abstract stack objects...
201 calculateFrameObjectOffsets(Fn);
203 // Add prolog and epilog code to the function. This function is required
204 // to align the stack frame as necessary for any stack variables or
205 // called functions. Because of this, calculateCalleeSavedRegisters()
206 // must be called before this function in order to set the AdjustsStack
207 // and MaxCallFrameSize variables.
208 if (!F->hasFnAttribute(Attribute::Naked))
209 insertPrologEpilogCode(Fn);
211 // Replace all MO_FrameIndex operands with physical register references
212 // and actual offsets.
214 replaceFrameIndices(Fn);
216 // If register scavenging is needed, as we've enabled doing it as a
217 // post-pass, scavenge the virtual registers that frame index elimination
219 if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
220 scavengeFrameVirtualRegs(Fn);
222 // Clear any vregs created by virtual scavenging.
223 Fn.getRegInfo().clearVirtRegs();
225 // Warn on stack size when we exceeds the given limit.
226 MachineFrameInfo *MFI = Fn.getFrameInfo();
227 uint64_t StackSize = MFI->getStackSize();
228 if (WarnStackSize.getNumOccurrences() > 0 && WarnStackSize < StackSize) {
229 DiagnosticInfoStackSize DiagStackSize(*F, StackSize);
230 F->getContext().diagnose(DiagStackSize);
235 RestoreBlocks.clear();
239 /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack
240 /// variables for the function's frame information and eliminate call frame
241 /// pseudo instructions.
242 void PEI::calculateCallsInformation(MachineFunction &Fn) {
243 const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
244 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
245 MachineFrameInfo *MFI = Fn.getFrameInfo();
247 unsigned MaxCallFrameSize = 0;
248 bool AdjustsStack = MFI->adjustsStack();
250 // Get the function call frame set-up and tear-down instruction opcode
251 unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
252 unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
254 // Early exit for targets which have no call frame setup/destroy pseudo
256 if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
259 std::vector<MachineBasicBlock::iterator> FrameSDOps;
260 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
261 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
262 if (I->getOpcode() == FrameSetupOpcode ||
263 I->getOpcode() == FrameDestroyOpcode) {
264 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
265 " instructions should have a single immediate argument!");
266 unsigned Size = I->getOperand(0).getImm();
267 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
269 FrameSDOps.push_back(I);
270 } else if (I->isInlineAsm()) {
271 // Some inline asm's need a stack frame, as indicated by operand 1.
272 unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
273 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
277 MFI->setAdjustsStack(AdjustsStack);
278 MFI->setMaxCallFrameSize(MaxCallFrameSize);
280 for (std::vector<MachineBasicBlock::iterator>::iterator
281 i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
282 MachineBasicBlock::iterator I = *i;
284 // If call frames are not being included as part of the stack frame, and
285 // the target doesn't indicate otherwise, remove the call frame pseudos
286 // here. The sub/add sp instruction pairs are still inserted, but we don't
287 // need to track the SP adjustment for frame index elimination.
288 if (TFI->canSimplifyCallFramePseudos(Fn))
289 TFI->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
293 void PEI::assignCalleeSavedSpillSlots(MachineFunction &F,
294 const BitVector &SavedRegs) {
295 // These are used to keep track the callee-save area. Initialize them.
296 MinCSFrameIndex = INT_MAX;
299 if (SavedRegs.empty())
302 const TargetRegisterInfo *RegInfo = F.getSubtarget().getRegisterInfo();
303 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&F);
305 std::vector<CalleeSavedInfo> CSI;
306 for (unsigned i = 0; CSRegs[i]; ++i) {
307 unsigned Reg = CSRegs[i];
308 if (SavedRegs.test(Reg))
309 CSI.push_back(CalleeSavedInfo(Reg));
312 const TargetFrameLowering *TFI = F.getSubtarget().getFrameLowering();
313 MachineFrameInfo *MFI = F.getFrameInfo();
314 if (!TFI->assignCalleeSavedSpillSlots(F, RegInfo, CSI)) {
315 // If target doesn't implement this, use generic code.
318 return; // Early exit if no callee saved registers are modified!
320 unsigned NumFixedSpillSlots;
321 const TargetFrameLowering::SpillSlot *FixedSpillSlots =
322 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
324 // Now that we know which registers need to be saved and restored, allocate
325 // stack slots for them.
326 for (std::vector<CalleeSavedInfo>::iterator I = CSI.begin(), E = CSI.end();
328 unsigned Reg = I->getReg();
329 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
332 if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) {
333 I->setFrameIdx(FrameIdx);
337 // Check to see if this physreg must be spilled to a particular stack slot
339 const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
340 while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots &&
341 FixedSlot->Reg != Reg)
344 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
345 // Nope, just spill it anywhere convenient.
346 unsigned Align = RC->getAlignment();
347 unsigned StackAlign = TFI->getStackAlignment();
349 // We may not be able to satisfy the desired alignment specification of
350 // the TargetRegisterClass if the stack alignment is smaller. Use the
352 Align = std::min(Align, StackAlign);
353 FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
354 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
355 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
357 // Spill it to the stack where we must.
359 MFI->CreateFixedSpillStackObject(RC->getSize(), FixedSlot->Offset);
362 I->setFrameIdx(FrameIdx);
366 MFI->setCalleeSavedInfo(CSI);
369 /// Helper function to update the liveness information for the callee-saved
371 static void updateLiveness(MachineFunction &MF) {
372 MachineFrameInfo *MFI = MF.getFrameInfo();
373 // Visited will contain all the basic blocks that are in the region
374 // where the callee saved registers are alive:
375 // - Anything that is not Save or Restore -> LiveThrough.
377 // - Restore -> LiveOut.
378 // The live-out is not attached to the block, so no need to keep
379 // Restore in this set.
380 SmallPtrSet<MachineBasicBlock *, 8> Visited;
381 SmallVector<MachineBasicBlock *, 8> WorkList;
382 MachineBasicBlock *Entry = &MF.front();
383 MachineBasicBlock *Save = MFI->getSavePoint();
389 WorkList.push_back(Entry);
390 Visited.insert(Entry);
392 Visited.insert(Save);
394 MachineBasicBlock *Restore = MFI->getRestorePoint();
396 // By construction Restore cannot be visited, otherwise it
397 // means there exists a path to Restore that does not go
399 WorkList.push_back(Restore);
401 while (!WorkList.empty()) {
402 const MachineBasicBlock *CurBB = WorkList.pop_back_val();
403 // By construction, the region that is after the save point is
404 // dominated by the Save and post-dominated by the Restore.
407 // Enqueue all the successors not already visited.
408 // Those are by construction either before Save or after Restore.
409 for (MachineBasicBlock *SuccBB : CurBB->successors())
410 if (Visited.insert(SuccBB).second)
411 WorkList.push_back(SuccBB);
414 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
416 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
417 for (MachineBasicBlock *MBB : Visited)
418 // Add the callee-saved register as live-in.
419 // It's killed at the spill.
420 MBB->addLiveIn(CSI[i].getReg());
424 /// insertCSRSpillsAndRestores - Insert spill and restore code for
425 /// callee saved registers used in the function.
427 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
428 // Get callee saved register information.
429 MachineFrameInfo *MFI = Fn.getFrameInfo();
430 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
432 MFI->setCalleeSavedInfoValid(true);
434 // Early exit if no callee saved registers are modified!
438 const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
439 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
440 const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
441 MachineBasicBlock::iterator I;
443 // Spill using target interface.
444 for (MachineBasicBlock *SaveBlock : SaveBlocks) {
445 I = SaveBlock->begin();
446 if (!TFI->spillCalleeSavedRegisters(*SaveBlock, I, CSI, TRI)) {
447 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
448 // Insert the spill to the stack frame.
449 unsigned Reg = CSI[i].getReg();
450 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
451 TII.storeRegToStackSlot(*SaveBlock, I, Reg, true, CSI[i].getFrameIdx(),
455 // Update the live-in information of all the blocks up to the save point.
459 // Restore using target interface.
460 for (MachineBasicBlock *MBB : RestoreBlocks) {
463 // Skip over all terminator instructions, which are part of the return
465 MachineBasicBlock::iterator I2 = I;
466 while (I2 != MBB->begin() && (--I2)->isTerminator())
469 bool AtStart = I == MBB->begin();
470 MachineBasicBlock::iterator BeforeI = I;
474 // Restore all registers immediately before the return and any
475 // terminators that precede it.
476 if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
477 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
478 unsigned Reg = CSI[i].getReg();
479 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
480 TII.loadRegFromStackSlot(*MBB, I, Reg, CSI[i].getFrameIdx(), RC, TRI);
481 assert(I != MBB->begin() &&
482 "loadRegFromStackSlot didn't insert any code!");
483 // Insert in reverse order. loadRegFromStackSlot can insert
484 // multiple instructions.
496 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
498 AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
499 bool StackGrowsDown, int64_t &Offset,
500 unsigned &MaxAlign) {
501 // If the stack grows down, add the object size to find the lowest address.
503 Offset += MFI->getObjectSize(FrameIdx);
505 unsigned Align = MFI->getObjectAlignment(FrameIdx);
507 // If the alignment of this object is greater than that of the stack, then
508 // increase the stack alignment to match.
509 MaxAlign = std::max(MaxAlign, Align);
511 // Adjust to alignment boundary.
512 Offset = RoundUpToAlignment(Offset, Align);
514 if (StackGrowsDown) {
515 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
516 MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
518 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
519 MFI->setObjectOffset(FrameIdx, Offset);
520 Offset += MFI->getObjectSize(FrameIdx);
524 /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
525 /// those required to be close to the Stack Protector) to stack offsets.
527 AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
528 SmallSet<int, 16> &ProtectedObjs,
529 MachineFrameInfo *MFI, bool StackGrowsDown,
530 int64_t &Offset, unsigned &MaxAlign) {
532 for (StackObjSet::const_iterator I = UnassignedObjs.begin(),
533 E = UnassignedObjs.end(); I != E; ++I) {
535 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
536 ProtectedObjs.insert(i);
540 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
541 /// abstract stack objects.
543 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
544 const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
545 StackProtector *SP = &getAnalysis<StackProtector>();
547 bool StackGrowsDown =
548 TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
550 // Loop over all of the stack objects, assigning sequential addresses...
551 MachineFrameInfo *MFI = Fn.getFrameInfo();
553 // Start at the beginning of the local area.
554 // The Offset is the distance from the stack top in the direction
555 // of stack growth -- so it's always nonnegative.
556 int LocalAreaOffset = TFI.getOffsetOfLocalArea();
558 LocalAreaOffset = -LocalAreaOffset;
559 assert(LocalAreaOffset >= 0
560 && "Local area offset should be in direction of stack growth");
561 int64_t Offset = LocalAreaOffset;
563 // If there are fixed sized objects that are preallocated in the local area,
564 // non-fixed objects can't be allocated right at the start of local area.
565 // We currently don't support filling in holes in between fixed sized
566 // objects, so we adjust 'Offset' to point to the end of last fixed sized
567 // preallocated object.
568 for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
570 if (StackGrowsDown) {
571 // The maximum distance from the stack pointer is at lower address of
572 // the object -- which is given by offset. For down growing stack
573 // the offset is negative, so we negate the offset to get the distance.
574 FixedOff = -MFI->getObjectOffset(i);
576 // The maximum distance from the start pointer is at the upper
577 // address of the object.
578 FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
580 if (FixedOff > Offset) Offset = FixedOff;
583 // First assign frame offsets to stack objects that are used to spill
584 // callee saved registers.
585 if (StackGrowsDown) {
586 for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
587 // If the stack grows down, we need to add the size to find the lowest
588 // address of the object.
589 Offset += MFI->getObjectSize(i);
591 unsigned Align = MFI->getObjectAlignment(i);
592 // Adjust to alignment boundary
593 Offset = RoundUpToAlignment(Offset, Align);
595 MFI->setObjectOffset(i, -Offset); // Set the computed offset
598 int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
599 for (int i = MaxCSFI; i >= MinCSFI ; --i) {
600 unsigned Align = MFI->getObjectAlignment(i);
601 // Adjust to alignment boundary
602 Offset = RoundUpToAlignment(Offset, Align);
604 MFI->setObjectOffset(i, Offset);
605 Offset += MFI->getObjectSize(i);
609 unsigned MaxAlign = MFI->getMaxAlignment();
611 // Make sure the special register scavenging spill slot is closest to the
612 // incoming stack pointer if a frame pointer is required and is closer
613 // to the incoming rather than the final stack pointer.
614 const TargetRegisterInfo *RegInfo = Fn.getSubtarget().getRegisterInfo();
615 bool EarlyScavengingSlots = (TFI.hasFP(Fn) &&
616 TFI.isFPCloseToIncomingSP() &&
617 RegInfo->useFPForScavengingIndex(Fn) &&
618 !RegInfo->needsStackRealignment(Fn));
619 if (RS && EarlyScavengingSlots) {
620 SmallVector<int, 2> SFIs;
621 RS->getScavengingFrameIndices(SFIs);
622 for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
623 IE = SFIs.end(); I != IE; ++I)
624 AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign);
627 // FIXME: Once this is working, then enable flag will change to a target
628 // check for whether the frame is large enough to want to use virtual
629 // frame index registers. Functions which don't want/need this optimization
630 // will continue to use the existing code path.
631 if (MFI->getUseLocalStackAllocationBlock()) {
632 unsigned Align = MFI->getLocalFrameMaxAlign();
634 // Adjust to alignment boundary.
635 Offset = RoundUpToAlignment(Offset, Align);
637 DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
639 // Resolve offsets for objects in the local block.
640 for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) {
641 std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i);
642 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
643 DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
645 MFI->setObjectOffset(Entry.first, FIOffset);
647 // Allocate the local block
648 Offset += MFI->getLocalFrameSize();
650 MaxAlign = std::max(Align, MaxAlign);
653 // Make sure that the stack protector comes before the local variables on the
655 SmallSet<int, 16> ProtectedObjs;
656 if (MFI->getStackProtectorIndex() >= 0) {
657 StackObjSet LargeArrayObjs;
658 StackObjSet SmallArrayObjs;
659 StackObjSet AddrOfObjs;
661 AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
664 // Assign large stack objects first.
665 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
666 if (MFI->isObjectPreAllocated(i) &&
667 MFI->getUseLocalStackAllocationBlock())
669 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
671 if (RS && RS->isScavengingFrameIndex((int)i))
673 if (MFI->isDeadObjectIndex(i))
675 if (MFI->getStackProtectorIndex() == (int)i)
678 switch (SP->getSSPLayout(MFI->getObjectAllocation(i))) {
679 case StackProtector::SSPLK_None:
681 case StackProtector::SSPLK_SmallArray:
682 SmallArrayObjs.insert(i);
684 case StackProtector::SSPLK_AddrOf:
685 AddrOfObjs.insert(i);
687 case StackProtector::SSPLK_LargeArray:
688 LargeArrayObjs.insert(i);
691 llvm_unreachable("Unexpected SSPLayoutKind.");
694 AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
696 AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
698 AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
702 // Then assign frame offsets to stack objects that are not used to spill
703 // callee saved registers.
704 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
705 if (MFI->isObjectPreAllocated(i) &&
706 MFI->getUseLocalStackAllocationBlock())
708 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
710 if (RS && RS->isScavengingFrameIndex((int)i))
712 if (MFI->isDeadObjectIndex(i))
714 if (MFI->getStackProtectorIndex() == (int)i)
716 if (ProtectedObjs.count(i))
719 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
722 // Make sure the special register scavenging spill slot is closest to the
724 if (RS && !EarlyScavengingSlots) {
725 SmallVector<int, 2> SFIs;
726 RS->getScavengingFrameIndices(SFIs);
727 for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
728 IE = SFIs.end(); I != IE; ++I)
729 AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign);
732 if (!TFI.targetHandlesStackFrameRounding()) {
733 // If we have reserved argument space for call sites in the function
734 // immediately on entry to the current function, count it as part of the
735 // overall stack size.
736 if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn))
737 Offset += MFI->getMaxCallFrameSize();
739 // Round up the size to a multiple of the alignment. If the function has
740 // any calls or alloca's, align to the target's StackAlignment value to
741 // ensure that the callee's frame or the alloca data is suitably aligned;
742 // otherwise, for leaf functions, align to the TransientStackAlignment
745 if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
746 (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
747 StackAlign = TFI.getStackAlignment();
749 StackAlign = TFI.getTransientStackAlignment();
751 // If the frame pointer is eliminated, all frame offsets will be relative to
752 // SP not FP. Align to MaxAlign so this works.
753 StackAlign = std::max(StackAlign, MaxAlign);
754 Offset = RoundUpToAlignment(Offset, StackAlign);
757 // Update frame info to pretend that this is part of the stack...
758 int64_t StackSize = Offset - LocalAreaOffset;
759 MFI->setStackSize(StackSize);
760 NumBytesStackSpace += StackSize;
763 /// insertPrologEpilogCode - Scan the function for modified callee saved
764 /// registers, insert spill code for these callee saved registers, then add
765 /// prolog and epilog code to the function.
767 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
768 const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
770 // Add prologue to the function...
771 for (MachineBasicBlock *SaveBlock : SaveBlocks)
772 TFI.emitPrologue(Fn, *SaveBlock);
774 // Add epilogue to restore the callee-save registers in each exiting block.
775 for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
776 TFI.emitEpilogue(Fn, *RestoreBlock);
778 // Emit additional code that is required to support segmented stacks, if
779 // we've been asked for it. This, when linked with a runtime with support
780 // for segmented stacks (libgcc is one), will result in allocating stack
781 // space in small chunks instead of one large contiguous block.
782 if (Fn.shouldSplitStack()) {
783 for (MachineBasicBlock *SaveBlock : SaveBlocks)
784 TFI.adjustForSegmentedStacks(Fn, *SaveBlock);
787 // Emit additional code that is required to explicitly handle the stack in
788 // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
789 // approach is rather similar to that of Segmented Stacks, but it uses a
790 // different conditional check and another BIF for allocating more stack
792 if (Fn.getFunction()->getCallingConv() == CallingConv::HiPE)
793 for (MachineBasicBlock *SaveBlock : SaveBlocks)
794 TFI.adjustForHiPEPrologue(Fn, *SaveBlock);
797 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
798 /// register references and actual offsets.
800 void PEI::replaceFrameIndices(MachineFunction &Fn) {
801 const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
802 if (!TFI.needsFrameIndexResolution(Fn)) return;
804 MachineModuleInfo &MMI = Fn.getMMI();
805 const Function *F = Fn.getFunction();
806 const Function *ParentF = MMI.getWinEHParent(F);
809 WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(Fn.getFunction());
810 // FIXME: This should be unconditional but we have bugs in the preparation
812 if (FuncInfo.UnwindHelpFrameIdx != INT_MAX)
813 FuncInfo.UnwindHelpFrameOffset = TFI.getFrameIndexReferenceFromSP(
814 Fn, FuncInfo.UnwindHelpFrameIdx, FrameReg);
815 for (WinEHTryBlockMapEntry &TBME : FuncInfo.TryBlockMap) {
816 for (WinEHHandlerType &H : TBME.HandlerArray) {
818 if (H.CatchObj.FrameIndex == INT_MAX)
819 H.CatchObj.FrameOffset = INT_MAX;
821 H.CatchObj.FrameOffset =
822 TFI.getFrameIndexReference(Fn, H.CatchObj.FrameIndex, UnusedReg);
827 // Store SPAdj at exit of a basic block.
828 SmallVector<int, 8> SPState;
829 SPState.resize(Fn.getNumBlockIDs());
830 SmallPtrSet<MachineBasicBlock*, 8> Reachable;
832 // Iterate over the reachable blocks in DFS order.
833 for (auto DFI = df_ext_begin(&Fn, Reachable), DFE = df_ext_end(&Fn, Reachable);
836 // Check the exit state of the DFS stack predecessor.
837 if (DFI.getPathLength() >= 2) {
838 MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
839 assert(Reachable.count(StackPred) &&
840 "DFS stack predecessor is already visited.\n");
841 SPAdj = SPState[StackPred->getNumber()];
843 MachineBasicBlock *BB = *DFI;
844 replaceFrameIndices(BB, Fn, SPAdj);
845 SPState[BB->getNumber()] = SPAdj;
848 // Handle the unreachable blocks.
849 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
850 if (Reachable.count(BB))
851 // Already handled in DFS traversal.
854 replaceFrameIndices(BB, Fn, SPAdj);
858 void PEI::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
860 assert(Fn.getSubtarget().getRegisterInfo() &&
861 "getRegisterInfo() must be implemented!");
862 const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
863 const TargetRegisterInfo &TRI = *Fn.getSubtarget().getRegisterInfo();
864 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
865 unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
866 unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
868 if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
870 bool InsideCallSequence = false;
872 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
874 if (I->getOpcode() == FrameSetupOpcode ||
875 I->getOpcode() == FrameDestroyOpcode) {
876 InsideCallSequence = (I->getOpcode() == FrameSetupOpcode);
877 SPAdj += TII.getSPAdjust(I);
879 MachineBasicBlock::iterator PrevI = BB->end();
880 if (I != BB->begin()) PrevI = std::prev(I);
881 TFI->eliminateCallFramePseudoInstr(Fn, *BB, I);
883 // Visit the instructions created by eliminateCallFramePseudoInstr().
884 if (PrevI == BB->end())
885 I = BB->begin(); // The replaced instr was the first in the block.
887 I = std::next(PrevI);
891 MachineInstr *MI = I;
893 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
894 if (!MI->getOperand(i).isFI())
897 // Frame indices in debug values are encoded in a target independent
898 // way with simply the frame index and offset rather than any
899 // target-specific addressing mode.
900 if (MI->isDebugValue()) {
901 assert(i == 0 && "Frame indices can only appear as the first "
902 "operand of a DBG_VALUE machine instruction");
904 MachineOperand &Offset = MI->getOperand(1);
905 Offset.setImm(Offset.getImm() +
906 TFI->getFrameIndexReference(
907 Fn, MI->getOperand(0).getIndex(), Reg));
908 MI->getOperand(0).ChangeToRegister(Reg, false /*isDef*/);
912 // TODO: This code should be commoned with the code for
913 // PATCHPOINT. There's no good reason for the difference in
914 // implementation other than historical accident. The only
915 // remaining difference is the unconditional use of the stack
916 // pointer as the base register.
917 if (MI->getOpcode() == TargetOpcode::STATEPOINT) {
918 assert((!MI->isDebugValue() || i == 0) &&
919 "Frame indicies can only appear as the first operand of a "
920 "DBG_VALUE machine instruction");
922 MachineOperand &Offset = MI->getOperand(i + 1);
923 const unsigned refOffset =
924 TFI->getFrameIndexReferenceFromSP(Fn, MI->getOperand(i).getIndex(),
927 Offset.setImm(Offset.getImm() + refOffset);
928 MI->getOperand(i).ChangeToRegister(Reg, false /*isDef*/);
932 // Some instructions (e.g. inline asm instructions) can have
933 // multiple frame indices and/or cause eliminateFrameIndex
934 // to insert more than one instruction. We need the register
935 // scavenger to go through all of these instructions so that
936 // it can update its register information. We keep the
937 // iterator at the point before insertion so that we can
938 // revisit them in full.
939 bool AtBeginning = (I == BB->begin());
940 if (!AtBeginning) --I;
942 // If this instruction has a FrameIndex operand, we need to
943 // use that target machine register info object to eliminate
945 TRI.eliminateFrameIndex(MI, SPAdj, i,
946 FrameIndexVirtualScavenging ? nullptr : RS);
948 // Reset the iterator if we were at the beginning of the BB.
958 // If we are looking at a call sequence, we need to keep track of
959 // the SP adjustment made by each instruction in the sequence.
960 // This includes both the frame setup/destroy pseudos (handled above),
961 // as well as other instructions that have side effects w.r.t the SP.
962 // Note that this must come after eliminateFrameIndex, because
963 // if I itself referred to a frame index, we shouldn't count its own
965 if (MI && InsideCallSequence)
966 SPAdj += TII.getSPAdjust(MI);
968 if (DoIncr && I != BB->end()) ++I;
970 // Update register states.
971 if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
975 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
976 /// with physical registers. Use the register scavenger to find an
977 /// appropriate register to use.
979 /// FIXME: Iterating over the instruction stream is unnecessary. We can simply
980 /// iterate over the vreg use list, which at this point only contains machine
981 /// operands for which eliminateFrameIndex need a new scratch reg.
983 PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
984 // Run through the instructions and find any virtual registers.
985 for (MachineFunction::iterator BB = Fn.begin(),
986 E = Fn.end(); BB != E; ++BB) {
987 RS->enterBasicBlock(BB);
991 // The instruction stream may change in the loop, so check BB->end()
993 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
994 // We might end up here again with a NULL iterator if we scavenged a
995 // register for which we inserted spill code for definition by what was
996 // originally the first instruction in BB.
997 if (I == MachineBasicBlock::iterator(nullptr))
1000 MachineInstr *MI = I;
1001 MachineBasicBlock::iterator J = std::next(I);
1002 MachineBasicBlock::iterator P =
1003 I == BB->begin() ? MachineBasicBlock::iterator(nullptr)
1006 // RS should process this instruction before we might scavenge at this
1007 // location. This is because we might be replacing a virtual register
1008 // defined by this instruction, and if so, registers killed by this
1009 // instruction are available, and defined registers are not.
1012 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1013 if (MI->getOperand(i).isReg()) {
1014 MachineOperand &MO = MI->getOperand(i);
1015 unsigned Reg = MO.getReg();
1018 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1021 // When we first encounter a new virtual register, it
1022 // must be a definition.
1023 assert(MI->getOperand(i).isDef() &&
1024 "frame index virtual missing def!");
1025 // Scavenge a new scratch register
1026 const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
1027 unsigned ScratchReg = RS->scavengeRegister(RC, J, SPAdj);
1031 // Replace this reference to the virtual register with the
1032 // scratch register.
1033 assert (ScratchReg && "Missing scratch register!");
1034 Fn.getRegInfo().replaceRegWith(Reg, ScratchReg);
1036 // Because this instruction was processed by the RS before this
1037 // register was allocated, make sure that the RS now records the
1038 // register as being used.
1039 RS->setRegUsed(ScratchReg);
1043 // If the scavenger needed to use one of its spill slots, the
1044 // spill code will have been inserted in between I and J. This is a
1045 // problem because we need the spill code before I: Move I to just
1047 if (I != std::prev(J)) {
1048 BB->splice(J, BB, I);
1050 // Before we move I, we need to prepare the RS to visit I again.
1051 // Specifically, RS will assert if it sees uses of registers that
1052 // it believes are undefined. Because we have already processed
1053 // register kills in I, when it visits I again, it will believe that
1054 // those registers are undefined. To avoid this situation, unprocess
1055 // the instruction I.
1056 assert(RS->getCurrentPosition() == I &&
1057 "The register scavenger has an unexpected position");