1 //===- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function ---===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This pass is responsible for finalizing the functions frame layout, saving
10 // callee saved registers, and for emitting prolog & epilog code for the
13 // This pass must be run after register allocation. After this pass is
14 // executed, it is illegal to construct MO_FrameIndex operands.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
27 #include "llvm/CodeGen/MachineBasicBlock.h"
28 #include "llvm/CodeGen/MachineDominators.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineLoopInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineOperand.h"
37 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
38 #include "llvm/CodeGen/MachineRegisterInfo.h"
39 #include "llvm/CodeGen/RegisterScavenging.h"
40 #include "llvm/CodeGen/TargetFrameLowering.h"
41 #include "llvm/CodeGen/TargetInstrInfo.h"
42 #include "llvm/CodeGen/TargetOpcodes.h"
43 #include "llvm/CodeGen/TargetRegisterInfo.h"
44 #include "llvm/CodeGen/TargetSubtargetInfo.h"
45 #include "llvm/CodeGen/WinEHFuncInfo.h"
46 #include "llvm/IR/Attributes.h"
47 #include "llvm/IR/CallingConv.h"
48 #include "llvm/IR/DebugInfoMetadata.h"
49 #include "llvm/IR/DiagnosticInfo.h"
50 #include "llvm/IR/Function.h"
51 #include "llvm/IR/InlineAsm.h"
52 #include "llvm/IR/LLVMContext.h"
53 #include "llvm/InitializePasses.h"
54 #include "llvm/MC/MCRegisterInfo.h"
55 #include "llvm/Pass.h"
56 #include "llvm/Support/CodeGen.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/ErrorHandling.h"
59 #include "llvm/Support/FormatVariadic.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include "llvm/Target/TargetMachine.h"
62 #include "llvm/Target/TargetOptions.h"
73 #define DEBUG_TYPE "prologepilog"
75 using MBBVector
= SmallVector
<MachineBasicBlock
*, 4>;
77 STATISTIC(NumLeafFuncWithSpills
, "Number of leaf functions with CSRs");
78 STATISTIC(NumFuncSeen
, "Number of functions seen in PEI");
83 class PEI
: public MachineFunctionPass
{
87 PEI() : MachineFunctionPass(ID
) {
88 initializePEIPass(*PassRegistry::getPassRegistry());
91 void getAnalysisUsage(AnalysisUsage
&AU
) const override
;
93 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
94 /// frame indexes with appropriate references.
95 bool runOnMachineFunction(MachineFunction
&MF
) override
;
98 RegScavenger
*RS
= nullptr;
100 // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved
101 // stack frame indexes.
102 unsigned MinCSFrameIndex
= std::numeric_limits
<unsigned>::max();
103 unsigned MaxCSFrameIndex
= 0;
105 // Save and Restore blocks of the current function. Typically there is a
106 // single save block, unless Windows EH funclets are involved.
107 MBBVector SaveBlocks
;
108 MBBVector RestoreBlocks
;
110 // Flag to control whether to use the register scavenger to resolve
111 // frame index materialization registers. Set according to
112 // TRI->requiresFrameIndexScavenging() for the current function.
113 bool FrameIndexVirtualScavenging
= false;
115 // Flag to control whether the scavenger should be passed even though
116 // FrameIndexVirtualScavenging is used.
117 bool FrameIndexEliminationScavenging
= false;
120 MachineOptimizationRemarkEmitter
*ORE
= nullptr;
122 void calculateCallFrameInfo(MachineFunction
&MF
);
123 void calculateSaveRestoreBlocks(MachineFunction
&MF
);
124 void spillCalleeSavedRegs(MachineFunction
&MF
);
126 void calculateFrameObjectOffsets(MachineFunction
&MF
);
127 void replaceFrameIndices(MachineFunction
&MF
);
128 void replaceFrameIndices(MachineBasicBlock
*BB
, MachineFunction
&MF
,
130 // Frame indices in debug values are encoded in a target independent
131 // way with simply the frame index and offset rather than any
132 // target-specific addressing mode.
133 bool replaceFrameIndexDebugInstr(MachineFunction
&MF
, MachineInstr
&MI
,
134 unsigned OpIdx
, int SPAdj
= 0);
135 // Does same as replaceFrameIndices but using the backward MIR walk and
136 // backward register scavenger walk.
137 void replaceFrameIndicesBackward(MachineFunction
&MF
);
138 void replaceFrameIndicesBackward(MachineBasicBlock
*BB
, MachineFunction
&MF
,
141 void insertPrologEpilogCode(MachineFunction
&MF
);
142 void insertZeroCallUsedRegs(MachineFunction
&MF
);
145 } // end anonymous namespace
149 char &llvm::PrologEpilogCodeInserterID
= PEI::ID
;
151 INITIALIZE_PASS_BEGIN(PEI
, DEBUG_TYPE
, "Prologue/Epilogue Insertion", false,
153 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfoWrapperPass
)
154 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass
)
155 INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass
)
156 INITIALIZE_PASS_END(PEI
, DEBUG_TYPE
,
157 "Prologue/Epilogue Insertion & Frame Finalization", false,
160 MachineFunctionPass
*llvm::createPrologEpilogInserterPass() {
164 STATISTIC(NumBytesStackSpace
,
165 "Number of bytes used for stack in all functions");
167 void PEI::getAnalysisUsage(AnalysisUsage
&AU
) const {
168 AU
.setPreservesCFG();
169 AU
.addPreserved
<MachineLoopInfoWrapperPass
>();
170 AU
.addPreserved
<MachineDominatorTreeWrapperPass
>();
171 AU
.addRequired
<MachineOptimizationRemarkEmitterPass
>();
172 MachineFunctionPass::getAnalysisUsage(AU
);
175 /// StackObjSet - A set of stack object indexes
176 using StackObjSet
= SmallSetVector
<int, 8>;
178 using SavedDbgValuesMap
=
179 SmallDenseMap
<MachineBasicBlock
*, SmallVector
<MachineInstr
*, 4>, 4>;
181 /// Stash DBG_VALUEs that describe parameters and which are placed at the start
182 /// of the block. Later on, after the prologue code has been emitted, the
183 /// stashed DBG_VALUEs will be reinserted at the start of the block.
184 static void stashEntryDbgValues(MachineBasicBlock
&MBB
,
185 SavedDbgValuesMap
&EntryDbgValues
) {
186 SmallVector
<const MachineInstr
*, 4> FrameIndexValues
;
188 for (auto &MI
: MBB
) {
189 if (!MI
.isDebugInstr())
191 if (!MI
.isDebugValue() || !MI
.getDebugVariable()->isParameter())
193 if (any_of(MI
.debug_operands(),
194 [](const MachineOperand
&MO
) { return MO
.isFI(); })) {
195 // We can only emit valid locations for frame indices after the frame
196 // setup, so do not stash away them.
197 FrameIndexValues
.push_back(&MI
);
200 const DILocalVariable
*Var
= MI
.getDebugVariable();
201 const DIExpression
*Expr
= MI
.getDebugExpression();
202 auto Overlaps
= [Var
, Expr
](const MachineInstr
*DV
) {
203 return Var
== DV
->getDebugVariable() &&
204 Expr
->fragmentsOverlap(DV
->getDebugExpression());
206 // See if the debug value overlaps with any preceding debug value that will
207 // not be stashed. If that is the case, then we can't stash this value, as
208 // we would then reorder the values at reinsertion.
209 if (llvm::none_of(FrameIndexValues
, Overlaps
))
210 EntryDbgValues
[&MBB
].push_back(&MI
);
213 // Remove stashed debug values from the block.
214 if (EntryDbgValues
.count(&MBB
))
215 for (auto *MI
: EntryDbgValues
[&MBB
])
216 MI
->removeFromParent();
219 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
220 /// frame indexes with appropriate references.
221 bool PEI::runOnMachineFunction(MachineFunction
&MF
) {
223 const Function
&F
= MF
.getFunction();
224 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
225 const TargetFrameLowering
*TFI
= MF
.getSubtarget().getFrameLowering();
227 RS
= TRI
->requiresRegisterScavenging(MF
) ? new RegScavenger() : nullptr;
228 FrameIndexVirtualScavenging
= TRI
->requiresFrameIndexScavenging(MF
);
229 ORE
= &getAnalysis
<MachineOptimizationRemarkEmitterPass
>().getORE();
231 // Calculate the MaxCallFrameSize value for the function's frame
232 // information. Also eliminates call frame pseudo instructions.
233 calculateCallFrameInfo(MF
);
235 // Determine placement of CSR spill/restore code and prolog/epilog code:
236 // place all spills in the entry block, all restores in return blocks.
237 calculateSaveRestoreBlocks(MF
);
239 // Stash away DBG_VALUEs that should not be moved by insertion of prolog code.
240 SavedDbgValuesMap EntryDbgValues
;
241 for (MachineBasicBlock
*SaveBlock
: SaveBlocks
)
242 stashEntryDbgValues(*SaveBlock
, EntryDbgValues
);
244 // Handle CSR spilling and restoring, for targets that need it.
245 if (MF
.getTarget().usesPhysRegsForValues())
246 spillCalleeSavedRegs(MF
);
248 // Allow the target machine to make final modifications to the function
249 // before the frame layout is finalized.
250 TFI
->processFunctionBeforeFrameFinalized(MF
, RS
);
252 // Calculate actual frame offsets for all abstract stack objects...
253 calculateFrameObjectOffsets(MF
);
255 // Add prolog and epilog code to the function. This function is required
256 // to align the stack frame as necessary for any stack variables or
257 // called functions. Because of this, calculateCalleeSavedRegisters()
258 // must be called before this function in order to set the AdjustsStack
259 // and MaxCallFrameSize variables.
260 if (!F
.hasFnAttribute(Attribute::Naked
))
261 insertPrologEpilogCode(MF
);
263 // Reinsert stashed debug values at the start of the entry blocks.
264 for (auto &I
: EntryDbgValues
)
265 I
.first
->insert(I
.first
->begin(), I
.second
.begin(), I
.second
.end());
267 // Allow the target machine to make final modifications to the function
268 // before the frame layout is finalized.
269 TFI
->processFunctionBeforeFrameIndicesReplaced(MF
, RS
);
271 // Replace all MO_FrameIndex operands with physical register references
272 // and actual offsets.
273 if (TFI
->needsFrameIndexResolution(MF
)) {
274 // Allow the target to determine this after knowing the frame size.
275 FrameIndexEliminationScavenging
=
276 (RS
&& !FrameIndexVirtualScavenging
) ||
277 TRI
->requiresFrameIndexReplacementScavenging(MF
);
279 if (TRI
->eliminateFrameIndicesBackwards())
280 replaceFrameIndicesBackward(MF
);
282 replaceFrameIndices(MF
);
285 // If register scavenging is needed, as we've enabled doing it as a
286 // post-pass, scavenge the virtual registers that frame index elimination
288 if (TRI
->requiresRegisterScavenging(MF
) && FrameIndexVirtualScavenging
)
289 scavengeFrameVirtualRegs(MF
, *RS
);
291 // Warn on stack size when we exceeds the given limit.
292 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
293 uint64_t StackSize
= MFI
.getStackSize();
295 uint64_t Threshold
= TFI
->getStackThreshold();
296 if (MF
.getFunction().hasFnAttribute("warn-stack-size")) {
297 bool Failed
= MF
.getFunction()
298 .getFnAttribute("warn-stack-size")
300 .getAsInteger(10, Threshold
);
301 // Verifier should have caught this.
302 assert(!Failed
&& "Invalid warn-stack-size fn attr value");
305 uint64_t UnsafeStackSize
= MFI
.getUnsafeStackSize();
306 if (MF
.getFunction().hasFnAttribute(Attribute::SafeStack
))
307 StackSize
+= UnsafeStackSize
;
309 if (StackSize
> Threshold
) {
310 DiagnosticInfoStackSize
DiagStackSize(F
, StackSize
, Threshold
, DS_Warning
);
311 F
.getContext().diagnose(DiagStackSize
);
312 int64_t SpillSize
= 0;
313 for (int Idx
= MFI
.getObjectIndexBegin(), End
= MFI
.getObjectIndexEnd();
315 if (MFI
.isSpillSlotObjectIndex(Idx
))
316 SpillSize
+= MFI
.getObjectSize(Idx
);
319 [[maybe_unused
]] float SpillPct
=
320 static_cast<float>(SpillSize
) / static_cast<float>(StackSize
);
322 dbgs() << formatv("{0}/{1} ({3:P}) spills, {2}/{1} ({4:P}) variables",
323 SpillSize
, StackSize
, StackSize
- SpillSize
, SpillPct
,
325 if (UnsafeStackSize
!= 0) {
326 LLVM_DEBUG(dbgs() << formatv(", {0}/{2} ({1:P}) unsafe stack",
328 static_cast<float>(UnsafeStackSize
) /
329 static_cast<float>(StackSize
),
332 LLVM_DEBUG(dbgs() << "\n");
336 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE
, "StackSize",
337 MF
.getFunction().getSubprogram(),
339 << ore::NV("NumStackBytes", StackSize
)
340 << " stack bytes in function '"
341 << ore::NV("Function", MF
.getFunction().getName()) << "'";
344 // Emit any remarks implemented for the target, based on final frame layout.
345 TFI
->emitRemarks(MF
, ORE
);
349 RestoreBlocks
.clear();
350 MFI
.setSavePoint(nullptr);
351 MFI
.setRestorePoint(nullptr);
355 /// Calculate the MaxCallFrameSize variable for the function's frame
356 /// information and eliminate call frame pseudo instructions.
357 void PEI::calculateCallFrameInfo(MachineFunction
&MF
) {
358 const TargetInstrInfo
&TII
= *MF
.getSubtarget().getInstrInfo();
359 const TargetFrameLowering
*TFI
= MF
.getSubtarget().getFrameLowering();
360 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
362 // Get the function call frame set-up and tear-down instruction opcode
363 unsigned FrameSetupOpcode
= TII
.getCallFrameSetupOpcode();
364 unsigned FrameDestroyOpcode
= TII
.getCallFrameDestroyOpcode();
366 // Early exit for targets which have no call frame setup/destroy pseudo
368 if (FrameSetupOpcode
== ~0u && FrameDestroyOpcode
== ~0u)
371 // (Re-)Compute the MaxCallFrameSize.
372 [[maybe_unused
]] uint64_t MaxCFSIn
=
373 MFI
.isMaxCallFrameSizeComputed() ? MFI
.getMaxCallFrameSize() : UINT64_MAX
;
374 std::vector
<MachineBasicBlock::iterator
> FrameSDOps
;
375 MFI
.computeMaxCallFrameSize(MF
, &FrameSDOps
);
376 assert(MFI
.getMaxCallFrameSize() <= MaxCFSIn
&&
377 "Recomputing MaxCFS gave a larger value.");
378 assert((FrameSDOps
.empty() || MF
.getFrameInfo().adjustsStack()) &&
379 "AdjustsStack not set in presence of a frame pseudo instruction.");
381 if (TFI
->canSimplifyCallFramePseudos(MF
)) {
382 // If call frames are not being included as part of the stack frame, and
383 // the target doesn't indicate otherwise, remove the call frame pseudos
384 // here. The sub/add sp instruction pairs are still inserted, but we don't
385 // need to track the SP adjustment for frame index elimination.
386 for (MachineBasicBlock::iterator I
: FrameSDOps
)
387 TFI
->eliminateCallFramePseudoInstr(MF
, *I
->getParent(), I
);
389 // We can't track the call frame size after call frame pseudos have been
390 // eliminated. Set it to zero everywhere to keep MachineVerifier happy.
391 for (MachineBasicBlock
&MBB
: MF
)
392 MBB
.setCallFrameSize(0);
396 /// Compute the sets of entry and return blocks for saving and restoring
397 /// callee-saved registers, and placing prolog and epilog code.
398 void PEI::calculateSaveRestoreBlocks(MachineFunction
&MF
) {
399 const MachineFrameInfo
&MFI
= MF
.getFrameInfo();
401 // Even when we do not change any CSR, we still want to insert the
402 // prologue and epilogue of the function.
403 // So set the save points for those.
405 // Use the points found by shrink-wrapping, if any.
406 if (MFI
.getSavePoint()) {
407 SaveBlocks
.push_back(MFI
.getSavePoint());
408 assert(MFI
.getRestorePoint() && "Both restore and save must be set");
409 MachineBasicBlock
*RestoreBlock
= MFI
.getRestorePoint();
410 // If RestoreBlock does not have any successor and is not a return block
411 // then the end point is unreachable and we do not need to insert any
413 if (!RestoreBlock
->succ_empty() || RestoreBlock
->isReturnBlock())
414 RestoreBlocks
.push_back(RestoreBlock
);
418 // Save refs to entry and return blocks.
419 SaveBlocks
.push_back(&MF
.front());
420 for (MachineBasicBlock
&MBB
: MF
) {
421 if (MBB
.isEHFuncletEntry())
422 SaveBlocks
.push_back(&MBB
);
423 if (MBB
.isReturnBlock())
424 RestoreBlocks
.push_back(&MBB
);
428 static void assignCalleeSavedSpillSlots(MachineFunction
&F
,
429 const BitVector
&SavedRegs
,
430 unsigned &MinCSFrameIndex
,
431 unsigned &MaxCSFrameIndex
) {
432 if (SavedRegs
.empty())
435 const TargetRegisterInfo
*RegInfo
= F
.getSubtarget().getRegisterInfo();
436 const MCPhysReg
*CSRegs
= F
.getRegInfo().getCalleeSavedRegs();
437 BitVector
CSMask(SavedRegs
.size());
439 for (unsigned i
= 0; CSRegs
[i
]; ++i
)
440 CSMask
.set(CSRegs
[i
]);
442 std::vector
<CalleeSavedInfo
> CSI
;
443 for (unsigned i
= 0; CSRegs
[i
]; ++i
) {
444 unsigned Reg
= CSRegs
[i
];
445 if (SavedRegs
.test(Reg
)) {
446 bool SavedSuper
= false;
447 for (const MCPhysReg
&SuperReg
: RegInfo
->superregs(Reg
)) {
448 // Some backends set all aliases for some registers as saved, such as
449 // Mips's $fp, so they appear in SavedRegs but not CSRegs.
450 if (SavedRegs
.test(SuperReg
) && CSMask
.test(SuperReg
)) {
457 CSI
.push_back(CalleeSavedInfo(Reg
));
461 const TargetFrameLowering
*TFI
= F
.getSubtarget().getFrameLowering();
462 MachineFrameInfo
&MFI
= F
.getFrameInfo();
463 if (!TFI
->assignCalleeSavedSpillSlots(F
, RegInfo
, CSI
, MinCSFrameIndex
,
465 // If target doesn't implement this, use generic code.
468 return; // Early exit if no callee saved registers are modified!
470 unsigned NumFixedSpillSlots
;
471 const TargetFrameLowering::SpillSlot
*FixedSpillSlots
=
472 TFI
->getCalleeSavedSpillSlots(NumFixedSpillSlots
);
474 // Now that we know which registers need to be saved and restored, allocate
475 // stack slots for them.
476 for (auto &CS
: CSI
) {
477 // If the target has spilled this register to another register, we don't
478 // need to allocate a stack slot.
479 if (CS
.isSpilledToReg())
482 unsigned Reg
= CS
.getReg();
483 const TargetRegisterClass
*RC
= RegInfo
->getMinimalPhysRegClass(Reg
);
486 if (RegInfo
->hasReservedSpillSlot(F
, Reg
, FrameIdx
)) {
487 CS
.setFrameIdx(FrameIdx
);
491 // Check to see if this physreg must be spilled to a particular stack slot
493 const TargetFrameLowering::SpillSlot
*FixedSlot
= FixedSpillSlots
;
494 while (FixedSlot
!= FixedSpillSlots
+ NumFixedSpillSlots
&&
495 FixedSlot
->Reg
!= Reg
)
498 unsigned Size
= RegInfo
->getSpillSize(*RC
);
499 if (FixedSlot
== FixedSpillSlots
+ NumFixedSpillSlots
) {
500 // Nope, just spill it anywhere convenient.
501 Align Alignment
= RegInfo
->getSpillAlign(*RC
);
502 // We may not be able to satisfy the desired alignment specification of
503 // the TargetRegisterClass if the stack alignment is smaller. Use the
505 Alignment
= std::min(Alignment
, TFI
->getStackAlign());
506 FrameIdx
= MFI
.CreateStackObject(Size
, Alignment
, true);
507 if ((unsigned)FrameIdx
< MinCSFrameIndex
) MinCSFrameIndex
= FrameIdx
;
508 if ((unsigned)FrameIdx
> MaxCSFrameIndex
) MaxCSFrameIndex
= FrameIdx
;
510 // Spill it to the stack where we must.
511 FrameIdx
= MFI
.CreateFixedSpillStackObject(Size
, FixedSlot
->Offset
);
514 CS
.setFrameIdx(FrameIdx
);
518 MFI
.setCalleeSavedInfo(CSI
);
521 /// Helper function to update the liveness information for the callee-saved
523 static void updateLiveness(MachineFunction
&MF
) {
524 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
525 // Visited will contain all the basic blocks that are in the region
526 // where the callee saved registers are alive:
527 // - Anything that is not Save or Restore -> LiveThrough.
529 // - Restore -> LiveOut.
530 // The live-out is not attached to the block, so no need to keep
531 // Restore in this set.
532 SmallPtrSet
<MachineBasicBlock
*, 8> Visited
;
533 SmallVector
<MachineBasicBlock
*, 8> WorkList
;
534 MachineBasicBlock
*Entry
= &MF
.front();
535 MachineBasicBlock
*Save
= MFI
.getSavePoint();
541 WorkList
.push_back(Entry
);
542 Visited
.insert(Entry
);
544 Visited
.insert(Save
);
546 MachineBasicBlock
*Restore
= MFI
.getRestorePoint();
548 // By construction Restore cannot be visited, otherwise it
549 // means there exists a path to Restore that does not go
551 WorkList
.push_back(Restore
);
553 while (!WorkList
.empty()) {
554 const MachineBasicBlock
*CurBB
= WorkList
.pop_back_val();
555 // By construction, the region that is after the save point is
556 // dominated by the Save and post-dominated by the Restore.
557 if (CurBB
== Save
&& Save
!= Restore
)
559 // Enqueue all the successors not already visited.
560 // Those are by construction either before Save or after Restore.
561 for (MachineBasicBlock
*SuccBB
: CurBB
->successors())
562 if (Visited
.insert(SuccBB
).second
)
563 WorkList
.push_back(SuccBB
);
566 const std::vector
<CalleeSavedInfo
> &CSI
= MFI
.getCalleeSavedInfo();
568 MachineRegisterInfo
&MRI
= MF
.getRegInfo();
569 for (const CalleeSavedInfo
&I
: CSI
) {
570 for (MachineBasicBlock
*MBB
: Visited
) {
571 MCPhysReg Reg
= I
.getReg();
572 // Add the callee-saved register as live-in.
573 // It's killed at the spill.
574 if (!MRI
.isReserved(Reg
) && !MBB
->isLiveIn(Reg
))
577 // If callee-saved register is spilled to another register rather than
578 // spilling to stack, the destination register has to be marked as live for
579 // each MBB between the prologue and epilogue so that it is not clobbered
580 // before it is reloaded in the epilogue. The Visited set contains all
581 // blocks outside of the region delimited by prologue/epilogue.
582 if (I
.isSpilledToReg()) {
583 for (MachineBasicBlock
&MBB
: MF
) {
584 if (Visited
.count(&MBB
))
586 MCPhysReg DstReg
= I
.getDstReg();
587 if (!MBB
.isLiveIn(DstReg
))
588 MBB
.addLiveIn(DstReg
);
594 /// Insert spill code for the callee-saved registers used in the function.
595 static void insertCSRSaves(MachineBasicBlock
&SaveBlock
,
596 ArrayRef
<CalleeSavedInfo
> CSI
) {
597 MachineFunction
&MF
= *SaveBlock
.getParent();
598 const TargetInstrInfo
&TII
= *MF
.getSubtarget().getInstrInfo();
599 const TargetFrameLowering
*TFI
= MF
.getSubtarget().getFrameLowering();
600 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
602 MachineBasicBlock::iterator I
= SaveBlock
.begin();
603 if (!TFI
->spillCalleeSavedRegisters(SaveBlock
, I
, CSI
, TRI
)) {
604 for (const CalleeSavedInfo
&CS
: CSI
) {
605 // Insert the spill to the stack frame.
606 unsigned Reg
= CS
.getReg();
608 if (CS
.isSpilledToReg()) {
609 BuildMI(SaveBlock
, I
, DebugLoc(),
610 TII
.get(TargetOpcode::COPY
), CS
.getDstReg())
611 .addReg(Reg
, getKillRegState(true));
613 const TargetRegisterClass
*RC
= TRI
->getMinimalPhysRegClass(Reg
);
614 TII
.storeRegToStackSlot(SaveBlock
, I
, Reg
, true, CS
.getFrameIdx(), RC
,
621 /// Insert restore code for the callee-saved registers used in the function.
622 static void insertCSRRestores(MachineBasicBlock
&RestoreBlock
,
623 std::vector
<CalleeSavedInfo
> &CSI
) {
624 MachineFunction
&MF
= *RestoreBlock
.getParent();
625 const TargetInstrInfo
&TII
= *MF
.getSubtarget().getInstrInfo();
626 const TargetFrameLowering
*TFI
= MF
.getSubtarget().getFrameLowering();
627 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
629 // Restore all registers immediately before the return and any
630 // terminators that precede it.
631 MachineBasicBlock::iterator I
= RestoreBlock
.getFirstTerminator();
633 if (!TFI
->restoreCalleeSavedRegisters(RestoreBlock
, I
, CSI
, TRI
)) {
634 for (const CalleeSavedInfo
&CI
: reverse(CSI
)) {
635 unsigned Reg
= CI
.getReg();
636 if (CI
.isSpilledToReg()) {
637 BuildMI(RestoreBlock
, I
, DebugLoc(), TII
.get(TargetOpcode::COPY
), Reg
)
638 .addReg(CI
.getDstReg(), getKillRegState(true));
640 const TargetRegisterClass
*RC
= TRI
->getMinimalPhysRegClass(Reg
);
641 TII
.loadRegFromStackSlot(RestoreBlock
, I
, Reg
, CI
.getFrameIdx(), RC
,
643 assert(I
!= RestoreBlock
.begin() &&
644 "loadRegFromStackSlot didn't insert any code!");
645 // Insert in reverse order. loadRegFromStackSlot can insert
646 // multiple instructions.
652 void PEI::spillCalleeSavedRegs(MachineFunction
&MF
) {
653 // We can't list this requirement in getRequiredProperties because some
654 // targets (WebAssembly) use virtual registers past this point, and the pass
655 // pipeline is set up without giving the passes a chance to look at the
657 // FIXME: Find a way to express this in getRequiredProperties.
658 assert(MF
.getProperties().hasProperty(
659 MachineFunctionProperties::Property::NoVRegs
));
661 const Function
&F
= MF
.getFunction();
662 const TargetFrameLowering
*TFI
= MF
.getSubtarget().getFrameLowering();
663 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
664 MinCSFrameIndex
= std::numeric_limits
<unsigned>::max();
667 // Determine which of the registers in the callee save list should be saved.
669 TFI
->determineCalleeSaves(MF
, SavedRegs
, RS
);
671 // Assign stack slots for any callee-saved registers that must be spilled.
672 assignCalleeSavedSpillSlots(MF
, SavedRegs
, MinCSFrameIndex
, MaxCSFrameIndex
);
674 // Add the code to save and restore the callee saved registers.
675 if (!F
.hasFnAttribute(Attribute::Naked
)) {
676 MFI
.setCalleeSavedInfoValid(true);
678 std::vector
<CalleeSavedInfo
> &CSI
= MFI
.getCalleeSavedInfo();
681 NumLeafFuncWithSpills
++;
683 for (MachineBasicBlock
*SaveBlock
: SaveBlocks
)
684 insertCSRSaves(*SaveBlock
, CSI
);
686 // Update the live-in information of all the blocks up to the save point.
689 for (MachineBasicBlock
*RestoreBlock
: RestoreBlocks
)
690 insertCSRRestores(*RestoreBlock
, CSI
);
695 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
696 static inline void AdjustStackOffset(MachineFrameInfo
&MFI
, int FrameIdx
,
697 bool StackGrowsDown
, int64_t &Offset
,
699 // If the stack grows down, add the object size to find the lowest address.
701 Offset
+= MFI
.getObjectSize(FrameIdx
);
703 Align Alignment
= MFI
.getObjectAlign(FrameIdx
);
705 // If the alignment of this object is greater than that of the stack, then
706 // increase the stack alignment to match.
707 MaxAlign
= std::max(MaxAlign
, Alignment
);
709 // Adjust to alignment boundary.
710 Offset
= alignTo(Offset
, Alignment
);
712 if (StackGrowsDown
) {
713 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx
<< ") at SP[" << -Offset
715 MFI
.setObjectOffset(FrameIdx
, -Offset
); // Set the computed offset
717 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx
<< ") at SP[" << Offset
719 MFI
.setObjectOffset(FrameIdx
, Offset
);
720 Offset
+= MFI
.getObjectSize(FrameIdx
);
724 /// Compute which bytes of fixed and callee-save stack area are unused and keep
725 /// track of them in StackBytesFree.
727 computeFreeStackSlots(MachineFrameInfo
&MFI
, bool StackGrowsDown
,
728 unsigned MinCSFrameIndex
, unsigned MaxCSFrameIndex
,
729 int64_t FixedCSEnd
, BitVector
&StackBytesFree
) {
730 // Avoid undefined int64_t -> int conversion below in extreme case.
731 if (FixedCSEnd
> std::numeric_limits
<int>::max())
734 StackBytesFree
.resize(FixedCSEnd
, true);
736 SmallVector
<int, 16> AllocatedFrameSlots
;
737 // Add fixed objects.
738 for (int i
= MFI
.getObjectIndexBegin(); i
!= 0; ++i
)
739 // StackSlot scavenging is only implemented for the default stack.
740 if (MFI
.getStackID(i
) == TargetStackID::Default
)
741 AllocatedFrameSlots
.push_back(i
);
742 // Add callee-save objects if there are any.
743 if (MinCSFrameIndex
<= MaxCSFrameIndex
) {
744 for (int i
= MinCSFrameIndex
; i
<= (int)MaxCSFrameIndex
; ++i
)
745 if (MFI
.getStackID(i
) == TargetStackID::Default
)
746 AllocatedFrameSlots
.push_back(i
);
749 for (int i
: AllocatedFrameSlots
) {
750 // These are converted from int64_t, but they should always fit in int
751 // because of the FixedCSEnd check above.
752 int ObjOffset
= MFI
.getObjectOffset(i
);
753 int ObjSize
= MFI
.getObjectSize(i
);
754 int ObjStart
, ObjEnd
;
755 if (StackGrowsDown
) {
756 // ObjOffset is negative when StackGrowsDown is true.
757 ObjStart
= -ObjOffset
- ObjSize
;
760 ObjStart
= ObjOffset
;
761 ObjEnd
= ObjOffset
+ ObjSize
;
763 // Ignore fixed holes that are in the previous stack frame.
765 StackBytesFree
.reset(ObjStart
, ObjEnd
);
769 /// Assign frame object to an unused portion of the stack in the fixed stack
770 /// object range. Return true if the allocation was successful.
771 static inline bool scavengeStackSlot(MachineFrameInfo
&MFI
, int FrameIdx
,
772 bool StackGrowsDown
, Align MaxAlign
,
773 BitVector
&StackBytesFree
) {
774 if (MFI
.isVariableSizedObjectIndex(FrameIdx
))
777 if (StackBytesFree
.none()) {
778 // clear it to speed up later scavengeStackSlot calls to
779 // StackBytesFree.none()
780 StackBytesFree
.clear();
784 Align ObjAlign
= MFI
.getObjectAlign(FrameIdx
);
785 if (ObjAlign
> MaxAlign
)
788 int64_t ObjSize
= MFI
.getObjectSize(FrameIdx
);
790 for (FreeStart
= StackBytesFree
.find_first(); FreeStart
!= -1;
791 FreeStart
= StackBytesFree
.find_next(FreeStart
)) {
793 // Check that free space has suitable alignment.
794 unsigned ObjStart
= StackGrowsDown
? FreeStart
+ ObjSize
: FreeStart
;
795 if (alignTo(ObjStart
, ObjAlign
) != ObjStart
)
798 if (FreeStart
+ ObjSize
> StackBytesFree
.size())
801 bool AllBytesFree
= true;
802 for (unsigned Byte
= 0; Byte
< ObjSize
; ++Byte
)
803 if (!StackBytesFree
.test(FreeStart
+ Byte
)) {
804 AllBytesFree
= false;
814 if (StackGrowsDown
) {
815 int ObjStart
= -(FreeStart
+ ObjSize
);
816 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx
<< ") scavenged at SP["
817 << ObjStart
<< "]\n");
818 MFI
.setObjectOffset(FrameIdx
, ObjStart
);
820 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx
<< ") scavenged at SP["
821 << FreeStart
<< "]\n");
822 MFI
.setObjectOffset(FrameIdx
, FreeStart
);
825 StackBytesFree
.reset(FreeStart
, FreeStart
+ ObjSize
);
829 /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
830 /// those required to be close to the Stack Protector) to stack offsets.
831 static void AssignProtectedObjSet(const StackObjSet
&UnassignedObjs
,
832 SmallSet
<int, 16> &ProtectedObjs
,
833 MachineFrameInfo
&MFI
, bool StackGrowsDown
,
834 int64_t &Offset
, Align
&MaxAlign
) {
836 for (int i
: UnassignedObjs
) {
837 AdjustStackOffset(MFI
, i
, StackGrowsDown
, Offset
, MaxAlign
);
838 ProtectedObjs
.insert(i
);
842 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
843 /// abstract stack objects.
844 void PEI::calculateFrameObjectOffsets(MachineFunction
&MF
) {
845 const TargetFrameLowering
&TFI
= *MF
.getSubtarget().getFrameLowering();
847 bool StackGrowsDown
=
848 TFI
.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown
;
850 // Loop over all of the stack objects, assigning sequential addresses...
851 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
853 // Start at the beginning of the local area.
854 // The Offset is the distance from the stack top in the direction
855 // of stack growth -- so it's always nonnegative.
856 int LocalAreaOffset
= TFI
.getOffsetOfLocalArea();
858 LocalAreaOffset
= -LocalAreaOffset
;
859 assert(LocalAreaOffset
>= 0
860 && "Local area offset should be in direction of stack growth");
861 int64_t Offset
= LocalAreaOffset
;
863 #ifdef EXPENSIVE_CHECKS
864 for (unsigned i
= 0, e
= MFI
.getObjectIndexEnd(); i
!= e
; ++i
)
865 if (!MFI
.isDeadObjectIndex(i
) &&
866 MFI
.getStackID(i
) == TargetStackID::Default
)
867 assert(MFI
.getObjectAlign(i
) <= MFI
.getMaxAlign() &&
868 "MaxAlignment is invalid");
871 // If there are fixed sized objects that are preallocated in the local area,
872 // non-fixed objects can't be allocated right at the start of local area.
873 // Adjust 'Offset' to point to the end of last fixed sized preallocated
875 for (int i
= MFI
.getObjectIndexBegin(); i
!= 0; ++i
) {
876 // Only allocate objects on the default stack.
877 if (MFI
.getStackID(i
) != TargetStackID::Default
)
881 if (StackGrowsDown
) {
882 // The maximum distance from the stack pointer is at lower address of
883 // the object -- which is given by offset. For down growing stack
884 // the offset is negative, so we negate the offset to get the distance.
885 FixedOff
= -MFI
.getObjectOffset(i
);
887 // The maximum distance from the start pointer is at the upper
888 // address of the object.
889 FixedOff
= MFI
.getObjectOffset(i
) + MFI
.getObjectSize(i
);
891 if (FixedOff
> Offset
) Offset
= FixedOff
;
894 Align MaxAlign
= MFI
.getMaxAlign();
895 // First assign frame offsets to stack objects that are used to spill
896 // callee saved registers.
897 if (MaxCSFrameIndex
>= MinCSFrameIndex
) {
898 for (unsigned i
= 0; i
<= MaxCSFrameIndex
- MinCSFrameIndex
; ++i
) {
899 unsigned FrameIndex
=
900 StackGrowsDown
? MinCSFrameIndex
+ i
: MaxCSFrameIndex
- i
;
902 // Only allocate objects on the default stack.
903 if (MFI
.getStackID(FrameIndex
) != TargetStackID::Default
)
906 // TODO: should this just be if (MFI.isDeadObjectIndex(FrameIndex))
907 if (!StackGrowsDown
&& MFI
.isDeadObjectIndex(FrameIndex
))
910 AdjustStackOffset(MFI
, FrameIndex
, StackGrowsDown
, Offset
, MaxAlign
);
914 assert(MaxAlign
== MFI
.getMaxAlign() &&
915 "MFI.getMaxAlign should already account for all callee-saved "
916 "registers without a fixed stack slot");
918 // FixedCSEnd is the stack offset to the end of the fixed and callee-save
920 int64_t FixedCSEnd
= Offset
;
922 // Make sure the special register scavenging spill slot is closest to the
923 // incoming stack pointer if a frame pointer is required and is closer
924 // to the incoming rather than the final stack pointer.
925 const TargetRegisterInfo
*RegInfo
= MF
.getSubtarget().getRegisterInfo();
926 bool EarlyScavengingSlots
= TFI
.allocateScavengingFrameIndexesNearIncomingSP(MF
);
927 if (RS
&& EarlyScavengingSlots
) {
928 SmallVector
<int, 2> SFIs
;
929 RS
->getScavengingFrameIndices(SFIs
);
931 AdjustStackOffset(MFI
, SFI
, StackGrowsDown
, Offset
, MaxAlign
);
934 // FIXME: Once this is working, then enable flag will change to a target
935 // check for whether the frame is large enough to want to use virtual
936 // frame index registers. Functions which don't want/need this optimization
937 // will continue to use the existing code path.
938 if (MFI
.getUseLocalStackAllocationBlock()) {
939 Align Alignment
= MFI
.getLocalFrameMaxAlign();
941 // Adjust to alignment boundary.
942 Offset
= alignTo(Offset
, Alignment
);
944 LLVM_DEBUG(dbgs() << "Local frame base offset: " << Offset
<< "\n");
946 // Resolve offsets for objects in the local block.
947 for (unsigned i
= 0, e
= MFI
.getLocalFrameObjectCount(); i
!= e
; ++i
) {
948 std::pair
<int, int64_t> Entry
= MFI
.getLocalFrameObjectMap(i
);
949 int64_t FIOffset
= (StackGrowsDown
? -Offset
: Offset
) + Entry
.second
;
950 LLVM_DEBUG(dbgs() << "alloc FI(" << Entry
.first
<< ") at SP[" << FIOffset
952 MFI
.setObjectOffset(Entry
.first
, FIOffset
);
954 // Allocate the local block
955 Offset
+= MFI
.getLocalFrameSize();
957 MaxAlign
= std::max(Alignment
, MaxAlign
);
960 // Retrieve the Exception Handler registration node.
961 int EHRegNodeFrameIndex
= std::numeric_limits
<int>::max();
962 if (const WinEHFuncInfo
*FuncInfo
= MF
.getWinEHFuncInfo())
963 EHRegNodeFrameIndex
= FuncInfo
->EHRegNodeFrameIndex
;
965 // Make sure that the stack protector comes before the local variables on the
967 SmallSet
<int, 16> ProtectedObjs
;
968 if (MFI
.hasStackProtectorIndex()) {
969 int StackProtectorFI
= MFI
.getStackProtectorIndex();
970 StackObjSet LargeArrayObjs
;
971 StackObjSet SmallArrayObjs
;
972 StackObjSet AddrOfObjs
;
974 // If we need a stack protector, we need to make sure that
975 // LocalStackSlotPass didn't already allocate a slot for it.
976 // If we are told to use the LocalStackAllocationBlock, the stack protector
977 // is expected to be already pre-allocated.
978 if (MFI
.getStackID(StackProtectorFI
) != TargetStackID::Default
) {
979 // If the stack protector isn't on the default stack then it's up to the
980 // target to set the stack offset.
981 assert(MFI
.getObjectOffset(StackProtectorFI
) != 0 &&
982 "Offset of stack protector on non-default stack expected to be "
984 assert(!MFI
.isObjectPreAllocated(MFI
.getStackProtectorIndex()) &&
985 "Stack protector on non-default stack expected to not be "
986 "pre-allocated by LocalStackSlotPass.");
987 } else if (!MFI
.getUseLocalStackAllocationBlock()) {
988 AdjustStackOffset(MFI
, StackProtectorFI
, StackGrowsDown
, Offset
,
990 } else if (!MFI
.isObjectPreAllocated(MFI
.getStackProtectorIndex())) {
992 "Stack protector not pre-allocated by LocalStackSlotPass.");
995 // Assign large stack objects first.
996 for (unsigned i
= 0, e
= MFI
.getObjectIndexEnd(); i
!= e
; ++i
) {
997 if (MFI
.isObjectPreAllocated(i
) && MFI
.getUseLocalStackAllocationBlock())
999 if (i
>= MinCSFrameIndex
&& i
<= MaxCSFrameIndex
)
1001 if (RS
&& RS
->isScavengingFrameIndex((int)i
))
1003 if (MFI
.isDeadObjectIndex(i
))
1005 if (StackProtectorFI
== (int)i
|| EHRegNodeFrameIndex
== (int)i
)
1007 // Only allocate objects on the default stack.
1008 if (MFI
.getStackID(i
) != TargetStackID::Default
)
1011 switch (MFI
.getObjectSSPLayout(i
)) {
1012 case MachineFrameInfo::SSPLK_None
:
1014 case MachineFrameInfo::SSPLK_SmallArray
:
1015 SmallArrayObjs
.insert(i
);
1017 case MachineFrameInfo::SSPLK_AddrOf
:
1018 AddrOfObjs
.insert(i
);
1020 case MachineFrameInfo::SSPLK_LargeArray
:
1021 LargeArrayObjs
.insert(i
);
1024 llvm_unreachable("Unexpected SSPLayoutKind.");
1027 // We expect **all** the protected stack objects to be pre-allocated by
1028 // LocalStackSlotPass. If it turns out that PEI still has to allocate some
1029 // of them, we may end up messing up the expected order of the objects.
1030 if (MFI
.getUseLocalStackAllocationBlock() &&
1031 !(LargeArrayObjs
.empty() && SmallArrayObjs
.empty() &&
1032 AddrOfObjs
.empty()))
1033 llvm_unreachable("Found protected stack objects not pre-allocated by "
1034 "LocalStackSlotPass.");
1036 AssignProtectedObjSet(LargeArrayObjs
, ProtectedObjs
, MFI
, StackGrowsDown
,
1038 AssignProtectedObjSet(SmallArrayObjs
, ProtectedObjs
, MFI
, StackGrowsDown
,
1040 AssignProtectedObjSet(AddrOfObjs
, ProtectedObjs
, MFI
, StackGrowsDown
,
1044 SmallVector
<int, 8> ObjectsToAllocate
;
1046 // Then prepare to assign frame offsets to stack objects that are not used to
1047 // spill callee saved registers.
1048 for (unsigned i
= 0, e
= MFI
.getObjectIndexEnd(); i
!= e
; ++i
) {
1049 if (MFI
.isObjectPreAllocated(i
) && MFI
.getUseLocalStackAllocationBlock())
1051 if (i
>= MinCSFrameIndex
&& i
<= MaxCSFrameIndex
)
1053 if (RS
&& RS
->isScavengingFrameIndex((int)i
))
1055 if (MFI
.isDeadObjectIndex(i
))
1057 if (MFI
.getStackProtectorIndex() == (int)i
|| EHRegNodeFrameIndex
== (int)i
)
1059 if (ProtectedObjs
.count(i
))
1061 // Only allocate objects on the default stack.
1062 if (MFI
.getStackID(i
) != TargetStackID::Default
)
1065 // Add the objects that we need to allocate to our working set.
1066 ObjectsToAllocate
.push_back(i
);
1069 // Allocate the EH registration node first if one is present.
1070 if (EHRegNodeFrameIndex
!= std::numeric_limits
<int>::max())
1071 AdjustStackOffset(MFI
, EHRegNodeFrameIndex
, StackGrowsDown
, Offset
,
1074 // Give the targets a chance to order the objects the way they like it.
1075 if (MF
.getTarget().getOptLevel() != CodeGenOptLevel::None
&&
1076 MF
.getTarget().Options
.StackSymbolOrdering
)
1077 TFI
.orderFrameObjects(MF
, ObjectsToAllocate
);
1079 // Keep track of which bytes in the fixed and callee-save range are used so we
1080 // can use the holes when allocating later stack objects. Only do this if
1081 // stack protector isn't being used and the target requests it and we're
1083 BitVector StackBytesFree
;
1084 if (!ObjectsToAllocate
.empty() &&
1085 MF
.getTarget().getOptLevel() != CodeGenOptLevel::None
&&
1086 MFI
.getStackProtectorIndex() < 0 && TFI
.enableStackSlotScavenging(MF
))
1087 computeFreeStackSlots(MFI
, StackGrowsDown
, MinCSFrameIndex
, MaxCSFrameIndex
,
1088 FixedCSEnd
, StackBytesFree
);
1090 // Now walk the objects and actually assign base offsets to them.
1091 for (auto &Object
: ObjectsToAllocate
)
1092 if (!scavengeStackSlot(MFI
, Object
, StackGrowsDown
, MaxAlign
,
1094 AdjustStackOffset(MFI
, Object
, StackGrowsDown
, Offset
, MaxAlign
);
1096 // Make sure the special register scavenging spill slot is closest to the
1098 if (RS
&& !EarlyScavengingSlots
) {
1099 SmallVector
<int, 2> SFIs
;
1100 RS
->getScavengingFrameIndices(SFIs
);
1101 for (int SFI
: SFIs
)
1102 AdjustStackOffset(MFI
, SFI
, StackGrowsDown
, Offset
, MaxAlign
);
1105 if (!TFI
.targetHandlesStackFrameRounding()) {
1106 // If we have reserved argument space for call sites in the function
1107 // immediately on entry to the current function, count it as part of the
1108 // overall stack size.
1109 if (MFI
.adjustsStack() && TFI
.hasReservedCallFrame(MF
))
1110 Offset
+= MFI
.getMaxCallFrameSize();
1112 // Round up the size to a multiple of the alignment. If the function has
1113 // any calls or alloca's, align to the target's StackAlignment value to
1114 // ensure that the callee's frame or the alloca data is suitably aligned;
1115 // otherwise, for leaf functions, align to the TransientStackAlignment
1118 if (MFI
.adjustsStack() || MFI
.hasVarSizedObjects() ||
1119 (RegInfo
->hasStackRealignment(MF
) && MFI
.getObjectIndexEnd() != 0))
1120 StackAlign
= TFI
.getStackAlign();
1122 StackAlign
= TFI
.getTransientStackAlign();
1124 // If the frame pointer is eliminated, all frame offsets will be relative to
1125 // SP not FP. Align to MaxAlign so this works.
1126 StackAlign
= std::max(StackAlign
, MaxAlign
);
1127 int64_t OffsetBeforeAlignment
= Offset
;
1128 Offset
= alignTo(Offset
, StackAlign
);
1130 // If we have increased the offset to fulfill the alignment constrants,
1131 // then the scavenging spill slots may become harder to reach from the
1132 // stack pointer, float them so they stay close.
1133 if (StackGrowsDown
&& OffsetBeforeAlignment
!= Offset
&& RS
&&
1134 !EarlyScavengingSlots
) {
1135 SmallVector
<int, 2> SFIs
;
1136 RS
->getScavengingFrameIndices(SFIs
);
1137 LLVM_DEBUG(if (!SFIs
.empty()) llvm::dbgs()
1138 << "Adjusting emergency spill slots!\n";);
1139 int64_t Delta
= Offset
- OffsetBeforeAlignment
;
1140 for (int SFI
: SFIs
) {
1141 LLVM_DEBUG(llvm::dbgs()
1142 << "Adjusting offset of emergency spill slot #" << SFI
1143 << " from " << MFI
.getObjectOffset(SFI
););
1144 MFI
.setObjectOffset(SFI
, MFI
.getObjectOffset(SFI
) - Delta
);
1145 LLVM_DEBUG(llvm::dbgs() << " to " << MFI
.getObjectOffset(SFI
) << "\n";);
1150 // Update frame info to pretend that this is part of the stack...
1151 int64_t StackSize
= Offset
- LocalAreaOffset
;
1152 MFI
.setStackSize(StackSize
);
1153 NumBytesStackSpace
+= StackSize
;
1156 /// insertPrologEpilogCode - Scan the function for modified callee saved
1157 /// registers, insert spill code for these callee saved registers, then add
1158 /// prolog and epilog code to the function.
1159 void PEI::insertPrologEpilogCode(MachineFunction
&MF
) {
1160 const TargetFrameLowering
&TFI
= *MF
.getSubtarget().getFrameLowering();
1162 // Add prologue to the function...
1163 for (MachineBasicBlock
*SaveBlock
: SaveBlocks
)
1164 TFI
.emitPrologue(MF
, *SaveBlock
);
1166 // Add epilogue to restore the callee-save registers in each exiting block.
1167 for (MachineBasicBlock
*RestoreBlock
: RestoreBlocks
)
1168 TFI
.emitEpilogue(MF
, *RestoreBlock
);
1170 // Zero call used registers before restoring callee-saved registers.
1171 insertZeroCallUsedRegs(MF
);
1173 for (MachineBasicBlock
*SaveBlock
: SaveBlocks
)
1174 TFI
.inlineStackProbe(MF
, *SaveBlock
);
1176 // Emit additional code that is required to support segmented stacks, if
1177 // we've been asked for it. This, when linked with a runtime with support
1178 // for segmented stacks (libgcc is one), will result in allocating stack
1179 // space in small chunks instead of one large contiguous block.
1180 if (MF
.shouldSplitStack()) {
1181 for (MachineBasicBlock
*SaveBlock
: SaveBlocks
)
1182 TFI
.adjustForSegmentedStacks(MF
, *SaveBlock
);
1185 // Emit additional code that is required to explicitly handle the stack in
1186 // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
1187 // approach is rather similar to that of Segmented Stacks, but it uses a
1188 // different conditional check and another BIF for allocating more stack
1190 if (MF
.getFunction().getCallingConv() == CallingConv::HiPE
)
1191 for (MachineBasicBlock
*SaveBlock
: SaveBlocks
)
1192 TFI
.adjustForHiPEPrologue(MF
, *SaveBlock
);
1195 /// insertZeroCallUsedRegs - Zero out call used registers.
1196 void PEI::insertZeroCallUsedRegs(MachineFunction
&MF
) {
1197 const Function
&F
= MF
.getFunction();
1199 if (!F
.hasFnAttribute("zero-call-used-regs"))
1202 using namespace ZeroCallUsedRegs
;
1204 ZeroCallUsedRegsKind ZeroRegsKind
=
1205 StringSwitch
<ZeroCallUsedRegsKind
>(
1206 F
.getFnAttribute("zero-call-used-regs").getValueAsString())
1207 .Case("skip", ZeroCallUsedRegsKind::Skip
)
1208 .Case("used-gpr-arg", ZeroCallUsedRegsKind::UsedGPRArg
)
1209 .Case("used-gpr", ZeroCallUsedRegsKind::UsedGPR
)
1210 .Case("used-arg", ZeroCallUsedRegsKind::UsedArg
)
1211 .Case("used", ZeroCallUsedRegsKind::Used
)
1212 .Case("all-gpr-arg", ZeroCallUsedRegsKind::AllGPRArg
)
1213 .Case("all-gpr", ZeroCallUsedRegsKind::AllGPR
)
1214 .Case("all-arg", ZeroCallUsedRegsKind::AllArg
)
1215 .Case("all", ZeroCallUsedRegsKind::All
);
1217 if (ZeroRegsKind
== ZeroCallUsedRegsKind::Skip
)
1220 const bool OnlyGPR
= static_cast<unsigned>(ZeroRegsKind
) & ONLY_GPR
;
1221 const bool OnlyUsed
= static_cast<unsigned>(ZeroRegsKind
) & ONLY_USED
;
1222 const bool OnlyArg
= static_cast<unsigned>(ZeroRegsKind
) & ONLY_ARG
;
1224 const TargetRegisterInfo
&TRI
= *MF
.getSubtarget().getRegisterInfo();
1225 const BitVector
AllocatableSet(TRI
.getAllocatableSet(MF
));
1227 // Mark all used registers.
1228 BitVector
UsedRegs(TRI
.getNumRegs());
1230 for (const MachineBasicBlock
&MBB
: MF
)
1231 for (const MachineInstr
&MI
: MBB
) {
1232 // skip debug instructions
1233 if (MI
.isDebugInstr())
1236 for (const MachineOperand
&MO
: MI
.operands()) {
1240 MCRegister Reg
= MO
.getReg();
1241 if (AllocatableSet
[Reg
] && !MO
.isImplicit() &&
1242 (MO
.isDef() || MO
.isUse()))
1247 // Get a list of registers that are used.
1248 BitVector
LiveIns(TRI
.getNumRegs());
1249 for (const MachineBasicBlock::RegisterMaskPair
&LI
: MF
.front().liveins())
1250 LiveIns
.set(LI
.PhysReg
);
1252 BitVector
RegsToZero(TRI
.getNumRegs());
1253 for (MCRegister Reg
: AllocatableSet
.set_bits()) {
1254 // Skip over fixed registers.
1255 if (TRI
.isFixedRegister(MF
, Reg
))
1258 // Want only general purpose registers.
1259 if (OnlyGPR
&& !TRI
.isGeneralPurposeRegister(MF
, Reg
))
1262 // Want only used registers.
1263 if (OnlyUsed
&& !UsedRegs
[Reg
])
1266 // Want only registers used for arguments.
1271 } else if (!TRI
.isArgumentRegister(MF
, Reg
)) {
1276 RegsToZero
.set(Reg
);
1279 // Don't clear registers that are live when leaving the function.
1280 for (const MachineBasicBlock
&MBB
: MF
)
1281 for (const MachineInstr
&MI
: MBB
.terminators()) {
1285 for (const auto &MO
: MI
.operands()) {
1289 MCRegister Reg
= MO
.getReg();
1293 // This picks up sibling registers (e.q. %al -> %ah).
1294 for (MCRegUnit Unit
: TRI
.regunits(Reg
))
1295 RegsToZero
.reset(Unit
);
1297 for (MCPhysReg SReg
: TRI
.sub_and_superregs_inclusive(Reg
))
1298 RegsToZero
.reset(SReg
);
1302 // Don't need to clear registers that are used/clobbered by terminating
1304 for (const MachineBasicBlock
&MBB
: MF
) {
1305 if (!MBB
.isReturnBlock())
1308 MachineBasicBlock::const_iterator MBBI
= MBB
.getFirstTerminator();
1309 for (MachineBasicBlock::const_iterator I
= MBBI
, E
= MBB
.end(); I
!= E
;
1311 for (const MachineOperand
&MO
: I
->operands()) {
1315 MCRegister Reg
= MO
.getReg();
1319 for (const MCPhysReg Reg
: TRI
.sub_and_superregs_inclusive(Reg
))
1320 RegsToZero
.reset(Reg
);
1325 // Don't clear registers that must be preserved.
1326 for (const MCPhysReg
*CSRegs
= TRI
.getCalleeSavedRegs(&MF
);
1327 MCPhysReg CSReg
= *CSRegs
; ++CSRegs
)
1328 for (MCRegister Reg
: TRI
.sub_and_superregs_inclusive(CSReg
))
1329 RegsToZero
.reset(Reg
);
1331 const TargetFrameLowering
&TFI
= *MF
.getSubtarget().getFrameLowering();
1332 for (MachineBasicBlock
&MBB
: MF
)
1333 if (MBB
.isReturnBlock())
1334 TFI
.emitZeroCallUsedRegs(RegsToZero
, MBB
);
1337 /// Replace all FrameIndex operands with physical register references and actual
1339 void PEI::replaceFrameIndicesBackward(MachineFunction
&MF
) {
1340 const TargetFrameLowering
&TFI
= *MF
.getSubtarget().getFrameLowering();
1342 for (auto &MBB
: MF
) {
1344 if (!MBB
.succ_empty()) {
1345 // Get the SP adjustment for the end of MBB from the start of any of its
1346 // successors. They should all be the same.
1347 assert(all_of(MBB
.successors(), [&MBB
](const MachineBasicBlock
*Succ
) {
1348 return Succ
->getCallFrameSize() ==
1349 (*MBB
.succ_begin())->getCallFrameSize();
1351 const MachineBasicBlock
&FirstSucc
= **MBB
.succ_begin();
1352 SPAdj
= TFI
.alignSPAdjust(FirstSucc
.getCallFrameSize());
1353 if (TFI
.getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp
)
1357 replaceFrameIndicesBackward(&MBB
, MF
, SPAdj
);
1359 // We can't track the call frame size after call frame pseudos have been
1360 // eliminated. Set it to zero everywhere to keep MachineVerifier happy.
1361 MBB
.setCallFrameSize(0);
1365 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
1366 /// register references and actual offsets.
1367 void PEI::replaceFrameIndices(MachineFunction
&MF
) {
1368 const TargetFrameLowering
&TFI
= *MF
.getSubtarget().getFrameLowering();
1370 for (auto &MBB
: MF
) {
1371 int SPAdj
= TFI
.alignSPAdjust(MBB
.getCallFrameSize());
1372 if (TFI
.getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp
)
1375 replaceFrameIndices(&MBB
, MF
, SPAdj
);
1377 // We can't track the call frame size after call frame pseudos have been
1378 // eliminated. Set it to zero everywhere to keep MachineVerifier happy.
1379 MBB
.setCallFrameSize(0);
1383 bool PEI::replaceFrameIndexDebugInstr(MachineFunction
&MF
, MachineInstr
&MI
,
1384 unsigned OpIdx
, int SPAdj
) {
1385 const TargetFrameLowering
*TFI
= MF
.getSubtarget().getFrameLowering();
1386 const TargetRegisterInfo
&TRI
= *MF
.getSubtarget().getRegisterInfo();
1387 if (MI
.isDebugValue()) {
1389 MachineOperand
&Op
= MI
.getOperand(OpIdx
);
1390 assert(MI
.isDebugOperand(&Op
) &&
1391 "Frame indices can only appear as a debug operand in a DBG_VALUE*"
1392 " machine instruction");
1394 unsigned FrameIdx
= Op
.getIndex();
1395 unsigned Size
= MF
.getFrameInfo().getObjectSize(FrameIdx
);
1397 StackOffset Offset
= TFI
->getFrameIndexReference(MF
, FrameIdx
, Reg
);
1398 Op
.ChangeToRegister(Reg
, false /*isDef*/);
1400 const DIExpression
*DIExpr
= MI
.getDebugExpression();
1402 // If we have a direct DBG_VALUE, and its location expression isn't
1403 // currently complex, then adding an offset will morph it into a
1404 // complex location that is interpreted as being a memory address.
1405 // This changes a pointer-valued variable to dereference that pointer,
1406 // which is incorrect. Fix by adding DW_OP_stack_value.
1408 if (MI
.isNonListDebugValue()) {
1409 unsigned PrependFlags
= DIExpression::ApplyOffset
;
1410 if (!MI
.isIndirectDebugValue() && !DIExpr
->isComplex())
1411 PrependFlags
|= DIExpression::StackValue
;
1413 // If we have DBG_VALUE that is indirect and has a Implicit location
1414 // expression need to insert a deref before prepending a Memory
1415 // location expression. Also after doing this we change the DBG_VALUE
1417 if (MI
.isIndirectDebugValue() && DIExpr
->isImplicit()) {
1418 SmallVector
<uint64_t, 2> Ops
= {dwarf::DW_OP_deref_size
, Size
};
1419 bool WithStackValue
= true;
1420 DIExpr
= DIExpression::prependOpcodes(DIExpr
, Ops
, WithStackValue
);
1421 // Make the DBG_VALUE direct.
1422 MI
.getDebugOffset().ChangeToRegister(0, false);
1424 DIExpr
= TRI
.prependOffsetExpression(DIExpr
, PrependFlags
, Offset
);
1426 // The debug operand at DebugOpIndex was a frame index at offset
1427 // `Offset`; now the operand has been replaced with the frame
1428 // register, we must add Offset with `register x, plus Offset`.
1429 unsigned DebugOpIndex
= MI
.getDebugOperandIndex(&Op
);
1430 SmallVector
<uint64_t, 3> Ops
;
1431 TRI
.getOffsetOpcodes(Offset
, Ops
);
1432 DIExpr
= DIExpression::appendOpsToArg(DIExpr
, Ops
, DebugOpIndex
);
1434 MI
.getDebugExpressionOp().setMetadata(DIExpr
);
1438 if (MI
.isDebugPHI()) {
1439 // Allow stack ref to continue onwards.
1443 // TODO: This code should be commoned with the code for
1444 // PATCHPOINT. There's no good reason for the difference in
1445 // implementation other than historical accident. The only
1446 // remaining difference is the unconditional use of the stack
1447 // pointer as the base register.
1448 if (MI
.getOpcode() == TargetOpcode::STATEPOINT
) {
1449 assert((!MI
.isDebugValue() || OpIdx
== 0) &&
1450 "Frame indices can only appear as the first operand of a "
1451 "DBG_VALUE machine instruction");
1453 MachineOperand
&Offset
= MI
.getOperand(OpIdx
+ 1);
1454 StackOffset refOffset
= TFI
->getFrameIndexReferencePreferSP(
1455 MF
, MI
.getOperand(OpIdx
).getIndex(), Reg
, /*IgnoreSPUpdates*/ false);
1456 assert(!refOffset
.getScalable() &&
1457 "Frame offsets with a scalable component are not supported");
1458 Offset
.setImm(Offset
.getImm() + refOffset
.getFixed() + SPAdj
);
1459 MI
.getOperand(OpIdx
).ChangeToRegister(Reg
, false /*isDef*/);
1465 void PEI::replaceFrameIndicesBackward(MachineBasicBlock
*BB
,
1466 MachineFunction
&MF
, int &SPAdj
) {
1467 assert(MF
.getSubtarget().getRegisterInfo() &&
1468 "getRegisterInfo() must be implemented!");
1470 const TargetInstrInfo
&TII
= *MF
.getSubtarget().getInstrInfo();
1471 const TargetRegisterInfo
&TRI
= *MF
.getSubtarget().getRegisterInfo();
1472 const TargetFrameLowering
&TFI
= *MF
.getSubtarget().getFrameLowering();
1474 RegScavenger
*LocalRS
= FrameIndexEliminationScavenging
? RS
: nullptr;
1476 LocalRS
->enterBasicBlockEnd(*BB
);
1478 for (MachineBasicBlock::iterator I
= BB
->end(); I
!= BB
->begin();) {
1479 MachineInstr
&MI
= *std::prev(I
);
1481 if (TII
.isFrameInstr(MI
)) {
1482 SPAdj
-= TII
.getSPAdjust(MI
);
1483 TFI
.eliminateCallFramePseudoInstr(MF
, *BB
, &MI
);
1487 // Step backwards to get the liveness state at (immedately after) MI.
1489 LocalRS
->backward(I
);
1491 bool RemovedMI
= false;
1492 for (const auto &[Idx
, Op
] : enumerate(MI
.operands())) {
1496 if (replaceFrameIndexDebugInstr(MF
, MI
, Idx
, SPAdj
))
1499 // Eliminate this FrameIndex operand.
1500 RemovedMI
= TRI
.eliminateFrameIndex(MI
, SPAdj
, Idx
, LocalRS
);
1510 void PEI::replaceFrameIndices(MachineBasicBlock
*BB
, MachineFunction
&MF
,
1512 assert(MF
.getSubtarget().getRegisterInfo() &&
1513 "getRegisterInfo() must be implemented!");
1514 const TargetInstrInfo
&TII
= *MF
.getSubtarget().getInstrInfo();
1515 const TargetRegisterInfo
&TRI
= *MF
.getSubtarget().getRegisterInfo();
1516 const TargetFrameLowering
*TFI
= MF
.getSubtarget().getFrameLowering();
1518 bool InsideCallSequence
= false;
1520 for (MachineBasicBlock::iterator I
= BB
->begin(); I
!= BB
->end(); ) {
1521 if (TII
.isFrameInstr(*I
)) {
1522 InsideCallSequence
= TII
.isFrameSetup(*I
);
1523 SPAdj
+= TII
.getSPAdjust(*I
);
1524 I
= TFI
->eliminateCallFramePseudoInstr(MF
, *BB
, I
);
1528 MachineInstr
&MI
= *I
;
1530 bool DidFinishLoop
= true;
1531 for (unsigned i
= 0, e
= MI
.getNumOperands(); i
!= e
; ++i
) {
1532 if (!MI
.getOperand(i
).isFI())
1535 if (replaceFrameIndexDebugInstr(MF
, MI
, i
, SPAdj
))
1538 // Some instructions (e.g. inline asm instructions) can have
1539 // multiple frame indices and/or cause eliminateFrameIndex
1540 // to insert more than one instruction. We need the register
1541 // scavenger to go through all of these instructions so that
1542 // it can update its register information. We keep the
1543 // iterator at the point before insertion so that we can
1544 // revisit them in full.
1545 bool AtBeginning
= (I
== BB
->begin());
1546 if (!AtBeginning
) --I
;
1548 // If this instruction has a FrameIndex operand, we need to
1549 // use that target machine register info object to eliminate
1551 TRI
.eliminateFrameIndex(MI
, SPAdj
, i
);
1553 // Reset the iterator if we were at the beginning of the BB.
1559 DidFinishLoop
= false;
1563 // If we are looking at a call sequence, we need to keep track of
1564 // the SP adjustment made by each instruction in the sequence.
1565 // This includes both the frame setup/destroy pseudos (handled above),
1566 // as well as other instructions that have side effects w.r.t the SP.
1567 // Note that this must come after eliminateFrameIndex, because
1568 // if I itself referred to a frame index, we shouldn't count its own
1570 if (DidFinishLoop
&& InsideCallSequence
)
1571 SPAdj
+= TII
.getSPAdjust(MI
);
1573 if (DoIncr
&& I
!= BB
->end())