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//===----------------------------------------------------------------------===//
70 #define DEBUG_TYPE "prologepilog"
74 STATISTIC(NumLeafFuncWithSpills,
"Number of leaf functions with CSRs");
75 STATISTIC(NumFuncSeen,
"Number of functions seen in PEI");
83 // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved
84 // stack frame indexes.
85 unsigned MinCSFrameIndex = std::numeric_limits<unsigned>::max();
86 unsigned MaxCSFrameIndex = 0;
88 // Save and Restore blocks of the current function. Typically there is a
89 // single save block, unless Windows EH funclets are involved.
93 // Flag to control whether to use the register scavenger to resolve
94 // frame index materialization registers. Set according to
95 // TRI->requiresFrameIndexScavenging() for the current function.
96 bool FrameIndexVirtualScavenging =
false;
98 // Flag to control whether the scavenger should be passed even though
99 // FrameIndexVirtualScavenging is used.
100 bool FrameIndexEliminationScavenging =
false;
113 // Frame indices in debug values are encoded in a target independent
114 // way with simply the frame index and offset rather than any
115 // target-specific addressing mode.
117 unsigned OpIdx,
int SPAdj = 0);
118 // Does same as replaceFrameIndices but using the backward MIR walk and
119 // backward register scavenger walk.
129 bool run(MachineFunction &MF);
136 PEILegacy() : MachineFunctionPass(ID) {
140 void getAnalysisUsage(AnalysisUsage &AU)
const override;
142 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
143 /// frame indexes with appropriate references.
144 bool runOnMachineFunction(MachineFunction &MF)
override;
147}
// end anonymous namespace
149char PEILegacy::ID = 0;
159 "Prologue/Epilogue Insertion & Frame Finalization",
false,
163 return new PEILegacy();
167 "Number of bytes used for stack in all functions");
177/// StackObjSet - A set of stack object indexes
183/// Stash DBG_VALUEs that describe parameters and which are placed at the start
184/// of the block. Later on, after the prologue code has been emitted, the
185/// stashed DBG_VALUEs will be reinserted at the start of the block.
190 for (
auto &
MI :
MBB) {
191 if (!
MI.isDebugInstr())
193 if (!
MI.isDebugValue() || !
MI.getDebugVariable()->isParameter())
197 // We can only emit valid locations for frame indices after the frame
198 // setup, so do not stash away them.
205 return Var == DV->getDebugVariable() &&
208 // See if the debug value overlaps with any preceding debug value that will
209 // not be stashed. If that is the case, then we can't stash this value, as
210 // we would then reorder the values at reinsertion.
212 EntryDbgValues[&
MBB].push_back(&
MI);
215 // Remove stashed debug values from the block.
216 if (
auto It = EntryDbgValues.find(&
MBB); It != EntryDbgValues.end())
217 for (
auto *
MI : It->second)
218 MI->removeFromParent();
221bool PEIImpl::run(MachineFunction &MF) {
227 RS =
TRI->requiresRegisterScavenging(MF) ?
new RegScavenger() : nullptr;
228 FrameIndexVirtualScavenging =
TRI->requiresFrameIndexScavenging(MF);
230 // Spill frame pointer and/or base pointer registers if they are clobbered.
231 // It is placed before call frame instruction elimination so it will not mess
232 // with stack arguments.
235 // Calculate the MaxCallFrameSize value for the function's frame
236 // information. Also eliminates call frame pseudo instructions.
237 calculateCallFrameInfo(MF);
239 // Determine placement of CSR spill/restore code and prolog/epilog code:
240 // place all spills in the entry block, all restores in return blocks.
241 calculateSaveRestoreBlocks(MF);
243 // Stash away DBG_VALUEs that should not be moved by insertion of prolog code.
245 for (MachineBasicBlock *SaveBlock : SaveBlocks)
248 // Handle CSR spilling and restoring, for targets that need it.
250 spillCalleeSavedRegs(MF);
252 // Allow the target machine to make final modifications to the function
253 // before the frame layout is finalized.
256 // Calculate actual frame offsets for all abstract stack objects...
257 calculateFrameObjectOffsets(MF);
259 // Add prolog and epilog code to the function. This function is required
260 // to align the stack frame as necessary for any stack variables or
261 // called functions. Because of this, calculateCalleeSavedRegisters()
262 // must be called before this function in order to set the AdjustsStack
263 // and MaxCallFrameSize variables.
264 if (!
F.hasFnAttribute(Attribute::Naked))
265 insertPrologEpilogCode(MF);
267 // Reinsert stashed debug values at the start of the entry blocks.
268 for (
auto &
I : EntryDbgValues)
269 I.first->insert(
I.first->begin(),
I.second.begin(),
I.second.end());
271 // Allow the target machine to make final modifications to the function
272 // before the frame layout is finalized.
275 // Replace all MO_FrameIndex operands with physical register references
276 // and actual offsets.
278 // Allow the target to determine this after knowing the frame size.
279 FrameIndexEliminationScavenging =
280 (RS && !FrameIndexVirtualScavenging) ||
281 TRI->requiresFrameIndexReplacementScavenging(MF);
283 if (
TRI->eliminateFrameIndicesBackwards())
284 replaceFrameIndicesBackward(MF);
286 replaceFrameIndices(MF);
289 // If register scavenging is needed, as we've enabled doing it as a
290 // post-pass, scavenge the virtual registers that frame index elimination
292 if (
TRI->requiresRegisterScavenging(MF) && FrameIndexVirtualScavenging)
295 // Warn on stack size when we exceeds the given limit.
305 // Verifier should have caught this.
306 assert(!
Failed &&
"Invalid warn-stack-size fn attr value");
311 StackSize += UnsafeStackSize;
313 if (StackSize > Threshold) {
314 DiagnosticInfoStackSize DiagStackSize(
F, StackSize, Threshold,
DS_Warning);
315 F.getContext().diagnose(DiagStackSize);
316 int64_t SpillSize = 0;
323 [[maybe_unused]]
float SpillPct =
324 static_cast<float>(SpillSize) /
static_cast<float>(StackSize);
326 dbgs() <<
formatv(
"{0}/{1} ({3:P}) spills, {2}/{1} ({4:P}) variables",
327 SpillSize, StackSize, StackSize - SpillSize, SpillPct,
329 if (UnsafeStackSize != 0) {
332 static_cast<float>(UnsafeStackSize) /
333 static_cast<float>(StackSize),
340 return MachineOptimizationRemarkAnalysis(
DEBUG_TYPE,
"StackSize",
343 <<
ore::NV(
"NumStackBytes", StackSize)
344 <<
" stack bytes in function '"
348 // Emit any remarks implemented for the target, based on final frame layout.
353 RestoreBlocks.
clear();
359/// runOnMachineFunction - Insert prolog/epilog code and replace abstract
360/// frame indexes with appropriate references.
361bool PEILegacy::runOnMachineFunction(MachineFunction &MF) {
362 MachineOptimizationRemarkEmitter *ORE =
363 &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
364 return PEIImpl(ORE).run(MF);
372 if (!PEIImpl(&ORE).
run(MF))
377 .preserve<MachineDominatorTreeAnalysis>()
381/// Calculate the MaxCallFrameSize variable for the function's frame
382/// information and eliminate call frame pseudo instructions.
388 // Get the function call frame set-up and tear-down instruction opcode
389 unsigned FrameSetupOpcode =
TII.getCallFrameSetupOpcode();
390 unsigned FrameDestroyOpcode =
TII.getCallFrameDestroyOpcode();
392 // Early exit for targets which have no call frame setup/destroy pseudo
394 if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
397 // (Re-)Compute the MaxCallFrameSize.
398 [[maybe_unused]]
uint64_t MaxCFSIn =
400 std::vector<MachineBasicBlock::iterator> FrameSDOps;
403 "Recomputing MaxCFS gave a larger value.");
405 "AdjustsStack not set in presence of a frame pseudo instruction.");
408 // If call frames are not being included as part of the stack frame, and
409 // the target doesn't indicate otherwise, remove the call frame pseudos
410 // here. The sub/add sp instruction pairs are still inserted, but we don't
411 // need to track the SP adjustment for frame index elimination.
415 // We can't track the call frame size after call frame pseudos have been
416 // eliminated. Set it to zero everywhere to keep MachineVerifier happy.
418 MBB.setCallFrameSize(0);
422/// Compute the sets of entry and return blocks for saving and restoring
423/// callee-saved registers, and placing prolog and epilog code.
424void PEIImpl::calculateSaveRestoreBlocks(MachineFunction &MF) {
426 // Even when we do not change any CSR, we still want to insert the
427 // prologue and epilogue of the function.
428 // So set the save points for those.
430 // Use the points found by shrink-wrapping, if any.
433 "Multiple save points are not yet supported!");
435 SaveBlocks.push_back(SavePoint.first);
437 "Multiple restore points are not yet supported!");
439 MachineBasicBlock *RestoreBlock = RestorePoint.first;
440 // If RestoreBlock does not have any successor and is not a return block
441 // then the end point is unreachable and we do not need to insert any
448 // Save refs to entry and return blocks.
449 SaveBlocks.push_back(&MF.
front());
450 for (MachineBasicBlock &
MBB : MF) {
452 SaveBlocks.push_back(&
MBB);
460 unsigned &MinCSFrameIndex,
461 unsigned &MaxCSFrameIndex) {
462 if (SavedRegs.
empty())
466 const MCPhysReg *CSRegs =
F.getRegInfo().getCalleeSavedRegs();
469 for (
unsigned i = 0; CSRegs[i]; ++i)
470 CSMask.
set(CSRegs[i]);
472 std::vector<CalleeSavedInfo> CSI;
473 for (
unsigned i = 0; CSRegs[i]; ++i) {
474 unsigned Reg = CSRegs[i];
476 bool SavedSuper =
false;
478 // Some backends set all aliases for some registers as saved, such as
479 // Mips's $fp, so they appear in SavedRegs but not CSRegs.
480 if (SavedRegs.
test(SuperReg) && CSMask.
test(SuperReg)) {
495 // If target doesn't implement this, use generic code.
498 return;
// Early exit if no callee saved registers are modified!
500 unsigned NumFixedSpillSlots;
504 // Now that we know which registers need to be saved and restored, allocate
505 // stack slots for them.
506 for (
auto &CS : CSI) {
507 // If the target has spilled this register to another register or already
508 // handled it , we don't need to allocate a stack slot.
509 if (CS.isSpilledToReg())
516 if (
RegInfo->hasReservedSpillSlot(
F,
Reg, FrameIdx)) {
517 CS.setFrameIdx(FrameIdx);
521 // Check to see if this physreg must be spilled to a particular stack slot
524 while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots &&
529 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
530 // Nope, just spill it anywhere convenient.
532 // We may not be able to satisfy the desired alignment specification of
533 // the TargetRegisterClass if the stack alignment is smaller. Use the
537 if ((
unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
538 if ((
unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
540 // Spill it to the stack where we must.
544 CS.setFrameIdx(FrameIdx);
551/// Helper function to update the liveness information for the callee-saved
555 // Visited will contain all the basic blocks that are in the region
556 // where the callee saved registers are alive:
557 // - Anything that is not Save or Restore -> LiveThrough.
559 // - Restore -> LiveOut.
560 // The live-out is not attached to the block, so no need to keep
561 // Restore in this set.
567 "Multiple save points not yet supported!");
582 "Multiple restore points not yet supported!");
587 // By construction Restore cannot be visited, otherwise it
588 // means there exists a path to Restore that does not go
592 while (!WorkList.
empty()) {
594 // By construction, the region that is after the save point is
595 // dominated by the Save and post-dominated by the Restore.
596 if (CurBB == Save && Save != Restore)
598 // Enqueue all the successors not already visited.
599 // Those are by construction either before Save or after Restore.
601 if (Visited.
insert(SuccBB).second)
611 // Add the callee-saved register as live-in.
612 // It's killed at the spill.
616 // If callee-saved register is spilled to another register rather than
617 // spilling to stack, the destination register has to be marked as live for
618 // each MBB between the prologue and epilogue so that it is not clobbered
619 // before it is reloaded in the epilogue. The Visited set contains all
620 // blocks outside of the region delimited by prologue/epilogue.
621 if (
I.isSpilledToReg()) {
623 if (Visited.count(&
MBB))
626 if (!
MBB.isLiveIn(DstReg))
627 MBB.addLiveIn(DstReg);
633/// Insert spill code for the callee-saved registers used in the function.
649/// Insert restore code for the callee-saved registers used in the function.
651 std::vector<CalleeSavedInfo> &CSI) {
657 // Restore all registers immediately before the return and any
658 // terminators that precede it.
668void PEIImpl::spillCalleeSavedRegs(MachineFunction &MF) {
669 // We can't list this requirement in getRequiredProperties because some
670 // targets (WebAssembly) use virtual registers past this point, and the pass
671 // pipeline is set up without giving the passes a chance to look at the
673 // FIXME: Find a way to express this in getRequiredProperties.
679 MinCSFrameIndex = std::numeric_limits<unsigned>::max();
682 // Determine which of the registers in the callee save list should be saved.
686 // Assign stack slots for any callee-saved registers that must be spilled.
689 // Add the code to save and restore the callee saved registers.
690 if (!
F.hasFnAttribute(Attribute::Naked)) {
695 // Fill SavePoints and RestorePoints with CalleeSavedRegisters
699 SaveRestorePts.insert({SavePoint.first, CSI});
702 SaveRestorePts.clear();
704 SaveRestorePts.insert({RestorePoint.first, CSI});
710 NumLeafFuncWithSpills++;
712 for (MachineBasicBlock *SaveBlock : SaveBlocks)
715 // Update the live-in information of all the blocks up to the save point.
718 for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
724/// AdjustStackOffset - Helper function used to adjust the stack frame offset.
726 bool StackGrowsDown, int64_t &
Offset,
728 // If the stack grows down, add the object size to find the lowest address.
734 // If the alignment of this object is greater than that of the stack, then
735 // increase the stack alignment to match.
736 MaxAlign = std::max(MaxAlign, Alignment);
738 // Adjust to alignment boundary.
741 if (StackGrowsDown) {
753/// Compute which bytes of fixed and callee-save stack area are unused and keep
754/// track of them in StackBytesFree.
757 unsigned MinCSFrameIndex,
unsigned MaxCSFrameIndex,
758 int64_t FixedCSEnd,
BitVector &StackBytesFree) {
759 // Avoid undefined int64_t -> int conversion below in extreme case.
760 if (FixedCSEnd > std::numeric_limits<int>::max())
763 StackBytesFree.
resize(FixedCSEnd,
true);
766 // Add fixed objects.
768 // StackSlot scavenging is only implemented for the default stack.
771 // Add callee-save objects if there are any.
772 if (MinCSFrameIndex <= MaxCSFrameIndex) {
773 for (
int i = MinCSFrameIndex; i <= (int)MaxCSFrameIndex; ++i)
778 for (
int i : AllocatedFrameSlots) {
779 // These are converted from int64_t, but they should always fit in int
780 // because of the FixedCSEnd check above.
783 int ObjStart, ObjEnd;
784 if (StackGrowsDown) {
785 // ObjOffset is negative when StackGrowsDown is true.
786 ObjStart = -ObjOffset - ObjSize;
789 ObjStart = ObjOffset;
790 ObjEnd = ObjOffset + ObjSize;
792 // Ignore fixed holes that are in the previous stack frame.
794 StackBytesFree.
reset(ObjStart, ObjEnd);
798/// Assign frame object to an unused portion of the stack in the fixed stack
799/// object range. Return true if the allocation was successful.
801 bool StackGrowsDown,
Align MaxAlign,
806 if (StackBytesFree.
none()) {
807 // clear it to speed up later scavengeStackSlot calls to
808 // StackBytesFree.none()
809 StackBytesFree.
clear();
814 if (ObjAlign > MaxAlign)
819 for (FreeStart = StackBytesFree.
find_first(); FreeStart != -1;
820 FreeStart = StackBytesFree.
find_next(FreeStart)) {
822 // Check that free space has suitable alignment.
823 unsigned ObjStart = StackGrowsDown ? FreeStart + ObjSize : FreeStart;
824 if (
alignTo(ObjStart, ObjAlign) != ObjStart)
827 if (FreeStart + ObjSize > StackBytesFree.
size())
830 bool AllBytesFree =
true;
831 for (
unsigned Byte = 0; Byte < ObjSize; ++Byte)
832 if (!StackBytesFree.
test(FreeStart + Byte)) {
833 AllBytesFree =
false;
843 if (StackGrowsDown) {
844 int ObjStart = -(FreeStart + ObjSize);
845 LLVM_DEBUG(
dbgs() <<
"alloc FI(" << FrameIdx <<
") scavenged at SP["
846 << ObjStart <<
"]\n");
849 LLVM_DEBUG(
dbgs() <<
"alloc FI(" << FrameIdx <<
") scavenged at SP["
850 << FreeStart <<
"]\n");
854 StackBytesFree.
reset(FreeStart, FreeStart + ObjSize);
858/// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
859/// those required to be close to the Stack Protector) to stack offsets.
865 for (
int i : UnassignedObjs) {
871/// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
872/// abstract stack objects.
873void PEIImpl::calculateFrameObjectOffsets(MachineFunction &MF) {
876 bool StackGrowsDown =
879 // Loop over all of the stack objects, assigning sequential addresses...
882 // Start at the beginning of the local area.
883 // The Offset is the distance from the stack top in the direction
884 // of stack growth -- so it's always nonnegative.
887 LocalAreaOffset = -LocalAreaOffset;
888 assert(LocalAreaOffset >= 0
889 &&
"Local area offset should be in direction of stack growth");
890 int64_t
Offset = LocalAreaOffset;
892#ifdef EXPENSIVE_CHECKS
897 "MaxAlignment is invalid");
900 // If there are fixed sized objects that are preallocated in the local area,
901 // non-fixed objects can't be allocated right at the start of local area.
902 // Adjust 'Offset' to point to the end of last fixed sized preallocated
905 // Only allocate objects on the default stack.
910 if (StackGrowsDown) {
911 // The maximum distance from the stack pointer is at lower address of
912 // the object -- which is given by offset. For down growing stack
913 // the offset is negative, so we negate the offset to get the distance.
916 // The maximum distance from the start pointer is at the upper
917 // address of the object.
924 // First assign frame offsets to stack objects that are used to spill
925 // callee saved registers.
926 if (MaxCSFrameIndex >= MinCSFrameIndex) {
927 for (
unsigned i = 0; i <= MaxCSFrameIndex - MinCSFrameIndex; ++i) {
929 StackGrowsDown ? MinCSFrameIndex + i : MaxCSFrameIndex - i;
931 // Only allocate objects on the default stack.
935 // TODO: should this just be if (MFI.isDeadObjectIndex(FrameIndex))
944 "MFI.getMaxAlign should already account for all callee-saved "
945 "registers without a fixed stack slot");
947 // FixedCSEnd is the stack offset to the end of the fixed and callee-save
949 int64_t FixedCSEnd =
Offset;
951 // Make sure the special register scavenging spill slot is closest to the
952 // incoming stack pointer if a frame pointer is required and is closer
953 // to the incoming rather than the final stack pointer.
956 if (RS && EarlyScavengingSlots) {
957 SmallVector<int, 2> SFIs;
963 // FIXME: Once this is working, then enable flag will change to a target
964 // check for whether the frame is large enough to want to use virtual
965 // frame index registers. Functions which don't want/need this optimization
966 // will continue to use the existing code path.
970 // Adjust to alignment boundary.
975 // Resolve offsets for objects in the local block.
983 // Allocate the local block
986 MaxAlign = std::max(Alignment, MaxAlign);
989 // Retrieve the Exception Handler registration node.
990 int EHRegNodeFrameIndex = std::numeric_limits<int>::max();
992 EHRegNodeFrameIndex = FuncInfo->EHRegNodeFrameIndex;
994 // Make sure that the stack protector comes before the local variables on the
996 SmallSet<int, 16> ProtectedObjs;
1003 // If we need a stack protector, we need to make sure that
1004 // LocalStackSlotPass didn't already allocate a slot for it.
1005 // If we are told to use the LocalStackAllocationBlock, the stack protector
1006 // is expected to be already pre-allocated.
1008 // If the stack protector isn't on the default stack then it's up to the
1009 // target to set the stack offset.
1011 "Offset of stack protector on non-default stack expected to be "
1014 "Stack protector on non-default stack expected to not be "
1015 "pre-allocated by LocalStackSlotPass.");
1021 "Stack protector not pre-allocated by LocalStackSlotPass.");
1024 // Assign large stack objects first.
1028 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
1034 if (StackProtectorFI == (
int)i || EHRegNodeFrameIndex == (
int)i)
1036 // Only allocate objects on the default stack.
1044 SmallArrayObjs.
insert(i);
1050 LargeArrayObjs.
insert(i);
1056 // We expect **all** the protected stack objects to be pre-allocated by
1057 // LocalStackSlotPass. If it turns out that PEI still has to allocate some
1058 // of them, we may end up messing up the expected order of the objects.
1060 !(LargeArrayObjs.
empty() && SmallArrayObjs.
empty() &&
1061 AddrOfObjs.
empty()))
1063 "LocalStackSlotPass.");
1073 SmallVector<int, 8> ObjectsToAllocate;
1075 // Then prepare to assign frame offsets to stack objects that are not used to
1076 // spill callee saved registers.
1080 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
1088 if (ProtectedObjs.
count(i))
1090 // Only allocate objects on the default stack.
1094 // Add the objects that we need to allocate to our working set.
1098 // Allocate the EH registration node first if one is present.
1099 if (EHRegNodeFrameIndex != std::numeric_limits<int>::max())
1103 // Give the targets a chance to order the objects the way they like it.
1108 // Keep track of which bytes in the fixed and callee-save range are used so we
1109 // can use the holes when allocating later stack objects. Only do this if
1110 // stack protector isn't being used and the target requests it and we're
1112 BitVector StackBytesFree;
1113 if (!ObjectsToAllocate.
empty() &&
1117 FixedCSEnd, StackBytesFree);
1119 // Now walk the objects and actually assign base offsets to them.
1120 for (
auto &Object : ObjectsToAllocate)
1125 // Make sure the special register scavenging spill slot is closest to the
1127 if (RS && !EarlyScavengingSlots) {
1128 SmallVector<int, 2> SFIs;
1130 for (
int SFI : SFIs)
1135 // If we have reserved argument space for call sites in the function
1136 // immediately on entry to the current function, count it as part of the
1137 // overall stack size.
1141 // Round up the size to a multiple of the alignment. If the function has
1142 // any calls or alloca's, align to the target's StackAlignment value to
1143 // ensure that the callee's frame or the alloca data is suitably aligned;
1144 // otherwise, for leaf functions, align to the TransientStackAlignment
1153 // If the frame pointer is eliminated, all frame offsets will be relative to
1154 // SP not FP. Align to MaxAlign so this works.
1155 StackAlign = std::max(StackAlign, MaxAlign);
1156 int64_t OffsetBeforeAlignment =
Offset;
1159 // If we have increased the offset to fulfill the alignment constrants,
1160 // then the scavenging spill slots may become harder to reach from the
1161 // stack pointer, float them so they stay close.
1162 if (StackGrowsDown && OffsetBeforeAlignment !=
Offset && RS &&
1163 !EarlyScavengingSlots) {
1164 SmallVector<int, 2> SFIs;
1167 <<
"Adjusting emergency spill slots!\n";);
1168 int64_t Delta =
Offset - OffsetBeforeAlignment;
1169 for (
int SFI : SFIs) {
1171 <<
"Adjusting offset of emergency spill slot #" << SFI
1179 // Update frame info to pretend that this is part of the stack...
1180 int64_t StackSize =
Offset - LocalAreaOffset;
1182 NumBytesStackSpace += StackSize;
1185/// insertPrologEpilogCode - Scan the function for modified callee saved
1186/// registers, insert spill code for these callee saved registers, then add
1187/// prolog and epilog code to the function.
1188void PEIImpl::insertPrologEpilogCode(MachineFunction &MF) {
1191 // Add prologue to the function...
1192 for (MachineBasicBlock *SaveBlock : SaveBlocks)
1195 // Add epilogue to restore the callee-save registers in each exiting block.
1196 for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
1199 // Zero call used registers before restoring callee-saved registers.
1200 insertZeroCallUsedRegs(MF);
1202 for (MachineBasicBlock *SaveBlock : SaveBlocks)
1205 // Emit additional code that is required to support segmented stacks, if
1206 // we've been asked for it. This, when linked with a runtime with support
1207 // for segmented stacks (libgcc is one), will result in allocating stack
1208 // space in small chunks instead of one large contiguous block.
1210 for (MachineBasicBlock *SaveBlock : SaveBlocks)
1214 // Emit additional code that is required to explicitly handle the stack in
1215 // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
1216 // approach is rather similar to that of Segmented Stacks, but it uses a
1217 // different conditional check and another BIF for allocating more stack
1220 for (MachineBasicBlock *SaveBlock : SaveBlocks)
1224/// insertZeroCallUsedRegs - Zero out call used registers.
1225void PEIImpl::insertZeroCallUsedRegs(MachineFunction &MF) {
1228 if (!
F.hasFnAttribute(
"zero-call-used-regs"))
1231 using namespace ZeroCallUsedRegs;
1234 StringSwitch<ZeroCallUsedRegsKind>(
1235 F.getFnAttribute(
"zero-call-used-regs").getValueAsString())
1236 .Case(
"skip", ZeroCallUsedRegsKind::Skip)
1237 .Case(
"used-gpr-arg", ZeroCallUsedRegsKind::UsedGPRArg)
1238 .Case(
"used-gpr", ZeroCallUsedRegsKind::UsedGPR)
1239 .Case(
"used-arg", ZeroCallUsedRegsKind::UsedArg)
1240 .Case(
"used", ZeroCallUsedRegsKind::Used)
1241 .Case(
"all-gpr-arg", ZeroCallUsedRegsKind::AllGPRArg)
1242 .Case(
"all-gpr", ZeroCallUsedRegsKind::AllGPR)
1243 .Case(
"all-arg", ZeroCallUsedRegsKind::AllArg)
1244 .Case(
"all", ZeroCallUsedRegsKind::All);
1246 if (ZeroRegsKind == ZeroCallUsedRegsKind::Skip)
1249 const bool OnlyGPR =
static_cast<unsigned>(ZeroRegsKind) & ONLY_GPR;
1250 const bool OnlyUsed =
static_cast<unsigned>(ZeroRegsKind) & ONLY_USED;
1251 const bool OnlyArg =
static_cast<unsigned>(ZeroRegsKind) & ONLY_ARG;
1254 const BitVector AllocatableSet(
TRI.getAllocatableSet(MF));
1256 // Mark all used registers.
1257 BitVector UsedRegs(
TRI.getNumRegs());
1259 for (
const MachineBasicBlock &
MBB : MF)
1260 for (
const MachineInstr &
MI :
MBB) {
1261 // skip debug instructions
1262 if (
MI.isDebugInstr())
1265 for (
const MachineOperand &MO :
MI.operands()) {
1269 MCRegister
Reg = MO.getReg();
1270 if (AllocatableSet[
Reg.
id()] && !MO.isImplicit() &&
1271 (MO.isDef() || MO.isUse()))
1272 UsedRegs.set(
Reg.
id());
1276 // Get a list of registers that are used.
1277 BitVector LiveIns(
TRI.getNumRegs());
1278 for (
const MachineBasicBlock::RegisterMaskPair &LI : MF.front().liveins())
1279 LiveIns.set(LI.PhysReg);
1281 BitVector RegsToZero(
TRI.getNumRegs());
1282 for (MCRegister
Reg : AllocatableSet.set_bits()) {
1283 // Skip over fixed registers.
1284 if (
TRI.isFixedRegister(MF,
Reg))
1287 // Want only general purpose registers.
1288 if (OnlyGPR && !
TRI.isGeneralPurposeRegister(MF,
Reg))
1291 // Want only used registers.
1292 if (OnlyUsed && !UsedRegs[
Reg.
id()])
1295 // Want only registers used for arguments.
1298 if (!LiveIns[
Reg.
id()])
1300 }
else if (!
TRI.isArgumentRegister(MF,
Reg)) {
1305 RegsToZero.set(
Reg.
id());
1308 // Don't clear registers that are live when leaving the function.
1309 for (
const MachineBasicBlock &
MBB : MF)
1314 for (
const auto &MO :
MI.operands()) {
1318 MCRegister
Reg = MO.getReg();
1322 // This picks up sibling registers (e.q. %al -> %ah).
1324 RegsToZero.reset(Unit);
1327 RegsToZero.reset(SReg);
1331 // Don't need to clear registers that are used/clobbered by terminating
1333 for (
const MachineBasicBlock &
MBB : MF) {
1340 for (
const MachineOperand &MO :
I->operands()) {
1344 MCRegister
Reg = MO.getReg();
1349 RegsToZero.reset(
Reg);
1354 // Don't clear registers that must be preserved.
1355 for (
const MCPhysReg *CSRegs =
TRI.getCalleeSavedRegs(&MF);
1357 for (MCRegister
Reg :
TRI.sub_and_superregs_inclusive(CSReg))
1358 RegsToZero.reset(
Reg.
id());
1360 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1361 for (MachineBasicBlock &
MBB : MF)
1366/// Replace all FrameIndex operands with physical register references and actual
1368void PEIImpl::replaceFrameIndicesBackward(MachineFunction &MF) {
1371 for (
auto &
MBB : MF) {
1374 // Get the SP adjustment for the end of MBB from the start of any of its
1375 // successors. They should all be the same.
1377 return Succ->getCallFrameSize() ==
1378 (*MBB.succ_begin())->getCallFrameSize();
1386 replaceFrameIndicesBackward(&
MBB, MF, SPAdj);
1388 // We can't track the call frame size after call frame pseudos have been
1389 // eliminated. Set it to zero everywhere to keep MachineVerifier happy.
1394/// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
1395/// register references and actual offsets.
1396void PEIImpl::replaceFrameIndices(MachineFunction &MF) {
1399 for (
auto &
MBB : MF) {
1404 replaceFrameIndices(&
MBB, MF, SPAdj);
1406 // We can't track the call frame size after call frame pseudos have been
1407 // eliminated. Set it to zero everywhere to keep MachineVerifier happy.
1412bool PEIImpl::replaceFrameIndexDebugInstr(MachineFunction &MF, MachineInstr &
MI,
1413 unsigned OpIdx,
int SPAdj) {
1416 if (
MI.isDebugValue()) {
1418 MachineOperand &
Op =
MI.getOperand(
OpIdx);
1420 "Frame indices can only appear as a debug operand in a DBG_VALUE*"
1421 " machine instruction");
1423 unsigned FrameIdx =
Op.getIndex();
1427 Op.ChangeToRegister(
Reg,
false /*isDef*/);
1429 const DIExpression *DIExpr =
MI.getDebugExpression();
1431 // If we have a direct DBG_VALUE, and its location expression isn't
1432 // currently complex, then adding an offset will morph it into a
1433 // complex location that is interpreted as being a memory address.
1434 // This changes a pointer-valued variable to dereference that pointer,
1435 // which is incorrect. Fix by adding DW_OP_stack_value.
1437 if (
MI.isNonListDebugValue()) {
1439 if (!
MI.isIndirectDebugValue() && !DIExpr->
isComplex())
1442 // If we have DBG_VALUE that is indirect and has a Implicit location
1443 // expression need to insert a deref before prepending a Memory
1444 // location expression. Also after doing this we change the DBG_VALUE
1446 if (
MI.isIndirectDebugValue() && DIExpr->
isImplicit()) {
1448 bool WithStackValue =
true;
1450 // Make the DBG_VALUE direct.
1451 MI.getDebugOffset().ChangeToRegister(0,
false);
1453 DIExpr =
TRI.prependOffsetExpression(DIExpr, PrependFlags,
Offset);
1455 // The debug operand at DebugOpIndex was a frame index at offset
1456 // `Offset`; now the operand has been replaced with the frame
1457 // register, we must add Offset with `register x, plus Offset`.
1458 unsigned DebugOpIndex =
MI.getDebugOperandIndex(&
Op);
1463 MI.getDebugExpressionOp().setMetadata(DIExpr);
1467 if (
MI.isDebugPHI()) {
1468 // Allow stack ref to continue onwards.
1472 // TODO: This code should be commoned with the code for
1473 // PATCHPOINT. There's no good reason for the difference in
1474 // implementation other than historical accident. The only
1475 // remaining difference is the unconditional use of the stack
1476 // pointer as the base register.
1477 if (
MI.getOpcode() == TargetOpcode::STATEPOINT) {
1479 "Frame indices can only appear as the first operand of a "
1480 "DBG_VALUE machine instruction");
1484 MF,
MI.getOperand(
OpIdx).getIndex(),
Reg,
/*IgnoreSPUpdates*/ false);
1486 "Frame offsets with a scalable component are not supported");
1488 MI.getOperand(
OpIdx).ChangeToRegister(
Reg,
false /*isDef*/);
1494void PEIImpl::replaceFrameIndicesBackward(MachineBasicBlock *BB,
1495 MachineFunction &MF,
int &SPAdj) {
1497 "getRegisterInfo() must be implemented!");
1503 RegScavenger *LocalRS = FrameIndexEliminationScavenging ? RS :
nullptr;
1508 MachineInstr &
MI = *std::prev(
I);
1510 if (
TII.isFrameInstr(
MI)) {
1511 SPAdj -=
TII.getSPAdjust(
MI);
1516 // Step backwards to get the liveness state at (immedately after) MI.
1520 bool RemovedMI =
false;
1525 if (replaceFrameIndexDebugInstr(MF,
MI, Idx, SPAdj))
1528 // Eliminate this FrameIndex operand.
1529 RemovedMI =
TRI.eliminateFrameIndex(
MI, SPAdj, Idx, LocalRS);
1539void PEIImpl::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &MF,
1542 "getRegisterInfo() must be implemented!");
1547 bool InsideCallSequence =
false;
1550 if (
TII.isFrameInstr(*
I)) {
1551 InsideCallSequence =
TII.isFrameSetup(*
I);
1552 SPAdj +=
TII.getSPAdjust(*
I);
1557 MachineInstr &
MI = *
I;
1559 bool DidFinishLoop =
true;
1560 for (
unsigned i = 0, e =
MI.getNumOperands(); i != e; ++i) {
1561 if (!
MI.getOperand(i).isFI())
1564 if (replaceFrameIndexDebugInstr(MF,
MI, i, SPAdj))
1567 // Some instructions (e.g. inline asm instructions) can have
1568 // multiple frame indices and/or cause eliminateFrameIndex
1569 // to insert more than one instruction. We need the register
1570 // scavenger to go through all of these instructions so that
1571 // it can update its register information. We keep the
1572 // iterator at the point before insertion so that we can
1573 // revisit them in full.
1574 bool AtBeginning = (
I == BB->
begin());
1575 if (!AtBeginning) --
I;
1577 // If this instruction has a FrameIndex operand, we need to
1578 // use that target machine register info object to eliminate
1580 TRI.eliminateFrameIndex(
MI, SPAdj, i, RS);
1582 // Reset the iterator if we were at the beginning of the BB.
1588 DidFinishLoop =
false;
1592 // If we are looking at a call sequence, we need to keep track of
1593 // the SP adjustment made by each instruction in the sequence.
1594 // This includes both the frame setup/destroy pseudos (handled above),
1595 // as well as other instructions that have side effects w.r.t the SP.
1596 // Note that this must come after eliminateFrameIndex, because
1597 // if I itself referred to a frame index, we shouldn't count its own
1599 if (DidFinishLoop && InsideCallSequence)
1600 SPAdj +=
TII.getSPAdjust(
MI);
1602 if (DoIncr &&
I != BB->
end())
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator MBBI
This file contains the simple types necessary to represent the attributes associated with functions a...
This file implements the BitVector class.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
const HexagonInstrInfo * TII
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
Register const TargetRegisterInfo * TRI
Promote Memory to Register
MachineInstr unsigned OpIdx
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
static void insertCSRRestores(MachineBasicBlock &RestoreBlock, std::vector< CalleeSavedInfo > &CSI)
Insert restore code for the callee-saved registers used in the function.
SmallVector< MachineBasicBlock *, 4 > MBBVector
static bool scavengeStackSlot(MachineFrameInfo &MFI, int FrameIdx, bool StackGrowsDown, Align MaxAlign, BitVector &StackBytesFree)
Assign frame object to an unused portion of the stack in the fixed stack object range.
static void insertCSRSaves(MachineBasicBlock &SaveBlock, ArrayRef< CalleeSavedInfo > CSI)
Insert spill code for the callee-saved registers used in the function.
static void AssignProtectedObjSet(const StackObjSet &UnassignedObjs, SmallSet< int, 16 > &ProtectedObjs, MachineFrameInfo &MFI, bool StackGrowsDown, int64_t &Offset, Align &MaxAlign)
AssignProtectedObjSet - Helper function to assign large stack objects (i.e., those required to be clo...
static void AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx, bool StackGrowsDown, int64_t &Offset, Align &MaxAlign)
AdjustStackOffset - Helper function used to adjust the stack frame offset.
SmallDenseMap< MachineBasicBlock *, SmallVector< MachineInstr *, 4 >, 4 > SavedDbgValuesMap
static void updateLiveness(MachineFunction &MF)
Helper function to update the liveness information for the callee-saved registers.
static void assignCalleeSavedSpillSlots(MachineFunction &F, const BitVector &SavedRegs, unsigned &MinCSFrameIndex, unsigned &MaxCSFrameIndex)
SmallSetVector< int, 8 > StackObjSet
StackObjSet - A set of stack object indexes.
static void stashEntryDbgValues(MachineBasicBlock &MBB, SavedDbgValuesMap &EntryDbgValues)
Stash DBG_VALUEs that describe parameters and which are placed at the start of the block.
static void computeFreeStackSlots(MachineFrameInfo &MFI, bool StackGrowsDown, unsigned MinCSFrameIndex, unsigned MaxCSFrameIndex, int64_t FixedCSEnd, BitVector &StackBytesFree)
Compute which bytes of fixed and callee-save stack area are unused and keep track of them in StackByt...
This file declares the machine register scavenger class.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
bool test(unsigned Idx) const
int find_first() const
find_first - Returns the index of the first set bit, -1 if none of the bits are set.
void resize(unsigned N, bool t=false)
resize - Grow or shrink the bitvector.
void clear()
clear - Removes all bits from the bitvector.
int find_next(unsigned Prev) const
find_next - Returns the index of the next set bit following the "Prev" bit.
bool none() const
none - Returns true if none of the bits are set.
size_type size() const
size - Returns the number of bits in this bitvector.
bool empty() const
empty - Tests whether there are no bits in this bitvector.
Represents analyses that only rely on functions' control flow.
The CalleeSavedInfo class tracks the information need to locate where a callee saved register is in t...
LLVM_ABI bool isImplicit() const
Return whether this is an implicit location description.
static bool fragmentsOverlap(const FragmentInfo &A, const FragmentInfo &B)
Check if fragments overlap between a pair of FragmentInfos.
static LLVM_ABI DIExpression * appendOpsToArg(const DIExpression *Expr, ArrayRef< uint64_t > Ops, unsigned ArgNo, bool StackValue=false)
Create a copy of Expr by appending the given list of Ops to each instance of the operand DW_OP_LLVM_a...
LLVM_ABI bool isComplex() const
Return whether the location is computed on the expression stack, meaning it cannot be a simple regist...
static LLVM_ABI DIExpression * prependOpcodes(const DIExpression *Expr, SmallVectorImpl< uint64_t > &Ops, bool StackValue=false, bool EntryValue=false)
Prepend DIExpr with the given opcodes and optionally turn it into a stack value.
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
DISubprogram * getSubprogram() const
Get the attached subprogram.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Wrapper class representing physical registers. Should be passed by value.
MachineInstrBundleIterator< const MachineInstr > const_iterator
void setCallFrameSize(unsigned N)
Set the call frame size on entry to this basic block.
succ_iterator succ_begin()
bool isEHFuncletEntry() const
Returns true if this is the entry block of an EH funclet.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
bool isReturnBlock() const
Convenience function that returns true if the block ends in a return instruction.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< iterator > terminators()
unsigned getCallFrameSize() const
Return the call frame size on entry to this basic block.
iterator_range< succ_iterator > successors()
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
SSPLayoutKind getObjectSSPLayout(int ObjectIdx) const
bool isObjectPreAllocated(int ObjectIdx) const
Return true if the object was pre-allocated into the local block.
LLVM_ABI void computeMaxCallFrameSize(MachineFunction &MF, std::vector< MachineBasicBlock::iterator > *FrameSDOps=nullptr)
Computes the maximum size of a callframe.
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
bool adjustsStack() const
Return true if this function adjusts the stack – e.g., when calling another function.
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
int64_t getLocalFrameObjectCount() const
Return the number of objects allocated into the local object block.
bool hasCalls() const
Return true if the current function has any function calls.
Align getMaxAlign() const
Return the alignment in bytes that this function must be aligned to, which is greater than the defaul...
Align getLocalFrameMaxAlign() const
Return the required alignment of the local object blob.
void setObjectOffset(int ObjectIdx, int64_t SPOffset)
Set the stack frame offset of the specified object.
@ SSPLK_SmallArray
Array or nested array < SSP-buffer-size.
@ SSPLK_LargeArray
Array or nested array >= SSP-buffer-size.
@ SSPLK_AddrOf
The address of this allocation is exposed and triggered protection.
@ SSPLK_None
Did not trigger a stack protector.
void clearRestorePoints()
std::pair< int, int64_t > getLocalFrameObjectMap(int i) const
Get the local offset mapping for a for an object.
uint64_t getMaxCallFrameSize() const
Return the maximum size of a call frame that must be allocated for an outgoing function call.
void setSavePoints(SaveRestorePoints NewSavePoints)
bool getUseLocalStackAllocationBlock() const
Get whether the local allocation blob should be allocated together or let PEI allocate the locals in ...
int getStackProtectorIndex() const
Return the index for the stack protector object.
void setCalleeSavedInfoValid(bool v)
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
bool isSpillSlotObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a spill slot.
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
bool isMaxCallFrameSizeComputed() const
int64_t getLocalFrameSize() const
Get the size of the local object blob.
const std::vector< CalleeSavedInfo > & getCalleeSavedInfo() const
Returns a reference to call saved info vector for the current function.
void setCalleeSavedInfo(std::vector< CalleeSavedInfo > CSI)
Used by prolog/epilog inserter to set the function's callee saved information.
bool isVariableSizedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a variable sized object.
uint64_t getUnsafeStackSize() const
int getObjectIndexEnd() const
Return one past the maximum frame object index.
bool hasStackProtectorIndex() const
void setRestorePoints(SaveRestorePoints NewRestorePoints)
LLVM_ABI int CreateFixedSpillStackObject(uint64_t Size, int64_t SPOffset, bool IsImmutable=false)
Create a spill slot at a fixed location on the stack.
uint8_t getStackID(int ObjectIdx) const
const SaveRestorePoints & getRestorePoints() const
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
void setStackSize(uint64_t Size)
Set the size of the stack.
int getObjectIndexBegin() const
Return the minimum frame object index.
const SaveRestorePoints & getSavePoints() const
bool isDeadObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a dead object.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const WinEHFuncInfo * getWinEHFuncInfo() const
getWinEHFuncInfo - Return information about how the current function uses Windows exception handling.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
bool shouldSplitStack() const
Should we be emitting segmented stack stuff for the function.
const MachineFunctionProperties & getProperties() const
Get the function properties.
const MachineBasicBlock & front() const
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Representation of each machine instruction.
Analysis pass that exposes the MachineLoopInfo for a machine function.
MachineOperand class - Representation of each machine instruction operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
void enterBasicBlockEnd(MachineBasicBlock &MBB)
Start tracking liveness from the end of basic block MBB.
void backward()
Update internal register state and move MBB iterator backwards.
void getScavengingFrameIndices(SmallVectorImpl< int > &A) const
Get an array of scavenging frame indices.
bool isScavengingFrameIndex(int FI) const
Query whether a frame index is a scavenging frame index.
constexpr unsigned id() const
bool empty() const
Determine if the SetVector is empty or not.
bool insert(const value_type &X)
Insert a new element into the SetVector.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
static StackOffset getScalable(int64_t Scalable)
static StackOffset getFixed(int64_t Fixed)
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Information about stack frame layout on the target.
virtual void spillFPBP(MachineFunction &MF) const
If frame pointer or base pointer is clobbered by an instruction, we should spill/restore it around th...
virtual void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const =0
virtual const SpillSlot * getCalleeSavedSpillSlots(unsigned &NumEntries) const
getCalleeSavedSpillSlots - This method returns a pointer to an array of pairs, that contains an entry...
virtual bool hasReservedCallFrame(const MachineFunction &MF) const
hasReservedCallFrame - Under normal circumstances, when a frame pointer is not required,...
virtual bool enableStackSlotScavenging(const MachineFunction &MF) const
Returns true if the stack slot holes in the fixed and callee-save stack area should be used when allo...
virtual bool allocateScavengingFrameIndexesNearIncomingSP(const MachineFunction &MF) const
Control the placement of special register scavenging spill slots when allocating a stack frame.
Align getTransientStackAlign() const
getTransientStackAlignment - This method returns the number of bytes to which the stack pointer must ...
virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
virtual uint64_t getStackThreshold() const
getStackThreshold - Return the maximum stack size
virtual void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS=nullptr) const
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
virtual void inlineStackProbe(MachineFunction &MF, MachineBasicBlock &PrologueMBB) const
Replace a StackProbe stub (if any) with the actual probe code inline.
void restoreCalleeSavedRegister(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const CalleeSavedInfo &CS, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const
void spillCalleeSavedRegister(MachineBasicBlock &SaveBlock, MachineBasicBlock::iterator MI, const CalleeSavedInfo &CS, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const
spillCalleeSavedRegister - Default implementation for spilling a single callee saved register.
virtual void orderFrameObjects(const MachineFunction &MF, SmallVectorImpl< int > &objectsToAllocate) const
Order the symbols in the local stack frame.
virtual void adjustForHiPEPrologue(MachineFunction &MF, MachineBasicBlock &PrologueMBB) const
Adjust the prologue to add Erlang Run-Time System (ERTS) specific code in the assembly prologue to ex...
virtual bool spillCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, ArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const
spillCalleeSavedRegisters - Issues instruction(s) to spill all callee saved registers and returns tru...
int getOffsetOfLocalArea() const
getOffsetOfLocalArea - This method returns the offset of the local area from the stack pointer on ent...
virtual bool assignCalleeSavedSpillSlots(MachineFunction &MF, const TargetRegisterInfo *TRI, std::vector< CalleeSavedInfo > &CSI, unsigned &MinCSFrameIndex, unsigned &MaxCSFrameIndex) const
assignCalleeSavedSpillSlots - Allows target to override spill slot assignment logic.
virtual bool needsFrameIndexResolution(const MachineFunction &MF) const
virtual MachineBasicBlock::iterator eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const
This method is called during prolog/epilog code insertion to eliminate call frame setup and destroy p...
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
virtual void processFunctionBeforeFrameIndicesReplaced(MachineFunction &MF, RegScavenger *RS=nullptr) const
processFunctionBeforeFrameIndicesReplaced - This method is called immediately before MO_FrameIndex op...
virtual StackOffset getFrameIndexReferencePreferSP(const MachineFunction &MF, int FI, Register &FrameReg, bool IgnoreSPUpdates) const
Same as getFrameIndexReference, except that the stack pointer (as opposed to the frame pointer) will ...
StackDirection getStackGrowthDirection() const
getStackGrowthDirection - Return the direction the stack grows
virtual void adjustForSegmentedStacks(MachineFunction &MF, MachineBasicBlock &PrologueMBB) const
Adjust the prologue to have the function use segmented stacks.
int alignSPAdjust(int SPAdj) const
alignSPAdjust - This method aligns the stack adjustment to the correct alignment.
virtual bool canSimplifyCallFramePseudos(const MachineFunction &MF) const
canSimplifyCallFramePseudos - When possible, it's best to simplify the call frame pseudo ops before d...
virtual void emitZeroCallUsedRegs(BitVector RegsToZero, MachineBasicBlock &MBB) const
emitZeroCallUsedRegs - Zeros out call used registers.
virtual void emitRemarks(const MachineFunction &MF, MachineOptimizationRemarkEmitter *ORE) const
This method is called at the end of prolog/epilog code insertion, so targets can emit remarks based o...
virtual bool targetHandlesStackFrameRounding() const
targetHandlesStackFrameRounding - Returns true if the target is responsible for rounding up the stack...
virtual void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const =0
emitProlog/emitEpilog - These methods insert prolog and epilog code into the function.
virtual bool restoreCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, MutableArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const
restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee saved registers and returns...
virtual StackOffset getFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg) const
getFrameIndexReference - This method should return the base register and offset used to reference a f...
TargetInstrInfo - Interface to description of machine instruction set.
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
virtual bool usesPhysRegsForValues() const
True if the target uses physical regs (as nearly all targets do).
unsigned StackSymbolOrdering
StackSymbolOrdering - When true, this will allow CodeGen to order the local stack symbols (for code s...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
bool hasStackRealignment(const MachineFunction &MF) const
True if stack realignment is required and still possible.
virtual const TargetFrameLowering * getFrameLowering() const
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
testing::Matcher< const detail::ErrorHolder & > Failed()
void scavengeFrameVirtualRegs(MachineFunction &MF, RegScavenger &RS)
Replaces all frame index virtual registers with physical registers.
LLVM_ABI MachineFunctionPass * createPrologEpilogInserterPass()
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI char & PrologEpilogCodeInserterID
PrologEpilogCodeInserter - This pass inserts prolog and epilog code, and eliminates abstract frame re...
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
auto reverse(ContainerTy &&C)
DenseMap< MachineBasicBlock *, std::vector< CalleeSavedInfo > > SaveRestorePoints
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
unsigned MCRegUnit
Register units are used to compute register aliasing.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
DWARFExpression::Operation Op
LLVM_ABI void initializePEILegacyPass(PassRegistry &)
This struct is a compact representation of a valid (non-zero power of two) alignment.