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/DepthFirstIterator.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineDominators.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineFunctionPass.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineLoopInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineOperand.h"
38 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
39 #include "llvm/CodeGen/MachineRegisterInfo.h"
40 #include "llvm/CodeGen/RegisterScavenging.h"
41 #include "llvm/CodeGen/TargetFrameLowering.h"
42 #include "llvm/CodeGen/TargetInstrInfo.h"
43 #include "llvm/CodeGen/TargetOpcodes.h"
44 #include "llvm/CodeGen/TargetRegisterInfo.h"
45 #include "llvm/CodeGen/TargetSubtargetInfo.h"
46 #include "llvm/CodeGen/WinEHFuncInfo.h"
47 #include "llvm/IR/Attributes.h"
48 #include "llvm/IR/CallingConv.h"
49 #include "llvm/IR/DebugInfoMetadata.h"
50 #include "llvm/IR/DiagnosticInfo.h"
51 #include "llvm/IR/Function.h"
52 #include "llvm/IR/InlineAsm.h"
53 #include "llvm/IR/LLVMContext.h"
54 #include "llvm/InitializePasses.h"
55 #include "llvm/MC/MCRegisterInfo.h"
56 #include "llvm/Pass.h"
57 #include "llvm/Support/CodeGen.h"
58 #include "llvm/Support/CommandLine.h"
59 #include "llvm/Support/Debug.h"
60 #include "llvm/Support/ErrorHandling.h"
61 #include "llvm/Support/MathExtras.h"
62 #include "llvm/Support/raw_ostream.h"
63 #include "llvm/Target/TargetMachine.h"
64 #include "llvm/Target/TargetOptions.h"
75 #define DEBUG_TYPE "prologepilog"
77 using MBBVector
= SmallVector
<MachineBasicBlock
*, 4>;
79 STATISTIC(NumLeafFuncWithSpills
, "Number of leaf functions with CSRs");
80 STATISTIC(NumFuncSeen
, "Number of functions seen in PEI");
85 class PEI
: public MachineFunctionPass
{
89 PEI() : MachineFunctionPass(ID
) {
90 initializePEIPass(*PassRegistry::getPassRegistry());
93 void getAnalysisUsage(AnalysisUsage
&AU
) const override
;
95 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
96 /// frame indexes with appropriate references.
97 bool runOnMachineFunction(MachineFunction
&MF
) override
;
102 // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved
103 // stack frame indexes.
104 unsigned MinCSFrameIndex
= std::numeric_limits
<unsigned>::max();
105 unsigned MaxCSFrameIndex
= 0;
107 // Save and Restore blocks of the current function. Typically there is a
108 // single save block, unless Windows EH funclets are involved.
109 MBBVector SaveBlocks
;
110 MBBVector RestoreBlocks
;
112 // Flag to control whether to use the register scavenger to resolve
113 // frame index materialization registers. Set according to
114 // TRI->requiresFrameIndexScavenging() for the current function.
115 bool FrameIndexVirtualScavenging
;
117 // Flag to control whether the scavenger should be passed even though
118 // FrameIndexVirtualScavenging is used.
119 bool FrameIndexEliminationScavenging
;
122 MachineOptimizationRemarkEmitter
*ORE
= nullptr;
124 void calculateCallFrameInfo(MachineFunction
&MF
);
125 void calculateSaveRestoreBlocks(MachineFunction
&MF
);
126 void spillCalleeSavedRegs(MachineFunction
&MF
);
128 void calculateFrameObjectOffsets(MachineFunction
&MF
);
129 void replaceFrameIndices(MachineFunction
&MF
);
130 void replaceFrameIndices(MachineBasicBlock
*BB
, MachineFunction
&MF
,
132 void insertPrologEpilogCode(MachineFunction
&MF
);
133 void insertZeroCallUsedRegs(MachineFunction
&MF
);
136 } // end anonymous namespace
140 char &llvm::PrologEpilogCodeInserterID
= PEI::ID
;
142 INITIALIZE_PASS_BEGIN(PEI
, DEBUG_TYPE
, "Prologue/Epilogue Insertion", false,
144 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo
)
145 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree
)
146 INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass
)
147 INITIALIZE_PASS_END(PEI
, DEBUG_TYPE
,
148 "Prologue/Epilogue Insertion & Frame Finalization", false,
151 MachineFunctionPass
*llvm::createPrologEpilogInserterPass() {
155 STATISTIC(NumBytesStackSpace
,
156 "Number of bytes used for stack in all functions");
158 void PEI::getAnalysisUsage(AnalysisUsage
&AU
) const {
159 AU
.setPreservesCFG();
160 AU
.addPreserved
<MachineLoopInfo
>();
161 AU
.addPreserved
<MachineDominatorTree
>();
162 AU
.addRequired
<MachineOptimizationRemarkEmitterPass
>();
163 MachineFunctionPass::getAnalysisUsage(AU
);
166 /// StackObjSet - A set of stack object indexes
167 using StackObjSet
= SmallSetVector
<int, 8>;
169 using SavedDbgValuesMap
=
170 SmallDenseMap
<MachineBasicBlock
*, SmallVector
<MachineInstr
*, 4>, 4>;
172 /// Stash DBG_VALUEs that describe parameters and which are placed at the start
173 /// of the block. Later on, after the prologue code has been emitted, the
174 /// stashed DBG_VALUEs will be reinserted at the start of the block.
175 static void stashEntryDbgValues(MachineBasicBlock
&MBB
,
176 SavedDbgValuesMap
&EntryDbgValues
) {
177 SmallVector
<const MachineInstr
*, 4> FrameIndexValues
;
179 for (auto &MI
: MBB
) {
180 if (!MI
.isDebugInstr())
182 if (!MI
.isDebugValue() || !MI
.getDebugVariable()->isParameter())
184 if (any_of(MI
.debug_operands(),
185 [](const MachineOperand
&MO
) { return MO
.isFI(); })) {
186 // We can only emit valid locations for frame indices after the frame
187 // setup, so do not stash away them.
188 FrameIndexValues
.push_back(&MI
);
191 const DILocalVariable
*Var
= MI
.getDebugVariable();
192 const DIExpression
*Expr
= MI
.getDebugExpression();
193 auto Overlaps
= [Var
, Expr
](const MachineInstr
*DV
) {
194 return Var
== DV
->getDebugVariable() &&
195 Expr
->fragmentsOverlap(DV
->getDebugExpression());
197 // See if the debug value overlaps with any preceding debug value that will
198 // not be stashed. If that is the case, then we can't stash this value, as
199 // we would then reorder the values at reinsertion.
200 if (llvm::none_of(FrameIndexValues
, Overlaps
))
201 EntryDbgValues
[&MBB
].push_back(&MI
);
204 // Remove stashed debug values from the block.
205 if (EntryDbgValues
.count(&MBB
))
206 for (auto *MI
: EntryDbgValues
[&MBB
])
207 MI
->removeFromParent();
210 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
211 /// frame indexes with appropriate references.
212 bool PEI::runOnMachineFunction(MachineFunction
&MF
) {
214 const Function
&F
= MF
.getFunction();
215 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
216 const TargetFrameLowering
*TFI
= MF
.getSubtarget().getFrameLowering();
218 RS
= TRI
->requiresRegisterScavenging(MF
) ? new RegScavenger() : nullptr;
219 FrameIndexVirtualScavenging
= TRI
->requiresFrameIndexScavenging(MF
);
220 ORE
= &getAnalysis
<MachineOptimizationRemarkEmitterPass
>().getORE();
222 // Calculate the MaxCallFrameSize and AdjustsStack variables for the
223 // function's frame information. Also eliminates call frame pseudo
225 calculateCallFrameInfo(MF
);
227 // Determine placement of CSR spill/restore code and prolog/epilog code:
228 // place all spills in the entry block, all restores in return blocks.
229 calculateSaveRestoreBlocks(MF
);
231 // Stash away DBG_VALUEs that should not be moved by insertion of prolog code.
232 SavedDbgValuesMap EntryDbgValues
;
233 for (MachineBasicBlock
*SaveBlock
: SaveBlocks
)
234 stashEntryDbgValues(*SaveBlock
, EntryDbgValues
);
236 // Handle CSR spilling and restoring, for targets that need it.
237 if (MF
.getTarget().usesPhysRegsForValues())
238 spillCalleeSavedRegs(MF
);
240 // Allow the target machine to make final modifications to the function
241 // before the frame layout is finalized.
242 TFI
->processFunctionBeforeFrameFinalized(MF
, RS
);
244 // Calculate actual frame offsets for all abstract stack objects...
245 calculateFrameObjectOffsets(MF
);
247 // Add prolog and epilog code to the function. This function is required
248 // to align the stack frame as necessary for any stack variables or
249 // called functions. Because of this, calculateCalleeSavedRegisters()
250 // must be called before this function in order to set the AdjustsStack
251 // and MaxCallFrameSize variables.
252 if (!F
.hasFnAttribute(Attribute::Naked
))
253 insertPrologEpilogCode(MF
);
255 // Reinsert stashed debug values at the start of the entry blocks.
256 for (auto &I
: EntryDbgValues
)
257 I
.first
->insert(I
.first
->begin(), I
.second
.begin(), I
.second
.end());
259 // Allow the target machine to make final modifications to the function
260 // before the frame layout is finalized.
261 TFI
->processFunctionBeforeFrameIndicesReplaced(MF
, RS
);
263 // Replace all MO_FrameIndex operands with physical register references
264 // and actual offsets.
266 replaceFrameIndices(MF
);
268 // If register scavenging is needed, as we've enabled doing it as a
269 // post-pass, scavenge the virtual registers that frame index elimination
271 if (TRI
->requiresRegisterScavenging(MF
) && FrameIndexVirtualScavenging
)
272 scavengeFrameVirtualRegs(MF
, *RS
);
274 // Warn on stack size when we exceeds the given limit.
275 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
276 uint64_t StackSize
= MFI
.getStackSize();
278 unsigned Threshold
= UINT_MAX
;
279 if (MF
.getFunction().hasFnAttribute("warn-stack-size")) {
280 bool Failed
= MF
.getFunction()
281 .getFnAttribute("warn-stack-size")
283 .getAsInteger(10, Threshold
);
284 // Verifier should have caught this.
285 assert(!Failed
&& "Invalid warn-stack-size fn attr value");
288 if (StackSize
> Threshold
) {
289 DiagnosticInfoStackSize
DiagStackSize(F
, StackSize
, Threshold
, DS_Warning
);
290 F
.getContext().diagnose(DiagStackSize
);
293 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE
, "StackSize",
294 MF
.getFunction().getSubprogram(),
296 << ore::NV("NumStackBytes", StackSize
) << " stack bytes in function";
301 RestoreBlocks
.clear();
302 MFI
.setSavePoint(nullptr);
303 MFI
.setRestorePoint(nullptr);
307 /// Calculate the MaxCallFrameSize and AdjustsStack
308 /// variables for the function's frame information and eliminate call frame
309 /// pseudo instructions.
310 void PEI::calculateCallFrameInfo(MachineFunction
&MF
) {
311 const TargetInstrInfo
&TII
= *MF
.getSubtarget().getInstrInfo();
312 const TargetFrameLowering
*TFI
= MF
.getSubtarget().getFrameLowering();
313 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
315 unsigned MaxCallFrameSize
= 0;
316 bool AdjustsStack
= MFI
.adjustsStack();
318 // Get the function call frame set-up and tear-down instruction opcode
319 unsigned FrameSetupOpcode
= TII
.getCallFrameSetupOpcode();
320 unsigned FrameDestroyOpcode
= TII
.getCallFrameDestroyOpcode();
322 // Early exit for targets which have no call frame setup/destroy pseudo
324 if (FrameSetupOpcode
== ~0u && FrameDestroyOpcode
== ~0u)
327 std::vector
<MachineBasicBlock::iterator
> FrameSDOps
;
328 for (MachineBasicBlock
&BB
: MF
)
329 for (MachineBasicBlock::iterator I
= BB
.begin(); I
!= BB
.end(); ++I
)
330 if (TII
.isFrameInstr(*I
)) {
331 unsigned Size
= TII
.getFrameSize(*I
);
332 if (Size
> MaxCallFrameSize
) MaxCallFrameSize
= Size
;
334 FrameSDOps
.push_back(I
);
335 } else if (I
->isInlineAsm()) {
336 // Some inline asm's need a stack frame, as indicated by operand 1.
337 unsigned ExtraInfo
= I
->getOperand(InlineAsm::MIOp_ExtraInfo
).getImm();
338 if (ExtraInfo
& InlineAsm::Extra_IsAlignStack
)
342 assert(!MFI
.isMaxCallFrameSizeComputed() ||
343 (MFI
.getMaxCallFrameSize() == MaxCallFrameSize
&&
344 MFI
.adjustsStack() == AdjustsStack
));
345 MFI
.setAdjustsStack(AdjustsStack
);
346 MFI
.setMaxCallFrameSize(MaxCallFrameSize
);
348 for (MachineBasicBlock::iterator I
: FrameSDOps
) {
349 // If call frames are not being included as part of the stack frame, and
350 // the target doesn't indicate otherwise, remove the call frame pseudos
351 // here. The sub/add sp instruction pairs are still inserted, but we don't
352 // need to track the SP adjustment for frame index elimination.
353 if (TFI
->canSimplifyCallFramePseudos(MF
))
354 TFI
->eliminateCallFramePseudoInstr(MF
, *I
->getParent(), I
);
358 /// Compute the sets of entry and return blocks for saving and restoring
359 /// callee-saved registers, and placing prolog and epilog code.
360 void PEI::calculateSaveRestoreBlocks(MachineFunction
&MF
) {
361 const MachineFrameInfo
&MFI
= MF
.getFrameInfo();
363 // Even when we do not change any CSR, we still want to insert the
364 // prologue and epilogue of the function.
365 // So set the save points for those.
367 // Use the points found by shrink-wrapping, if any.
368 if (MFI
.getSavePoint()) {
369 SaveBlocks
.push_back(MFI
.getSavePoint());
370 assert(MFI
.getRestorePoint() && "Both restore and save must be set");
371 MachineBasicBlock
*RestoreBlock
= MFI
.getRestorePoint();
372 // If RestoreBlock does not have any successor and is not a return block
373 // then the end point is unreachable and we do not need to insert any
375 if (!RestoreBlock
->succ_empty() || RestoreBlock
->isReturnBlock())
376 RestoreBlocks
.push_back(RestoreBlock
);
380 // Save refs to entry and return blocks.
381 SaveBlocks
.push_back(&MF
.front());
382 for (MachineBasicBlock
&MBB
: MF
) {
383 if (MBB
.isEHFuncletEntry())
384 SaveBlocks
.push_back(&MBB
);
385 if (MBB
.isReturnBlock())
386 RestoreBlocks
.push_back(&MBB
);
390 static void assignCalleeSavedSpillSlots(MachineFunction
&F
,
391 const BitVector
&SavedRegs
,
392 unsigned &MinCSFrameIndex
,
393 unsigned &MaxCSFrameIndex
) {
394 if (SavedRegs
.empty())
397 const TargetRegisterInfo
*RegInfo
= F
.getSubtarget().getRegisterInfo();
398 const MCPhysReg
*CSRegs
= F
.getRegInfo().getCalleeSavedRegs();
399 BitVector
CSMask(SavedRegs
.size());
401 for (unsigned i
= 0; CSRegs
[i
]; ++i
)
402 CSMask
.set(CSRegs
[i
]);
404 std::vector
<CalleeSavedInfo
> CSI
;
405 for (unsigned i
= 0; CSRegs
[i
]; ++i
) {
406 unsigned Reg
= CSRegs
[i
];
407 if (SavedRegs
.test(Reg
)) {
408 bool SavedSuper
= false;
409 for (const MCPhysReg
&SuperReg
: RegInfo
->superregs(Reg
)) {
410 // Some backends set all aliases for some registers as saved, such as
411 // Mips's $fp, so they appear in SavedRegs but not CSRegs.
412 if (SavedRegs
.test(SuperReg
) && CSMask
.test(SuperReg
)) {
419 CSI
.push_back(CalleeSavedInfo(Reg
));
423 const TargetFrameLowering
*TFI
= F
.getSubtarget().getFrameLowering();
424 MachineFrameInfo
&MFI
= F
.getFrameInfo();
425 if (!TFI
->assignCalleeSavedSpillSlots(F
, RegInfo
, CSI
, MinCSFrameIndex
,
427 // If target doesn't implement this, use generic code.
430 return; // Early exit if no callee saved registers are modified!
432 unsigned NumFixedSpillSlots
;
433 const TargetFrameLowering::SpillSlot
*FixedSpillSlots
=
434 TFI
->getCalleeSavedSpillSlots(NumFixedSpillSlots
);
436 // Now that we know which registers need to be saved and restored, allocate
437 // stack slots for them.
438 for (auto &CS
: CSI
) {
439 // If the target has spilled this register to another register, we don't
440 // need to allocate a stack slot.
441 if (CS
.isSpilledToReg())
444 unsigned Reg
= CS
.getReg();
445 const TargetRegisterClass
*RC
= RegInfo
->getMinimalPhysRegClass(Reg
);
448 if (RegInfo
->hasReservedSpillSlot(F
, Reg
, FrameIdx
)) {
449 CS
.setFrameIdx(FrameIdx
);
453 // Check to see if this physreg must be spilled to a particular stack slot
455 const TargetFrameLowering::SpillSlot
*FixedSlot
= FixedSpillSlots
;
456 while (FixedSlot
!= FixedSpillSlots
+ NumFixedSpillSlots
&&
457 FixedSlot
->Reg
!= Reg
)
460 unsigned Size
= RegInfo
->getSpillSize(*RC
);
461 if (FixedSlot
== FixedSpillSlots
+ NumFixedSpillSlots
) {
462 // Nope, just spill it anywhere convenient.
463 Align Alignment
= RegInfo
->getSpillAlign(*RC
);
464 // We may not be able to satisfy the desired alignment specification of
465 // the TargetRegisterClass if the stack alignment is smaller. Use the
467 Alignment
= std::min(Alignment
, TFI
->getStackAlign());
468 FrameIdx
= MFI
.CreateStackObject(Size
, Alignment
, true);
469 if ((unsigned)FrameIdx
< MinCSFrameIndex
) MinCSFrameIndex
= FrameIdx
;
470 if ((unsigned)FrameIdx
> MaxCSFrameIndex
) MaxCSFrameIndex
= FrameIdx
;
472 // Spill it to the stack where we must.
473 FrameIdx
= MFI
.CreateFixedSpillStackObject(Size
, FixedSlot
->Offset
);
476 CS
.setFrameIdx(FrameIdx
);
480 MFI
.setCalleeSavedInfo(CSI
);
483 /// Helper function to update the liveness information for the callee-saved
485 static void updateLiveness(MachineFunction
&MF
) {
486 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
487 // Visited will contain all the basic blocks that are in the region
488 // where the callee saved registers are alive:
489 // - Anything that is not Save or Restore -> LiveThrough.
491 // - Restore -> LiveOut.
492 // The live-out is not attached to the block, so no need to keep
493 // Restore in this set.
494 SmallPtrSet
<MachineBasicBlock
*, 8> Visited
;
495 SmallVector
<MachineBasicBlock
*, 8> WorkList
;
496 MachineBasicBlock
*Entry
= &MF
.front();
497 MachineBasicBlock
*Save
= MFI
.getSavePoint();
503 WorkList
.push_back(Entry
);
504 Visited
.insert(Entry
);
506 Visited
.insert(Save
);
508 MachineBasicBlock
*Restore
= MFI
.getRestorePoint();
510 // By construction Restore cannot be visited, otherwise it
511 // means there exists a path to Restore that does not go
513 WorkList
.push_back(Restore
);
515 while (!WorkList
.empty()) {
516 const MachineBasicBlock
*CurBB
= WorkList
.pop_back_val();
517 // By construction, the region that is after the save point is
518 // dominated by the Save and post-dominated by the Restore.
519 if (CurBB
== Save
&& Save
!= Restore
)
521 // Enqueue all the successors not already visited.
522 // Those are by construction either before Save or after Restore.
523 for (MachineBasicBlock
*SuccBB
: CurBB
->successors())
524 if (Visited
.insert(SuccBB
).second
)
525 WorkList
.push_back(SuccBB
);
528 const std::vector
<CalleeSavedInfo
> &CSI
= MFI
.getCalleeSavedInfo();
530 MachineRegisterInfo
&MRI
= MF
.getRegInfo();
531 for (const CalleeSavedInfo
&I
: CSI
) {
532 for (MachineBasicBlock
*MBB
: Visited
) {
533 MCPhysReg Reg
= I
.getReg();
534 // Add the callee-saved register as live-in.
535 // It's killed at the spill.
536 if (!MRI
.isReserved(Reg
) && !MBB
->isLiveIn(Reg
))
539 // If callee-saved register is spilled to another register rather than
540 // spilling to stack, the destination register has to be marked as live for
541 // each MBB between the prologue and epilogue so that it is not clobbered
542 // before it is reloaded in the epilogue. The Visited set contains all
543 // blocks outside of the region delimited by prologue/epilogue.
544 if (I
.isSpilledToReg()) {
545 for (MachineBasicBlock
&MBB
: MF
) {
546 if (Visited
.count(&MBB
))
548 MCPhysReg DstReg
= I
.getDstReg();
549 if (!MBB
.isLiveIn(DstReg
))
550 MBB
.addLiveIn(DstReg
);
556 /// Insert restore code for the callee-saved registers used in the function.
557 static void insertCSRSaves(MachineBasicBlock
&SaveBlock
,
558 ArrayRef
<CalleeSavedInfo
> CSI
) {
559 MachineFunction
&MF
= *SaveBlock
.getParent();
560 const TargetInstrInfo
&TII
= *MF
.getSubtarget().getInstrInfo();
561 const TargetFrameLowering
*TFI
= MF
.getSubtarget().getFrameLowering();
562 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
564 MachineBasicBlock::iterator I
= SaveBlock
.begin();
565 if (!TFI
->spillCalleeSavedRegisters(SaveBlock
, I
, CSI
, TRI
)) {
566 for (const CalleeSavedInfo
&CS
: CSI
) {
567 // Insert the spill to the stack frame.
568 unsigned Reg
= CS
.getReg();
570 if (CS
.isSpilledToReg()) {
571 BuildMI(SaveBlock
, I
, DebugLoc(),
572 TII
.get(TargetOpcode::COPY
), CS
.getDstReg())
573 .addReg(Reg
, getKillRegState(true));
575 const TargetRegisterClass
*RC
= TRI
->getMinimalPhysRegClass(Reg
);
576 TII
.storeRegToStackSlot(SaveBlock
, I
, Reg
, true, CS
.getFrameIdx(), RC
,
583 /// Insert restore code for the callee-saved registers used in the function.
584 static void insertCSRRestores(MachineBasicBlock
&RestoreBlock
,
585 std::vector
<CalleeSavedInfo
> &CSI
) {
586 MachineFunction
&MF
= *RestoreBlock
.getParent();
587 const TargetInstrInfo
&TII
= *MF
.getSubtarget().getInstrInfo();
588 const TargetFrameLowering
*TFI
= MF
.getSubtarget().getFrameLowering();
589 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
591 // Restore all registers immediately before the return and any
592 // terminators that precede it.
593 MachineBasicBlock::iterator I
= RestoreBlock
.getFirstTerminator();
595 if (!TFI
->restoreCalleeSavedRegisters(RestoreBlock
, I
, CSI
, TRI
)) {
596 for (const CalleeSavedInfo
&CI
: reverse(CSI
)) {
597 unsigned Reg
= CI
.getReg();
598 if (CI
.isSpilledToReg()) {
599 BuildMI(RestoreBlock
, I
, DebugLoc(), TII
.get(TargetOpcode::COPY
), Reg
)
600 .addReg(CI
.getDstReg(), getKillRegState(true));
602 const TargetRegisterClass
*RC
= TRI
->getMinimalPhysRegClass(Reg
);
603 TII
.loadRegFromStackSlot(RestoreBlock
, I
, Reg
, CI
.getFrameIdx(), RC
, TRI
);
604 assert(I
!= RestoreBlock
.begin() &&
605 "loadRegFromStackSlot didn't insert any code!");
606 // Insert in reverse order. loadRegFromStackSlot can insert
607 // multiple instructions.
613 void PEI::spillCalleeSavedRegs(MachineFunction
&MF
) {
614 // We can't list this requirement in getRequiredProperties because some
615 // targets (WebAssembly) use virtual registers past this point, and the pass
616 // pipeline is set up without giving the passes a chance to look at the
618 // FIXME: Find a way to express this in getRequiredProperties.
619 assert(MF
.getProperties().hasProperty(
620 MachineFunctionProperties::Property::NoVRegs
));
622 const Function
&F
= MF
.getFunction();
623 const TargetFrameLowering
*TFI
= MF
.getSubtarget().getFrameLowering();
624 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
625 MinCSFrameIndex
= std::numeric_limits
<unsigned>::max();
628 // Determine which of the registers in the callee save list should be saved.
630 TFI
->determineCalleeSaves(MF
, SavedRegs
, RS
);
632 // Assign stack slots for any callee-saved registers that must be spilled.
633 assignCalleeSavedSpillSlots(MF
, SavedRegs
, MinCSFrameIndex
, MaxCSFrameIndex
);
635 // Add the code to save and restore the callee saved registers.
636 if (!F
.hasFnAttribute(Attribute::Naked
)) {
637 MFI
.setCalleeSavedInfoValid(true);
639 std::vector
<CalleeSavedInfo
> &CSI
= MFI
.getCalleeSavedInfo();
642 NumLeafFuncWithSpills
++;
644 for (MachineBasicBlock
*SaveBlock
: SaveBlocks
)
645 insertCSRSaves(*SaveBlock
, CSI
);
647 // Update the live-in information of all the blocks up to the save point.
650 for (MachineBasicBlock
*RestoreBlock
: RestoreBlocks
)
651 insertCSRRestores(*RestoreBlock
, CSI
);
656 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
657 static inline void AdjustStackOffset(MachineFrameInfo
&MFI
, int FrameIdx
,
658 bool StackGrowsDown
, int64_t &Offset
,
659 Align
&MaxAlign
, unsigned Skew
) {
660 // If the stack grows down, add the object size to find the lowest address.
662 Offset
+= MFI
.getObjectSize(FrameIdx
);
664 Align Alignment
= MFI
.getObjectAlign(FrameIdx
);
666 // If the alignment of this object is greater than that of the stack, then
667 // increase the stack alignment to match.
668 MaxAlign
= std::max(MaxAlign
, Alignment
);
670 // Adjust to alignment boundary.
671 Offset
= alignTo(Offset
, Alignment
, Skew
);
673 if (StackGrowsDown
) {
674 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx
<< ") at SP[" << -Offset
676 MFI
.setObjectOffset(FrameIdx
, -Offset
); // Set the computed offset
678 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx
<< ") at SP[" << Offset
680 MFI
.setObjectOffset(FrameIdx
, Offset
);
681 Offset
+= MFI
.getObjectSize(FrameIdx
);
685 /// Compute which bytes of fixed and callee-save stack area are unused and keep
686 /// track of them in StackBytesFree.
688 computeFreeStackSlots(MachineFrameInfo
&MFI
, bool StackGrowsDown
,
689 unsigned MinCSFrameIndex
, unsigned MaxCSFrameIndex
,
690 int64_t FixedCSEnd
, BitVector
&StackBytesFree
) {
691 // Avoid undefined int64_t -> int conversion below in extreme case.
692 if (FixedCSEnd
> std::numeric_limits
<int>::max())
695 StackBytesFree
.resize(FixedCSEnd
, true);
697 SmallVector
<int, 16> AllocatedFrameSlots
;
698 // Add fixed objects.
699 for (int i
= MFI
.getObjectIndexBegin(); i
!= 0; ++i
)
700 // StackSlot scavenging is only implemented for the default stack.
701 if (MFI
.getStackID(i
) == TargetStackID::Default
)
702 AllocatedFrameSlots
.push_back(i
);
703 // Add callee-save objects if there are any.
704 if (MinCSFrameIndex
<= MaxCSFrameIndex
) {
705 for (int i
= MinCSFrameIndex
; i
<= (int)MaxCSFrameIndex
; ++i
)
706 if (MFI
.getStackID(i
) == TargetStackID::Default
)
707 AllocatedFrameSlots
.push_back(i
);
710 for (int i
: AllocatedFrameSlots
) {
711 // These are converted from int64_t, but they should always fit in int
712 // because of the FixedCSEnd check above.
713 int ObjOffset
= MFI
.getObjectOffset(i
);
714 int ObjSize
= MFI
.getObjectSize(i
);
715 int ObjStart
, ObjEnd
;
716 if (StackGrowsDown
) {
717 // ObjOffset is negative when StackGrowsDown is true.
718 ObjStart
= -ObjOffset
- ObjSize
;
721 ObjStart
= ObjOffset
;
722 ObjEnd
= ObjOffset
+ ObjSize
;
724 // Ignore fixed holes that are in the previous stack frame.
726 StackBytesFree
.reset(ObjStart
, ObjEnd
);
730 /// Assign frame object to an unused portion of the stack in the fixed stack
731 /// object range. Return true if the allocation was successful.
732 static inline bool scavengeStackSlot(MachineFrameInfo
&MFI
, int FrameIdx
,
733 bool StackGrowsDown
, Align MaxAlign
,
734 BitVector
&StackBytesFree
) {
735 if (MFI
.isVariableSizedObjectIndex(FrameIdx
))
738 if (StackBytesFree
.none()) {
739 // clear it to speed up later scavengeStackSlot calls to
740 // StackBytesFree.none()
741 StackBytesFree
.clear();
745 Align ObjAlign
= MFI
.getObjectAlign(FrameIdx
);
746 if (ObjAlign
> MaxAlign
)
749 int64_t ObjSize
= MFI
.getObjectSize(FrameIdx
);
751 for (FreeStart
= StackBytesFree
.find_first(); FreeStart
!= -1;
752 FreeStart
= StackBytesFree
.find_next(FreeStart
)) {
754 // Check that free space has suitable alignment.
755 unsigned ObjStart
= StackGrowsDown
? FreeStart
+ ObjSize
: FreeStart
;
756 if (alignTo(ObjStart
, ObjAlign
) != ObjStart
)
759 if (FreeStart
+ ObjSize
> StackBytesFree
.size())
762 bool AllBytesFree
= true;
763 for (unsigned Byte
= 0; Byte
< ObjSize
; ++Byte
)
764 if (!StackBytesFree
.test(FreeStart
+ Byte
)) {
765 AllBytesFree
= false;
775 if (StackGrowsDown
) {
776 int ObjStart
= -(FreeStart
+ ObjSize
);
777 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx
<< ") scavenged at SP["
778 << ObjStart
<< "]\n");
779 MFI
.setObjectOffset(FrameIdx
, ObjStart
);
781 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx
<< ") scavenged at SP["
782 << FreeStart
<< "]\n");
783 MFI
.setObjectOffset(FrameIdx
, FreeStart
);
786 StackBytesFree
.reset(FreeStart
, FreeStart
+ ObjSize
);
790 /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
791 /// those required to be close to the Stack Protector) to stack offsets.
792 static void AssignProtectedObjSet(const StackObjSet
&UnassignedObjs
,
793 SmallSet
<int, 16> &ProtectedObjs
,
794 MachineFrameInfo
&MFI
, bool StackGrowsDown
,
795 int64_t &Offset
, Align
&MaxAlign
,
798 for (int i
: UnassignedObjs
) {
799 AdjustStackOffset(MFI
, i
, StackGrowsDown
, Offset
, MaxAlign
, Skew
);
800 ProtectedObjs
.insert(i
);
804 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
805 /// abstract stack objects.
806 void PEI::calculateFrameObjectOffsets(MachineFunction
&MF
) {
807 const TargetFrameLowering
&TFI
= *MF
.getSubtarget().getFrameLowering();
809 bool StackGrowsDown
=
810 TFI
.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown
;
812 // Loop over all of the stack objects, assigning sequential addresses...
813 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
815 // Start at the beginning of the local area.
816 // The Offset is the distance from the stack top in the direction
817 // of stack growth -- so it's always nonnegative.
818 int LocalAreaOffset
= TFI
.getOffsetOfLocalArea();
820 LocalAreaOffset
= -LocalAreaOffset
;
821 assert(LocalAreaOffset
>= 0
822 && "Local area offset should be in direction of stack growth");
823 int64_t Offset
= LocalAreaOffset
;
825 // Skew to be applied to alignment.
826 unsigned Skew
= TFI
.getStackAlignmentSkew(MF
);
828 #ifdef EXPENSIVE_CHECKS
829 for (unsigned i
= 0, e
= MFI
.getObjectIndexEnd(); i
!= e
; ++i
)
830 if (!MFI
.isDeadObjectIndex(i
) &&
831 MFI
.getStackID(i
) == TargetStackID::Default
)
832 assert(MFI
.getObjectAlign(i
) <= MFI
.getMaxAlign() &&
833 "MaxAlignment is invalid");
836 // If there are fixed sized objects that are preallocated in the local area,
837 // non-fixed objects can't be allocated right at the start of local area.
838 // Adjust 'Offset' to point to the end of last fixed sized preallocated
840 for (int i
= MFI
.getObjectIndexBegin(); i
!= 0; ++i
) {
841 if (MFI
.getStackID(i
) !=
842 TargetStackID::Default
) // Only allocate objects on the default stack.
846 if (StackGrowsDown
) {
847 // The maximum distance from the stack pointer is at lower address of
848 // the object -- which is given by offset. For down growing stack
849 // the offset is negative, so we negate the offset to get the distance.
850 FixedOff
= -MFI
.getObjectOffset(i
);
852 // The maximum distance from the start pointer is at the upper
853 // address of the object.
854 FixedOff
= MFI
.getObjectOffset(i
) + MFI
.getObjectSize(i
);
856 if (FixedOff
> Offset
) Offset
= FixedOff
;
859 Align MaxAlign
= MFI
.getMaxAlign();
860 // First assign frame offsets to stack objects that are used to spill
861 // callee saved registers.
862 if (MaxCSFrameIndex
>= MinCSFrameIndex
) {
863 for (unsigned i
= 0; i
<= MaxCSFrameIndex
- MinCSFrameIndex
; ++i
) {
864 unsigned FrameIndex
=
865 StackGrowsDown
? MinCSFrameIndex
+ i
: MaxCSFrameIndex
- i
;
867 // Only allocate objects on the default stack.
868 if (MFI
.getStackID(FrameIndex
) != TargetStackID::Default
)
871 // TODO: should this just be if (MFI.isDeadObjectIndex(FrameIndex))
872 if (!StackGrowsDown
&& MFI
.isDeadObjectIndex(FrameIndex
))
875 AdjustStackOffset(MFI
, FrameIndex
, StackGrowsDown
, Offset
, MaxAlign
,
880 assert(MaxAlign
== MFI
.getMaxAlign() &&
881 "MFI.getMaxAlign should already account for all callee-saved "
882 "registers without a fixed stack slot");
884 // FixedCSEnd is the stack offset to the end of the fixed and callee-save
886 int64_t FixedCSEnd
= Offset
;
888 // Make sure the special register scavenging spill slot is closest to the
889 // incoming stack pointer if a frame pointer is required and is closer
890 // to the incoming rather than the final stack pointer.
891 const TargetRegisterInfo
*RegInfo
= MF
.getSubtarget().getRegisterInfo();
892 bool EarlyScavengingSlots
= TFI
.allocateScavengingFrameIndexesNearIncomingSP(MF
);
893 if (RS
&& EarlyScavengingSlots
) {
894 SmallVector
<int, 2> SFIs
;
895 RS
->getScavengingFrameIndices(SFIs
);
897 AdjustStackOffset(MFI
, SFI
, StackGrowsDown
, Offset
, MaxAlign
, Skew
);
900 // FIXME: Once this is working, then enable flag will change to a target
901 // check for whether the frame is large enough to want to use virtual
902 // frame index registers. Functions which don't want/need this optimization
903 // will continue to use the existing code path.
904 if (MFI
.getUseLocalStackAllocationBlock()) {
905 Align Alignment
= MFI
.getLocalFrameMaxAlign();
907 // Adjust to alignment boundary.
908 Offset
= alignTo(Offset
, Alignment
, Skew
);
910 LLVM_DEBUG(dbgs() << "Local frame base offset: " << Offset
<< "\n");
912 // Resolve offsets for objects in the local block.
913 for (unsigned i
= 0, e
= MFI
.getLocalFrameObjectCount(); i
!= e
; ++i
) {
914 std::pair
<int, int64_t> Entry
= MFI
.getLocalFrameObjectMap(i
);
915 int64_t FIOffset
= (StackGrowsDown
? -Offset
: Offset
) + Entry
.second
;
916 LLVM_DEBUG(dbgs() << "alloc FI(" << Entry
.first
<< ") at SP[" << FIOffset
918 MFI
.setObjectOffset(Entry
.first
, FIOffset
);
920 // Allocate the local block
921 Offset
+= MFI
.getLocalFrameSize();
923 MaxAlign
= std::max(Alignment
, MaxAlign
);
926 // Retrieve the Exception Handler registration node.
927 int EHRegNodeFrameIndex
= std::numeric_limits
<int>::max();
928 if (const WinEHFuncInfo
*FuncInfo
= MF
.getWinEHFuncInfo())
929 EHRegNodeFrameIndex
= FuncInfo
->EHRegNodeFrameIndex
;
931 // Make sure that the stack protector comes before the local variables on the
933 SmallSet
<int, 16> ProtectedObjs
;
934 if (MFI
.hasStackProtectorIndex()) {
935 int StackProtectorFI
= MFI
.getStackProtectorIndex();
936 StackObjSet LargeArrayObjs
;
937 StackObjSet SmallArrayObjs
;
938 StackObjSet AddrOfObjs
;
940 // If we need a stack protector, we need to make sure that
941 // LocalStackSlotPass didn't already allocate a slot for it.
942 // If we are told to use the LocalStackAllocationBlock, the stack protector
943 // is expected to be already pre-allocated.
944 if (MFI
.getStackID(StackProtectorFI
) != TargetStackID::Default
) {
945 // If the stack protector isn't on the default stack then it's up to the
946 // target to set the stack offset.
947 assert(MFI
.getObjectOffset(StackProtectorFI
) != 0 &&
948 "Offset of stack protector on non-default stack expected to be "
950 assert(!MFI
.isObjectPreAllocated(MFI
.getStackProtectorIndex()) &&
951 "Stack protector on non-default stack expected to not be "
952 "pre-allocated by LocalStackSlotPass.");
953 } else if (!MFI
.getUseLocalStackAllocationBlock()) {
954 AdjustStackOffset(MFI
, StackProtectorFI
, StackGrowsDown
, Offset
, MaxAlign
,
956 } else if (!MFI
.isObjectPreAllocated(MFI
.getStackProtectorIndex())) {
958 "Stack protector not pre-allocated by LocalStackSlotPass.");
961 // Assign large stack objects first.
962 for (unsigned i
= 0, e
= MFI
.getObjectIndexEnd(); i
!= e
; ++i
) {
963 if (MFI
.isObjectPreAllocated(i
) && MFI
.getUseLocalStackAllocationBlock())
965 if (i
>= MinCSFrameIndex
&& i
<= MaxCSFrameIndex
)
967 if (RS
&& RS
->isScavengingFrameIndex((int)i
))
969 if (MFI
.isDeadObjectIndex(i
))
971 if (StackProtectorFI
== (int)i
|| EHRegNodeFrameIndex
== (int)i
)
973 if (MFI
.getStackID(i
) !=
974 TargetStackID::Default
) // Only allocate objects on the default stack.
977 switch (MFI
.getObjectSSPLayout(i
)) {
978 case MachineFrameInfo::SSPLK_None
:
980 case MachineFrameInfo::SSPLK_SmallArray
:
981 SmallArrayObjs
.insert(i
);
983 case MachineFrameInfo::SSPLK_AddrOf
:
984 AddrOfObjs
.insert(i
);
986 case MachineFrameInfo::SSPLK_LargeArray
:
987 LargeArrayObjs
.insert(i
);
990 llvm_unreachable("Unexpected SSPLayoutKind.");
993 // We expect **all** the protected stack objects to be pre-allocated by
994 // LocalStackSlotPass. If it turns out that PEI still has to allocate some
995 // of them, we may end up messing up the expected order of the objects.
996 if (MFI
.getUseLocalStackAllocationBlock() &&
997 !(LargeArrayObjs
.empty() && SmallArrayObjs
.empty() &&
999 llvm_unreachable("Found protected stack objects not pre-allocated by "
1000 "LocalStackSlotPass.");
1002 AssignProtectedObjSet(LargeArrayObjs
, ProtectedObjs
, MFI
, StackGrowsDown
,
1003 Offset
, MaxAlign
, Skew
);
1004 AssignProtectedObjSet(SmallArrayObjs
, ProtectedObjs
, MFI
, StackGrowsDown
,
1005 Offset
, MaxAlign
, Skew
);
1006 AssignProtectedObjSet(AddrOfObjs
, ProtectedObjs
, MFI
, StackGrowsDown
,
1007 Offset
, MaxAlign
, Skew
);
1010 SmallVector
<int, 8> ObjectsToAllocate
;
1012 // Then prepare to assign frame offsets to stack objects that are not used to
1013 // spill callee saved registers.
1014 for (unsigned i
= 0, e
= MFI
.getObjectIndexEnd(); i
!= e
; ++i
) {
1015 if (MFI
.isObjectPreAllocated(i
) && MFI
.getUseLocalStackAllocationBlock())
1017 if (i
>= MinCSFrameIndex
&& i
<= MaxCSFrameIndex
)
1019 if (RS
&& RS
->isScavengingFrameIndex((int)i
))
1021 if (MFI
.isDeadObjectIndex(i
))
1023 if (MFI
.getStackProtectorIndex() == (int)i
|| EHRegNodeFrameIndex
== (int)i
)
1025 if (ProtectedObjs
.count(i
))
1027 if (MFI
.getStackID(i
) !=
1028 TargetStackID::Default
) // Only allocate objects on the default stack.
1031 // Add the objects that we need to allocate to our working set.
1032 ObjectsToAllocate
.push_back(i
);
1035 // Allocate the EH registration node first if one is present.
1036 if (EHRegNodeFrameIndex
!= std::numeric_limits
<int>::max())
1037 AdjustStackOffset(MFI
, EHRegNodeFrameIndex
, StackGrowsDown
, Offset
,
1040 // Give the targets a chance to order the objects the way they like it.
1041 if (MF
.getTarget().getOptLevel() != CodeGenOpt::None
&&
1042 MF
.getTarget().Options
.StackSymbolOrdering
)
1043 TFI
.orderFrameObjects(MF
, ObjectsToAllocate
);
1045 // Keep track of which bytes in the fixed and callee-save range are used so we
1046 // can use the holes when allocating later stack objects. Only do this if
1047 // stack protector isn't being used and the target requests it and we're
1049 BitVector StackBytesFree
;
1050 if (!ObjectsToAllocate
.empty() &&
1051 MF
.getTarget().getOptLevel() != CodeGenOpt::None
&&
1052 MFI
.getStackProtectorIndex() < 0 && TFI
.enableStackSlotScavenging(MF
))
1053 computeFreeStackSlots(MFI
, StackGrowsDown
, MinCSFrameIndex
, MaxCSFrameIndex
,
1054 FixedCSEnd
, StackBytesFree
);
1056 // Now walk the objects and actually assign base offsets to them.
1057 for (auto &Object
: ObjectsToAllocate
)
1058 if (!scavengeStackSlot(MFI
, Object
, StackGrowsDown
, MaxAlign
,
1060 AdjustStackOffset(MFI
, Object
, StackGrowsDown
, Offset
, MaxAlign
, Skew
);
1062 // Make sure the special register scavenging spill slot is closest to the
1064 if (RS
&& !EarlyScavengingSlots
) {
1065 SmallVector
<int, 2> SFIs
;
1066 RS
->getScavengingFrameIndices(SFIs
);
1067 for (int SFI
: SFIs
)
1068 AdjustStackOffset(MFI
, SFI
, StackGrowsDown
, Offset
, MaxAlign
, Skew
);
1071 if (!TFI
.targetHandlesStackFrameRounding()) {
1072 // If we have reserved argument space for call sites in the function
1073 // immediately on entry to the current function, count it as part of the
1074 // overall stack size.
1075 if (MFI
.adjustsStack() && TFI
.hasReservedCallFrame(MF
))
1076 Offset
+= MFI
.getMaxCallFrameSize();
1078 // Round up the size to a multiple of the alignment. If the function has
1079 // any calls or alloca's, align to the target's StackAlignment value to
1080 // ensure that the callee's frame or the alloca data is suitably aligned;
1081 // otherwise, for leaf functions, align to the TransientStackAlignment
1084 if (MFI
.adjustsStack() || MFI
.hasVarSizedObjects() ||
1085 (RegInfo
->hasStackRealignment(MF
) && MFI
.getObjectIndexEnd() != 0))
1086 StackAlign
= TFI
.getStackAlign();
1088 StackAlign
= TFI
.getTransientStackAlign();
1090 // If the frame pointer is eliminated, all frame offsets will be relative to
1091 // SP not FP. Align to MaxAlign so this works.
1092 StackAlign
= std::max(StackAlign
, MaxAlign
);
1093 int64_t OffsetBeforeAlignment
= Offset
;
1094 Offset
= alignTo(Offset
, StackAlign
, Skew
);
1096 // If we have increased the offset to fulfill the alignment constrants,
1097 // then the scavenging spill slots may become harder to reach from the
1098 // stack pointer, float them so they stay close.
1099 if (StackGrowsDown
&& OffsetBeforeAlignment
!= Offset
&& RS
&&
1100 !EarlyScavengingSlots
) {
1101 SmallVector
<int, 2> SFIs
;
1102 RS
->getScavengingFrameIndices(SFIs
);
1103 LLVM_DEBUG(if (!SFIs
.empty()) llvm::dbgs()
1104 << "Adjusting emergency spill slots!\n";);
1105 int64_t Delta
= Offset
- OffsetBeforeAlignment
;
1106 for (int SFI
: SFIs
) {
1107 LLVM_DEBUG(llvm::dbgs()
1108 << "Adjusting offset of emergency spill slot #" << SFI
1109 << " from " << MFI
.getObjectOffset(SFI
););
1110 MFI
.setObjectOffset(SFI
, MFI
.getObjectOffset(SFI
) - Delta
);
1111 LLVM_DEBUG(llvm::dbgs() << " to " << MFI
.getObjectOffset(SFI
) << "\n";);
1116 // Update frame info to pretend that this is part of the stack...
1117 int64_t StackSize
= Offset
- LocalAreaOffset
;
1118 MFI
.setStackSize(StackSize
);
1119 NumBytesStackSpace
+= StackSize
;
1122 /// insertPrologEpilogCode - Scan the function for modified callee saved
1123 /// registers, insert spill code for these callee saved registers, then add
1124 /// prolog and epilog code to the function.
1125 void PEI::insertPrologEpilogCode(MachineFunction
&MF
) {
1126 const TargetFrameLowering
&TFI
= *MF
.getSubtarget().getFrameLowering();
1128 // Add prologue to the function...
1129 for (MachineBasicBlock
*SaveBlock
: SaveBlocks
)
1130 TFI
.emitPrologue(MF
, *SaveBlock
);
1132 // Add epilogue to restore the callee-save registers in each exiting block.
1133 for (MachineBasicBlock
*RestoreBlock
: RestoreBlocks
)
1134 TFI
.emitEpilogue(MF
, *RestoreBlock
);
1136 // Zero call used registers before restoring callee-saved registers.
1137 insertZeroCallUsedRegs(MF
);
1139 for (MachineBasicBlock
*SaveBlock
: SaveBlocks
)
1140 TFI
.inlineStackProbe(MF
, *SaveBlock
);
1142 // Emit additional code that is required to support segmented stacks, if
1143 // we've been asked for it. This, when linked with a runtime with support
1144 // for segmented stacks (libgcc is one), will result in allocating stack
1145 // space in small chunks instead of one large contiguous block.
1146 if (MF
.shouldSplitStack()) {
1147 for (MachineBasicBlock
*SaveBlock
: SaveBlocks
)
1148 TFI
.adjustForSegmentedStacks(MF
, *SaveBlock
);
1149 // Record that there are split-stack functions, so we will emit a
1150 // special section to tell the linker.
1151 MF
.getMMI().setHasSplitStack(true);
1153 MF
.getMMI().setHasNosplitStack(true);
1155 // Emit additional code that is required to explicitly handle the stack in
1156 // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
1157 // approach is rather similar to that of Segmented Stacks, but it uses a
1158 // different conditional check and another BIF for allocating more stack
1160 if (MF
.getFunction().getCallingConv() == CallingConv::HiPE
)
1161 for (MachineBasicBlock
*SaveBlock
: SaveBlocks
)
1162 TFI
.adjustForHiPEPrologue(MF
, *SaveBlock
);
1165 /// insertZeroCallUsedRegs - Zero out call used registers.
1166 void PEI::insertZeroCallUsedRegs(MachineFunction
&MF
) {
1167 const Function
&F
= MF
.getFunction();
1169 if (!F
.hasFnAttribute("zero-call-used-regs"))
1172 using namespace ZeroCallUsedRegs
;
1174 ZeroCallUsedRegsKind ZeroRegsKind
=
1175 StringSwitch
<ZeroCallUsedRegsKind
>(
1176 F
.getFnAttribute("zero-call-used-regs").getValueAsString())
1177 .Case("skip", ZeroCallUsedRegsKind::Skip
)
1178 .Case("used-gpr-arg", ZeroCallUsedRegsKind::UsedGPRArg
)
1179 .Case("used-gpr", ZeroCallUsedRegsKind::UsedGPR
)
1180 .Case("used-arg", ZeroCallUsedRegsKind::UsedArg
)
1181 .Case("used", ZeroCallUsedRegsKind::Used
)
1182 .Case("all-gpr-arg", ZeroCallUsedRegsKind::AllGPRArg
)
1183 .Case("all-gpr", ZeroCallUsedRegsKind::AllGPR
)
1184 .Case("all-arg", ZeroCallUsedRegsKind::AllArg
)
1185 .Case("all", ZeroCallUsedRegsKind::All
);
1187 if (ZeroRegsKind
== ZeroCallUsedRegsKind::Skip
)
1190 const bool OnlyGPR
= static_cast<unsigned>(ZeroRegsKind
) & ONLY_GPR
;
1191 const bool OnlyUsed
= static_cast<unsigned>(ZeroRegsKind
) & ONLY_USED
;
1192 const bool OnlyArg
= static_cast<unsigned>(ZeroRegsKind
) & ONLY_ARG
;
1194 const TargetRegisterInfo
&TRI
= *MF
.getSubtarget().getRegisterInfo();
1195 const BitVector
AllocatableSet(TRI
.getAllocatableSet(MF
));
1197 // Mark all used registers.
1198 BitVector
UsedRegs(TRI
.getNumRegs());
1200 for (const MachineBasicBlock
&MBB
: MF
)
1201 for (const MachineInstr
&MI
: MBB
)
1202 for (const MachineOperand
&MO
: MI
.operands()) {
1206 MCRegister Reg
= MO
.getReg();
1207 if (AllocatableSet
[Reg
] && !MO
.isImplicit() &&
1208 (MO
.isDef() || MO
.isUse()))
1212 BitVector
RegsToZero(TRI
.getNumRegs());
1213 for (MCRegister Reg
: AllocatableSet
.set_bits()) {
1214 // Skip over fixed registers.
1215 if (TRI
.isFixedRegister(MF
, Reg
))
1218 // Want only general purpose registers.
1219 if (OnlyGPR
&& !TRI
.isGeneralPurposeRegister(MF
, Reg
))
1222 // Want only used registers.
1223 if (OnlyUsed
&& !UsedRegs
[Reg
])
1226 // Want only registers used for arguments.
1227 if (OnlyArg
&& !TRI
.isArgumentRegister(MF
, Reg
))
1230 RegsToZero
.set(Reg
);
1233 // Remove registers that are live when leaving the function.
1234 for (const MachineBasicBlock
&MBB
: MF
)
1235 for (const MachineInstr
&MI
: MBB
.terminators()) {
1239 for (const auto &MO
: MI
.operands()) {
1243 for (MCPhysReg SReg
: TRI
.sub_and_superregs_inclusive(MO
.getReg()))
1244 RegsToZero
.reset(SReg
);
1248 const TargetFrameLowering
&TFI
= *MF
.getSubtarget().getFrameLowering();
1249 for (MachineBasicBlock
&MBB
: MF
)
1250 if (MBB
.isReturnBlock())
1251 TFI
.emitZeroCallUsedRegs(RegsToZero
, MBB
);
1254 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
1255 /// register references and actual offsets.
1256 void PEI::replaceFrameIndices(MachineFunction
&MF
) {
1257 const auto &ST
= MF
.getSubtarget();
1258 const TargetFrameLowering
&TFI
= *ST
.getFrameLowering();
1259 if (!TFI
.needsFrameIndexResolution(MF
))
1262 const TargetRegisterInfo
*TRI
= ST
.getRegisterInfo();
1264 // Allow the target to determine this after knowing the frame size.
1265 FrameIndexEliminationScavenging
= (RS
&& !FrameIndexVirtualScavenging
) ||
1266 TRI
->requiresFrameIndexReplacementScavenging(MF
);
1268 // Store SPAdj at exit of a basic block.
1269 SmallVector
<int, 8> SPState
;
1270 SPState
.resize(MF
.getNumBlockIDs());
1271 df_iterator_default_set
<MachineBasicBlock
*> Reachable
;
1273 // Iterate over the reachable blocks in DFS order.
1274 for (auto DFI
= df_ext_begin(&MF
, Reachable
), DFE
= df_ext_end(&MF
, Reachable
);
1275 DFI
!= DFE
; ++DFI
) {
1277 // Check the exit state of the DFS stack predecessor.
1278 if (DFI
.getPathLength() >= 2) {
1279 MachineBasicBlock
*StackPred
= DFI
.getPath(DFI
.getPathLength() - 2);
1280 assert(Reachable
.count(StackPred
) &&
1281 "DFS stack predecessor is already visited.\n");
1282 SPAdj
= SPState
[StackPred
->getNumber()];
1284 MachineBasicBlock
*BB
= *DFI
;
1285 replaceFrameIndices(BB
, MF
, SPAdj
);
1286 SPState
[BB
->getNumber()] = SPAdj
;
1289 // Handle the unreachable blocks.
1290 for (auto &BB
: MF
) {
1291 if (Reachable
.count(&BB
))
1292 // Already handled in DFS traversal.
1295 replaceFrameIndices(&BB
, MF
, SPAdj
);
1299 void PEI::replaceFrameIndices(MachineBasicBlock
*BB
, MachineFunction
&MF
,
1301 assert(MF
.getSubtarget().getRegisterInfo() &&
1302 "getRegisterInfo() must be implemented!");
1303 const TargetInstrInfo
&TII
= *MF
.getSubtarget().getInstrInfo();
1304 const TargetRegisterInfo
&TRI
= *MF
.getSubtarget().getRegisterInfo();
1305 const TargetFrameLowering
*TFI
= MF
.getSubtarget().getFrameLowering();
1307 if (RS
&& FrameIndexEliminationScavenging
)
1308 RS
->enterBasicBlock(*BB
);
1310 bool InsideCallSequence
= false;
1312 for (MachineBasicBlock::iterator I
= BB
->begin(); I
!= BB
->end(); ) {
1313 if (TII
.isFrameInstr(*I
)) {
1314 InsideCallSequence
= TII
.isFrameSetup(*I
);
1315 SPAdj
+= TII
.getSPAdjust(*I
);
1316 I
= TFI
->eliminateCallFramePseudoInstr(MF
, *BB
, I
);
1320 MachineInstr
&MI
= *I
;
1322 bool DidFinishLoop
= true;
1323 for (unsigned i
= 0, e
= MI
.getNumOperands(); i
!= e
; ++i
) {
1324 if (!MI
.getOperand(i
).isFI())
1327 // Frame indices in debug values are encoded in a target independent
1328 // way with simply the frame index and offset rather than any
1329 // target-specific addressing mode.
1330 if (MI
.isDebugValue()) {
1331 MachineOperand
&Op
= MI
.getOperand(i
);
1333 MI
.isDebugOperand(&Op
) &&
1334 "Frame indices can only appear as a debug operand in a DBG_VALUE*"
1335 " machine instruction");
1337 unsigned FrameIdx
= Op
.getIndex();
1338 unsigned Size
= MF
.getFrameInfo().getObjectSize(FrameIdx
);
1340 StackOffset Offset
=
1341 TFI
->getFrameIndexReference(MF
, FrameIdx
, Reg
);
1342 Op
.ChangeToRegister(Reg
, false /*isDef*/);
1344 const DIExpression
*DIExpr
= MI
.getDebugExpression();
1346 // If we have a direct DBG_VALUE, and its location expression isn't
1347 // currently complex, then adding an offset will morph it into a
1348 // complex location that is interpreted as being a memory address.
1349 // This changes a pointer-valued variable to dereference that pointer,
1350 // which is incorrect. Fix by adding DW_OP_stack_value.
1352 if (MI
.isNonListDebugValue()) {
1353 unsigned PrependFlags
= DIExpression::ApplyOffset
;
1354 if (!MI
.isIndirectDebugValue() && !DIExpr
->isComplex())
1355 PrependFlags
|= DIExpression::StackValue
;
1357 // If we have DBG_VALUE that is indirect and has a Implicit location
1358 // expression need to insert a deref before prepending a Memory
1359 // location expression. Also after doing this we change the DBG_VALUE
1361 if (MI
.isIndirectDebugValue() && DIExpr
->isImplicit()) {
1362 SmallVector
<uint64_t, 2> Ops
= {dwarf::DW_OP_deref_size
, Size
};
1363 bool WithStackValue
= true;
1364 DIExpr
= DIExpression::prependOpcodes(DIExpr
, Ops
, WithStackValue
);
1365 // Make the DBG_VALUE direct.
1366 MI
.getDebugOffset().ChangeToRegister(0, false);
1368 DIExpr
= TRI
.prependOffsetExpression(DIExpr
, PrependFlags
, Offset
);
1370 // The debug operand at DebugOpIndex was a frame index at offset
1371 // `Offset`; now the operand has been replaced with the frame
1372 // register, we must add Offset with `register x, plus Offset`.
1373 unsigned DebugOpIndex
= MI
.getDebugOperandIndex(&Op
);
1374 SmallVector
<uint64_t, 3> Ops
;
1375 TRI
.getOffsetOpcodes(Offset
, Ops
);
1376 DIExpr
= DIExpression::appendOpsToArg(DIExpr
, Ops
, DebugOpIndex
);
1378 MI
.getDebugExpressionOp().setMetadata(DIExpr
);
1380 } else if (MI
.isDebugPHI()) {
1381 // Allow stack ref to continue onwards.
1385 // TODO: This code should be commoned with the code for
1386 // PATCHPOINT. There's no good reason for the difference in
1387 // implementation other than historical accident. The only
1388 // remaining difference is the unconditional use of the stack
1389 // pointer as the base register.
1390 if (MI
.getOpcode() == TargetOpcode::STATEPOINT
) {
1391 assert((!MI
.isDebugValue() || i
== 0) &&
1392 "Frame indicies can only appear as the first operand of a "
1393 "DBG_VALUE machine instruction");
1395 MachineOperand
&Offset
= MI
.getOperand(i
+ 1);
1396 StackOffset refOffset
= TFI
->getFrameIndexReferencePreferSP(
1397 MF
, MI
.getOperand(i
).getIndex(), Reg
, /*IgnoreSPUpdates*/ false);
1398 assert(!refOffset
.getScalable() &&
1399 "Frame offsets with a scalable component are not supported");
1400 Offset
.setImm(Offset
.getImm() + refOffset
.getFixed() + SPAdj
);
1401 MI
.getOperand(i
).ChangeToRegister(Reg
, false /*isDef*/);
1405 // Some instructions (e.g. inline asm instructions) can have
1406 // multiple frame indices and/or cause eliminateFrameIndex
1407 // to insert more than one instruction. We need the register
1408 // scavenger to go through all of these instructions so that
1409 // it can update its register information. We keep the
1410 // iterator at the point before insertion so that we can
1411 // revisit them in full.
1412 bool AtBeginning
= (I
== BB
->begin());
1413 if (!AtBeginning
) --I
;
1415 // If this instruction has a FrameIndex operand, we need to
1416 // use that target machine register info object to eliminate
1418 TRI
.eliminateFrameIndex(MI
, SPAdj
, i
,
1419 FrameIndexEliminationScavenging
? RS
: nullptr);
1421 // Reset the iterator if we were at the beginning of the BB.
1427 DidFinishLoop
= false;
1431 // If we are looking at a call sequence, we need to keep track of
1432 // the SP adjustment made by each instruction in the sequence.
1433 // This includes both the frame setup/destroy pseudos (handled above),
1434 // as well as other instructions that have side effects w.r.t the SP.
1435 // Note that this must come after eliminateFrameIndex, because
1436 // if I itself referred to a frame index, we shouldn't count its own
1438 if (DidFinishLoop
&& InsideCallSequence
)
1439 SPAdj
+= TII
.getSPAdjust(MI
);
1441 if (DoIncr
&& I
!= BB
->end()) ++I
;
1443 // Update register states.
1444 if (RS
&& FrameIndexEliminationScavenging
&& DidFinishLoop
)