LLVM 24.0.0git
MachineLoopInfo.cpp
Go to the documentation of this file.
1//===- MachineLoopInfo.cpp - Natural Loop Calculator ----------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the MachineLoopInfo class that is used to identify natural
10// loops and determine the loop depth of various nodes of the CFG. Note that
11// the loops identified may actually be several natural loops that share the
12// same header node... not just a single natural loop.
13//
14//===----------------------------------------------------------------------===//
15
21#include "llvm/Config/llvm-config.h"
23#include "llvm/Pass.h"
26
27using namespace llvm;
28
29// Explicitly instantiate methods in LoopInfoImpl.h for MI-level Loops.
30template class LLVM_EXPORT_TEMPLATE
32template class LLVM_EXPORT_TEMPLATE
34
35AnalysisKey MachineLoopAnalysis::Key;
36
41 // The dominator tree is needed only for an irreducible CFG.
42 LI.calculate(MF, [&]() -> const MachineDominatorTree & {
44 });
45 return LI;
46}
47
51 OS << "Machine loop info for machine function '" << MF.getName() << "':\n";
54}
55
60 "Machine Natural Loop Construction", true, true)
63 "Machine Natural Loop Construction", true, true)
64
66
71
74 MachineFunctionAnalysisManager::Invalidator &) {
75 // Check whether the analysis, all analyses on functions, or the function's
76 // CFG have been preserved.
77 auto PAC = PA.getChecker<MachineLoopAnalysis>();
78 return !PAC.preserved() &&
79 !PAC.preservedSet<AllAnalysesOn<MachineFunction>>() &&
80 !PAC.preservedSet<CFGAnalyses>();
81}
82
87
90 function_ref<const DomTreeBase<MachineBasicBlock> &()> GetDomTree) {
92 analyze(&MF, GetDomTree);
93}
94
100
102 MachineBasicBlock *TopMBB = getHeader();
103 MachineFunction::iterator Begin = TopMBB->getParent()->begin();
104 if (TopMBB->getIterator() != Begin) {
105 MachineBasicBlock *PriorMBB = &*std::prev(TopMBB->getIterator());
106 while (contains(PriorMBB)) {
107 TopMBB = PriorMBB;
108 if (TopMBB->getIterator() == Begin)
109 break;
110 PriorMBB = &*std::prev(TopMBB->getIterator());
111 }
112 }
113 return TopMBB;
114}
115
117 MachineBasicBlock *BotMBB = getHeader();
119 if (BotMBB->getIterator() != std::prev(End)) {
120 MachineBasicBlock *NextMBB = &*std::next(BotMBB->getIterator());
121 while (contains(NextMBB)) {
122 BotMBB = NextMBB;
123 if (BotMBB == &*std::next(BotMBB->getIterator()))
124 break;
125 NextMBB = &*std::next(BotMBB->getIterator());
126 }
127 }
128 return BotMBB;
129}
130
132 if (MachineBasicBlock *Latch = getLoopLatch()) {
133 if (isLoopExiting(Latch))
134 return Latch;
135 else
136 return getExitingBlock();
137 }
138 return nullptr;
139}
140
142 // Try the pre-header first.
143 if (MachineBasicBlock *PHeadMBB = getLoopPreheader())
144 if (const BasicBlock *PHeadBB = PHeadMBB->getBasicBlock())
145 if (DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc())
146 return DL;
147
148 // If we have no pre-header or there are no instructions with debug
149 // info in it, try the header.
150 if (MachineBasicBlock *HeadMBB = getHeader())
151 if (const BasicBlock *HeadBB = HeadMBB->getBasicBlock())
152 return HeadBB->getTerminator()->getDebugLoc();
153
154 return DebugLoc();
155}
156
159 bool FindMultiLoopPreheader) const {
160 if (MachineBasicBlock *PB = L->getLoopPreheader())
161 return PB;
162
163 if (!SpeculativePreheader)
164 return nullptr;
165
166 MachineBasicBlock *HB = L->getHeader(), *LB = L->getLoopLatch();
167 if (HB->pred_size() != 2 || HB->hasAddressTaken())
168 return nullptr;
169 // Find the predecessor of the header that is not the latch block.
170 MachineBasicBlock *Preheader = nullptr;
171 for (MachineBasicBlock *P : HB->predecessors()) {
172 if (P == LB)
173 continue;
174 // Sanity.
175 if (Preheader)
176 return nullptr;
177 Preheader = P;
178 }
179
180 // Check if the preheader candidate is a successor of any other loop
181 // headers. We want to avoid having two loop setups in the same block.
182 if (!FindMultiLoopPreheader) {
183 for (MachineBasicBlock *S : Preheader->successors()) {
184 if (S == HB)
185 continue;
187 if (T && T->getHeader() == S)
188 return nullptr;
189 }
190 }
191 return Preheader;
192}
193
195 MDNode *LoopID = nullptr;
196
197 // Go through the latch blocks and check the terminator for the metadata
199 getLoopLatches(LatchesBlocks);
200 for (const auto *MBB : LatchesBlocks) {
201 const auto *BB = MBB->getBasicBlock();
202 if (!BB)
203 return nullptr;
204 const auto *TI = BB->getTerminator();
205 MDNode *MD = TI->getMetadata(LLVMContext::MD_loop);
206 if (!MD)
207 return nullptr;
208
209 if (!LoopID)
210 LoopID = MD;
211 else if (MD != LoopID)
212 return nullptr;
213 }
214
215 if (!LoopID || LoopID->getNumOperands() == 0 ||
216 LoopID->getOperand(0) != LoopID)
217 return nullptr;
218
219 return LoopID;
220}
221
222bool MachineLoop::isLoopInvariantImplicitPhysReg(Register Reg) const {
224 MachineRegisterInfo *MRI = &MF->getRegInfo();
225
226 if (MRI->isConstantPhysReg(Reg))
227 return true;
228
229 if (!MF->getSubtarget()
232 return false;
233
234 return !llvm::any_of(
235 MRI->def_instructions(Reg),
236 [this](const MachineInstr &MI) { return this->contains(&MI); });
237}
238
240 const Register ExcludeReg) const {
241 MachineFunction *MF = I.getParent()->getParent();
242 MachineRegisterInfo *MRI = &MF->getRegInfo();
243 const TargetSubtargetInfo &ST = MF->getSubtarget();
244 const TargetRegisterInfo *TRI = ST.getRegisterInfo();
245 const TargetInstrInfo *TII = ST.getInstrInfo();
246
247 // The instruction is loop invariant if all of its operands are.
248 for (const MachineOperand &MO : I.operands()) {
249 if (!MO.isReg())
250 continue;
251
252 Register Reg = MO.getReg();
253 if (Reg == 0) continue;
254
255 if (ExcludeReg == Reg)
256 continue;
257
258 // An instruction that uses or defines a physical register can't e.g. be
259 // hoisted, so mark this as not invariant.
260 if (Reg.isPhysical()) {
261 if (MO.isUse()) {
262 // If the physreg has no defs anywhere, it's just an ambient register
263 // and we can freely move its uses. Alternatively, if it's allocatable,
264 // it could get allocated to something with a def during allocation.
265 // However, if the physreg is known to always be caller saved/restored
266 // then this use is safe to hoist.
267 if (!isLoopInvariantImplicitPhysReg(Reg) &&
268 !(TRI->isCallerPreservedPhysReg(Reg.asMCReg(), *I.getMF())) &&
269 !TII->isIgnorableUse(I, I.getOperandNo(&MO)))
270 return false;
271 // Otherwise it's safe to move.
272 continue;
273 } else if (!MO.isDead()) {
274 // A def that isn't dead can't be moved.
275 return false;
276 } else if (getHeader()->isLiveIn(Reg)) {
277 // If the reg is live into the loop, we can't hoist an instruction
278 // which would clobber it.
279 return false;
280 }
281 }
282
283 if (!MO.readsReg())
284 continue;
285
286 MachineBasicBlock *DefBlock = MRI->getDefBlock(Reg);
287 assert(DefBlock && "Machine instr not mapped for this vreg?!");
288
289 // If the loop contains the definition of an operand, then the instruction
290 // isn't loop invariant.
291 if (contains(DefBlock))
292 return false;
293 }
294
295 // If we got this far, the instruction is loop invariant!
296 return true;
297}
298
299#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
301 print(dbgs());
302}
303#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:682
#define LLVM_EXPORT_TEMPLATE
Definition Compiler.h:213
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
Register const TargetRegisterInfo * TRI
#define T
#define P(N)
PassBuilder PB(Mod->getContext(), Machine, PassOpts->PTO, std::nullopt, &PIC)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
static DominatorTree getDomTree(Function &F)
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
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()
void setPreservesAll()
Set by analyses that do not transform their input at all.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
A debug info location.
Definition DebugLoc.h:126
Instances of this class are used to represent loops that are detected in the flow graph.
void getLoopLatches(SmallVectorImpl< MachineBasicBlock * > &LoopLatches) const
void print(raw_ostream &OS, bool Verbose=false, bool PrintNested=true, unsigned Depth=0) const
bool isLoopExiting(const MachineBasicBlock *BB) const
This class builds and contains all of the top-level loop structures in the specified function.
MachineLoop * getLoopFor(const MachineBasicBlock *BB) const
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1443
bool hasAddressTaken() const
Test whether this block is used as something other than the target of a terminator,...
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< succ_iterator > successors()
iterator_range< pred_iterator > predecessors()
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
BasicBlockListType::iterator iterator
Representation of each machine instruction.
Analysis pass that exposes the MachineLoopInfo for a machine function.
LLVM_ABI Result run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
bool runOnMachineFunction(MachineFunction &F) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
LLVM_ABI void calculate(MachineDominatorTree &MDT)
Calculate the natural loop information.
LLVM_ABI bool invalidate(MachineFunction &, const PreservedAnalyses &PA, MachineFunctionAnalysisManager::Invalidator &)
Handle invalidation explicitly.
LLVM_ABI MachineBasicBlock * findLoopPreheader(MachineLoop *L, bool SpeculativePreheader=false, bool FindMultiLoopPreheader=false) const
Find the block that either is the loop preheader, or could speculatively be used as the preheader.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI MachineBasicBlock * getTopBlock() const
Return the "top" block in the loop, which is the first block in the linear layout,...
LLVM_ABI MachineBasicBlock * findLoopControlBlock() const
Find the block that contains the loop control variable and the loop test.
LLVM_ABI MDNode * getLoopID() const
Find the llvm.loop metadata for this loop.
LLVM_ABI DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
LLVM_ABI void dump() const
LLVM_ABI MachineBasicBlock * getBottomBlock() const
Return the "bottom" block in the loop, which is the last block in the linear layout,...
LLVM_ABI bool isLoopInvariant(MachineInstr &I, const Register ExcludeReg=0) const
Returns true if the instruction is loop invariant.
MachineOperand class - Representation of each machine instruction operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
iterator_range< def_instr_iterator > def_instructions(Register Reg) const
MachineBasicBlock * getDefBlock(Register Reg) const
Return the machine basic block in which the specified virtual register is defined,...
LLVM_ABI bool isConstantPhysReg(MCRegister PhysReg) const
Returns true if PhysReg is unallocatable and constant throughout the function.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
Wrapper class representing virtual and physical registers.
Definition Register.h:20
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual bool shouldAnalyzePhysregInMachineLoopInfo(MCRegister R) const
Returns true if MachineLoopInfo should analyze the given physreg for loop invariance.
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Definition ilist_node.h:123
This is an optimization pass for GlobalISel generic memory operations.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI char & MachineLoopInfoID
MachineLoopInfo - This pass is a loop analysis pass.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
DominatorTreeBase< T, false > DomTreeBase
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:267
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29