1//===- LoopInfo.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 LoopInfo class that is used to identify natural loops
10// and determine the loop depth of various nodes of the CFG. Note that the
11// loops identified may actually be several natural loops that share the same
12// header node... not just a single natural loop.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/Analysis/LoopInfo.h"
17#include "llvm/ADT/ScopeExit.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/Analysis/IVDescriptors.h"
20#include "llvm/Analysis/LoopIterator.h"
21#include "llvm/Analysis/LoopNestAnalysis.h"
22#include "llvm/Analysis/MemorySSA.h"
23#include "llvm/Analysis/MemorySSAUpdater.h"
24#include "llvm/Analysis/ScalarEvolutionExpressions.h"
25#include "llvm/Analysis/ValueTracking.h"
26#include "llvm/Config/llvm-config.h"
27#include "llvm/IR/CFG.h"
28#include "llvm/IR/Constants.h"
29#include "llvm/IR/DebugLoc.h"
30#include "llvm/IR/Dominators.h"
31#include "llvm/IR/Instructions.h"
32#include "llvm/IR/LLVMContext.h"
33#include "llvm/IR/Metadata.h"
34#include "llvm/IR/Module.h"
35#include "llvm/IR/PassManager.h"
36#include "llvm/IR/PrintPasses.h"
37#include "llvm/IR/ProfDataUtils.h"
38#include "llvm/InitializePasses.h"
39#include "llvm/Support/CommandLine.h"
40#include "llvm/Support/Compiler.h"
41#include "llvm/Support/GenericLoopInfoImpl.h"
42#include "llvm/Support/raw_ostream.h"
43using namespace llvm;
44
45// Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
46template class LLVM_EXPORT_TEMPLATE llvm::LoopBase<BasicBlock, Loop>;
47template class LLVM_EXPORT_TEMPLATE llvm::LoopInfoBase<BasicBlock, Loop>;
48
49// Always verify loopinfo if expensive checking is enabled.
50#ifdef EXPENSIVE_CHECKS
51bool llvm::VerifyLoopInfo = true;
52#else
53bool llvm::VerifyLoopInfo = false;
54#endif
55static cl::opt<bool, true>
56 VerifyLoopInfoX("verify-loop-info", cl::location(L&: VerifyLoopInfo),
57 cl::Hidden, cl::desc("Verify loop info (time consuming)"));
58
59namespace llvm {
60extern cl::opt<bool> ProfcheckDisableMetadataFixes;
61} // end namespace llvm
62
63//===----------------------------------------------------------------------===//
64// Loop implementation
65//
66
67bool Loop::isLoopInvariant(const Value *V) const {
68 if (const Instruction *I = dyn_cast<Instruction>(Val: V))
69 return !contains(Inst: I);
70 return true; // All non-instructions are loop invariant
71}
72
73bool Loop::hasLoopInvariantOperands(const Instruction *I) const {
74 return all_of(Range: I->operands(), P: [&](Value *V) { return isLoopInvariant(V); });
75}
76
77bool Loop::makeLoopInvariant(Value *V, bool &Changed, Instruction *InsertPt,
78 MemorySSAUpdater *MSSAU,
79 ScalarEvolution *SE) const {
80 if (Instruction *I = dyn_cast<Instruction>(Val: V))
81 return makeLoopInvariant(I, Changed, InsertPt, MSSAU, SE);
82 return true; // All non-instructions are loop-invariant.
83}
84
85bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
86 Instruction *InsertPt, MemorySSAUpdater *MSSAU,
87 ScalarEvolution *SE) const {
88 BasicBlock *OriginalParent = I->getParent();
89 // Test if the value is already loop-invariant.
90 if (isLoopInvariant(V: I))
91 return true;
92 if (!isSafeToSpeculativelyExecute(I))
93 return false;
94 if (I->mayReadFromMemory())
95 return false;
96 // EH block instructions are immobile.
97 if (I->isEHPad())
98 return false;
99 // Determine the insertion point, unless one was given.
100 if (!InsertPt) {
101 BasicBlock *Preheader = getLoopPreheader();
102 // Without a preheader, hoisting is not feasible.
103 if (!Preheader)
104 return false;
105 InsertPt = Preheader->getTerminator();
106 }
107 // Don't hoist instructions with loop-variant operands.
108 for (Value *Operand : I->operands())
109 if (!makeLoopInvariant(V: Operand, Changed, InsertPt, MSSAU, SE))
110 return false;
111
112 // Hoist.
113 I->moveBefore(InsertPos: InsertPt->getIterator());
114 if (MSSAU)
115 if (auto *MUD = MSSAU->getMemorySSA()->getMemoryAccess(I))
116 MSSAU->moveToPlace(What: MUD, BB: InsertPt->getParent(),
117 Where: MemorySSA::BeforeTerminator);
118
119 // We want to preserve profile metadata if possible. However, we need to
120 // ensure that profile metadata would remain the same outside of the loop.
121 // Given at this point we know the conditional is loop-invariant, we just
122 // need to worry about other control flow in the loop conditioned on values
123 // that are potentially not independent of the condition of the instruction
124 // we are interested in hoisting. Given this is not knowable in the general
125 // case, we only hoist from a loop header (which covers a reasonable number
126 // of cases) where we are guaranteed to not run into problems.
127 SmallVector<unsigned, 1> ProfileMetadataToPreserve;
128 if (!ProfcheckDisableMetadataFixes)
129 if (OriginalParent == getHeader())
130 ProfileMetadataToPreserve.push_back(Elt: LLVMContext::MD_prof);
131
132 // There is possibility of hoisting this instruction above some arbitrary
133 // condition. Any metadata defined on it can be control dependent on this
134 // condition. Conservatively strip it here so that we don't give any wrong
135 // information to the optimizer.
136 I->dropUnknownNonDebugMetadata(KnownIDs: ProfileMetadataToPreserve);
137
138 if (ProfileMetadataToPreserve.empty() && isa<SelectInst>(Val: I))
139 setExplicitlyUnknownBranchWeightsIfProfiled(I&: *I, PassName: "LoopInfo");
140
141 if (SE)
142 SE->forgetBlockAndLoopDispositions(V: I);
143
144 Changed = true;
145 return true;
146}
147
148bool Loop::getIncomingAndBackEdge(BasicBlock *&Incoming,
149 BasicBlock *&Backedge) const {
150 BasicBlock *H = getHeader();
151
152 Incoming = nullptr;
153 Backedge = nullptr;
154 pred_iterator PI = pred_begin(BB: H);
155 assert(PI != pred_end(H) && "Loop must have at least one backedge!");
156 Backedge = *PI++;
157 if (PI == pred_end(BB: H))
158 return false; // dead loop
159 Incoming = *PI++;
160 if (PI != pred_end(BB: H))
161 return false; // multiple backedges?
162
163 if (contains(BB: Incoming)) {
164 if (contains(BB: Backedge))
165 return false;
166 std::swap(a&: Incoming, b&: Backedge);
167 } else if (!contains(BB: Backedge))
168 return false;
169
170 assert(Incoming && Backedge && "expected non-null incoming and backedges");
171 return true;
172}
173
174PHINode *Loop::getCanonicalInductionVariable() const {
175 BasicBlock *H = getHeader();
176
177 BasicBlock *Incoming = nullptr, *Backedge = nullptr;
178 if (!getIncomingAndBackEdge(Incoming, Backedge))
179 return nullptr;
180
181 // Loop over all of the PHI nodes, looking for a canonical indvar.
182 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(Val: I); ++I) {
183 PHINode *PN = cast<PHINode>(Val&: I);
184 if (ConstantInt *CI =
185 dyn_cast<ConstantInt>(Val: PN->getIncomingValueForBlock(BB: Incoming)))
186 if (CI->isZero())
187 if (Instruction *Inc =
188 dyn_cast<Instruction>(Val: PN->getIncomingValueForBlock(BB: Backedge)))
189 if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(i: 0) == PN)
190 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: Inc->getOperand(i: 1)))
191 if (CI->isOne())
192 return PN;
193 }
194 return nullptr;
195}
196
197/// Get the latch condition instruction.
198ICmpInst *Loop::getLatchCmpInst() const {
199 if (BasicBlock *Latch = getLoopLatch())
200 if (CondBrInst *BI = dyn_cast_or_null<CondBrInst>(Val: Latch->getTerminator()))
201 return dyn_cast<ICmpInst>(Val: BI->getCondition());
202
203 return nullptr;
204}
205
206/// Return the final value of the loop induction variable if found.
207static Value *findFinalIVValue(const Loop &L, const PHINode &IndVar,
208 const Instruction &StepInst) {
209 ICmpInst *LatchCmpInst = L.getLatchCmpInst();
210 if (!LatchCmpInst)
211 return nullptr;
212
213 Value *Op0 = LatchCmpInst->getOperand(i_nocapture: 0);
214 Value *Op1 = LatchCmpInst->getOperand(i_nocapture: 1);
215 if (Op0 == &IndVar || Op0 == &StepInst)
216 return Op1;
217
218 if (Op1 == &IndVar || Op1 == &StepInst)
219 return Op0;
220
221 return nullptr;
222}
223
224std::optional<Loop::LoopBounds>
225Loop::LoopBounds::getBounds(const Loop &L, PHINode &IndVar,
226 ScalarEvolution &SE) {
227 InductionDescriptor IndDesc;
228 if (!InductionDescriptor::isInductionPHI(Phi: &IndVar, L: &L, SE: &SE, D&: IndDesc))
229 return std::nullopt;
230
231 Value *InitialIVValue = IndDesc.getStartValue();
232 Instruction *StepInst = IndDesc.getInductionBinOp();
233 if (!InitialIVValue || !StepInst)
234 return std::nullopt;
235
236 const SCEV *Step = IndDesc.getStep();
237 Value *StepInstOp1 = StepInst->getOperand(i: 1);
238 Value *StepInstOp0 = StepInst->getOperand(i: 0);
239 Value *StepValue = nullptr;
240 if (SE.getSCEV(V: StepInstOp1) == Step)
241 StepValue = StepInstOp1;
242 else if (SE.getSCEV(V: StepInstOp0) == Step)
243 StepValue = StepInstOp0;
244
245 Value *FinalIVValue = findFinalIVValue(L, IndVar, StepInst: *StepInst);
246 if (!FinalIVValue)
247 return std::nullopt;
248
249 return LoopBounds(L, *InitialIVValue, *StepInst, StepValue, *FinalIVValue,
250 SE);
251}
252
253using Direction = Loop::LoopBounds::Direction;
254
255ICmpInst::Predicate Loop::LoopBounds::getCanonicalPredicate() const {
256 BasicBlock *Latch = L.getLoopLatch();
257 assert(Latch && "Expecting valid latch");
258
259 CondBrInst *BI = cast<CondBrInst>(Val: Latch->getTerminator());
260
261 ICmpInst *LatchCmpInst = dyn_cast<ICmpInst>(Val: BI->getCondition());
262 assert(LatchCmpInst &&
263 "Expecting the latch compare instruction to be a CmpInst");
264
265 // Need to inverse the predicate when first successor is not the loop
266 // header
267 ICmpInst::Predicate Pred = (BI->getSuccessor(i: 0) == L.getHeader())
268 ? LatchCmpInst->getPredicate()
269 : LatchCmpInst->getInversePredicate();
270
271 if (LatchCmpInst->getOperand(i_nocapture: 0) == &getFinalIVValue())
272 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
273
274 // Need to flip strictness of the predicate when the latch compare instruction
275 // is not using StepInst
276 if (LatchCmpInst->getOperand(i_nocapture: 0) == &getStepInst() ||
277 LatchCmpInst->getOperand(i_nocapture: 1) == &getStepInst())
278 return Pred;
279
280 // Cannot flip strictness of NE and EQ
281 if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
282 return ICmpInst::getFlippedStrictnessPredicate(pred: Pred);
283
284 Direction D = getDirection();
285 if (D == Direction::Increasing)
286 return ICmpInst::ICMP_SLT;
287
288 if (D == Direction::Decreasing)
289 return ICmpInst::ICMP_SGT;
290
291 // If cannot determine the direction, then unable to find the canonical
292 // predicate
293 return ICmpInst::BAD_ICMP_PREDICATE;
294}
295
296Direction Loop::LoopBounds::getDirection() const {
297 if (const SCEVAddRecExpr *StepAddRecExpr =
298 dyn_cast<SCEVAddRecExpr>(Val: SE.getSCEV(V: &getStepInst())))
299 if (const SCEV *StepRecur = StepAddRecExpr->getStepRecurrence(SE)) {
300 if (SE.isKnownPositive(S: StepRecur))
301 return Direction::Increasing;
302 if (SE.isKnownNegative(S: StepRecur))
303 return Direction::Decreasing;
304 }
305
306 return Direction::Unknown;
307}
308
309std::optional<Loop::LoopBounds> Loop::getBounds(ScalarEvolution &SE) const {
310 if (PHINode *IndVar = getInductionVariable(SE))
311 return LoopBounds::getBounds(L: *this, IndVar&: *IndVar, SE);
312
313 return std::nullopt;
314}
315
316PHINode *Loop::getInductionVariable(ScalarEvolution &SE) const {
317 if (!isLoopSimplifyForm())
318 return nullptr;
319
320 BasicBlock *Header = getHeader();
321 assert(Header && "Expected a valid loop header");
322 ICmpInst *CmpInst = getLatchCmpInst();
323 if (!CmpInst)
324 return nullptr;
325
326 Value *LatchCmpOp0 = CmpInst->getOperand(i_nocapture: 0);
327 Value *LatchCmpOp1 = CmpInst->getOperand(i_nocapture: 1);
328
329 for (PHINode &IndVar : Header->phis()) {
330 InductionDescriptor IndDesc;
331 if (!InductionDescriptor::isInductionPHI(Phi: &IndVar, L: this, SE: &SE, D&: IndDesc))
332 continue;
333
334 BasicBlock *Latch = getLoopLatch();
335 Value *StepInst = IndVar.getIncomingValueForBlock(BB: Latch);
336
337 // case 1:
338 // IndVar = phi[{InitialValue, preheader}, {StepInst, latch}]
339 // StepInst = IndVar + step
340 // cmp = StepInst < FinalValue
341 if (StepInst == LatchCmpOp0 || StepInst == LatchCmpOp1)
342 return &IndVar;
343
344 // case 2:
345 // IndVar = phi[{InitialValue, preheader}, {StepInst, latch}]
346 // StepInst = IndVar + step
347 // cmp = IndVar < FinalValue
348 if (&IndVar == LatchCmpOp0 || &IndVar == LatchCmpOp1)
349 return &IndVar;
350 }
351
352 return nullptr;
353}
354
355bool Loop::getInductionDescriptor(ScalarEvolution &SE,
356 InductionDescriptor &IndDesc) const {
357 if (PHINode *IndVar = getInductionVariable(SE))
358 return InductionDescriptor::isInductionPHI(Phi: IndVar, L: this, SE: &SE, D&: IndDesc);
359
360 return false;
361}
362
363bool Loop::isAuxiliaryInductionVariable(PHINode &AuxIndVar,
364 ScalarEvolution &SE) const {
365 // Located in the loop header
366 BasicBlock *Header = getHeader();
367 if (AuxIndVar.getParent() != Header)
368 return false;
369
370 // No uses outside of the loop
371 for (User *U : AuxIndVar.users())
372 if (const Instruction *I = dyn_cast<Instruction>(Val: U))
373 if (!contains(Inst: I))
374 return false;
375
376 InductionDescriptor IndDesc;
377 if (!InductionDescriptor::isInductionPHI(Phi: &AuxIndVar, L: this, SE: &SE, D&: IndDesc))
378 return false;
379
380 // The step instruction opcode should be add or sub.
381 if (IndDesc.getInductionOpcode() != Instruction::Add &&
382 IndDesc.getInductionOpcode() != Instruction::Sub)
383 return false;
384
385 // Incremented by a loop invariant step for each loop iteration
386 return SE.isLoopInvariant(S: IndDesc.getStep(), L: this);
387}
388
389CondBrInst *Loop::getLoopGuardBranch() const {
390 if (!isLoopSimplifyForm())
391 return nullptr;
392
393 BasicBlock *Preheader = getLoopPreheader();
394 assert(Preheader && getLoopLatch() &&
395 "Expecting a loop with valid preheader and latch");
396
397 // Loop should be in rotate form.
398 if (!isRotatedForm())
399 return nullptr;
400
401 // Disallow loops with more than one unique exit block, as we do not verify
402 // that GuardOtherSucc post dominates all exit blocks.
403 BasicBlock *ExitFromLatch = getUniqueExitBlock();
404 if (!ExitFromLatch)
405 return nullptr;
406
407 BasicBlock *GuardBB = Preheader->getUniquePredecessor();
408 if (!GuardBB)
409 return nullptr;
410
411 assert(GuardBB->getTerminator() && "Expecting valid guard terminator");
412
413 CondBrInst *GuardBI = dyn_cast<CondBrInst>(Val: GuardBB->getTerminator());
414 if (!GuardBI)
415 return nullptr;
416
417 BasicBlock *GuardOtherSucc = (GuardBI->getSuccessor(i: 0) == Preheader)
418 ? GuardBI->getSuccessor(i: 1)
419 : GuardBI->getSuccessor(i: 0);
420
421 // Check if ExitFromLatch (or any BasicBlock which is an empty unique
422 // successor of ExitFromLatch) is equal to GuardOtherSucc. If
423 // skipEmptyBlockUntil returns GuardOtherSucc, then the guard branch for the
424 // loop is GuardBI (return GuardBI), otherwise return nullptr.
425 if (&LoopNest::skipEmptyBlockUntil(From: ExitFromLatch, End: GuardOtherSucc,
426 /*CheckUniquePred=*/true) ==
427 GuardOtherSucc)
428 return GuardBI;
429 else
430 return nullptr;
431}
432
433bool Loop::isCanonical(ScalarEvolution &SE) const {
434 InductionDescriptor IndDesc;
435 if (!getInductionDescriptor(SE, IndDesc))
436 return false;
437
438 ConstantInt *Init = dyn_cast_or_null<ConstantInt>(Val: IndDesc.getStartValue());
439 if (!Init || !Init->isZero())
440 return false;
441
442 if (IndDesc.getInductionOpcode() != Instruction::Add)
443 return false;
444
445 ConstantInt *Step = IndDesc.getConstIntStepValue();
446 if (!Step || !Step->isOne())
447 return false;
448
449 return true;
450}
451
452// Check that 'BB' doesn't have any uses outside of the 'L'
453static bool isBlockInLCSSAForm(const Loop &L, const BasicBlock &BB,
454 const DominatorTree &DT, bool IgnoreTokens) {
455 for (const Instruction &I : BB) {
456 // Tokens can't be used in PHI nodes and live-out tokens prevent loop
457 // optimizations, so for the purposes of considered LCSSA form, we
458 // can ignore them.
459 if (IgnoreTokens && I.getType()->isTokenTy())
460 continue;
461
462 for (const Use &U : I.uses()) {
463 const Instruction *UI = cast<Instruction>(Val: U.getUser());
464 const BasicBlock *UserBB = UI->getParent();
465
466 // For practical purposes, we consider that the use in a PHI
467 // occurs in the respective predecessor block. For more info,
468 // see the `phi` doc in LangRef and the LCSSA doc.
469 if (const PHINode *P = dyn_cast<PHINode>(Val: UI))
470 UserBB = P->getIncomingBlock(U);
471
472 // Check the current block, as a fast-path, before checking whether
473 // the use is anywhere in the loop. Most values are used in the same
474 // block they are defined in. Also, blocks not reachable from the
475 // entry are special; uses in them don't need to go through PHIs.
476 if (UserBB != &BB && !L.contains(BB: UserBB) &&
477 DT.isReachableFromEntry(A: UserBB))
478 return false;
479 }
480 }
481 return true;
482}
483
484bool Loop::isLCSSAForm(const DominatorTree &DT, bool IgnoreTokens) const {
485 // For each block we check that it doesn't have any uses outside of this loop.
486 return all_of(Range: this->blocks(), P: [&](const BasicBlock *BB) {
487 return isBlockInLCSSAForm(L: *this, BB: *BB, DT, IgnoreTokens);
488 });
489}
490
491bool Loop::isRecursivelyLCSSAForm(const DominatorTree &DT, const LoopInfo &LI,
492 bool IgnoreTokens) const {
493 // For each block we check that it doesn't have any uses outside of its
494 // innermost loop. This process will transitively guarantee that the current
495 // loop and all of the nested loops are in LCSSA form.
496 return all_of(Range: this->blocks(), P: [&](const BasicBlock *BB) {
497 return isBlockInLCSSAForm(L: *LI.getLoopFor(BB), BB: *BB, DT, IgnoreTokens);
498 });
499}
500
501bool Loop::isLoopSimplifyForm() const {
502 // Normal-form loops have a preheader, a single backedge, and all of their
503 // exits have all their predecessors inside the loop.
504 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
505}
506
507// Routines that reform the loop CFG and split edges often fail on indirectbr.
508bool Loop::isSafeToClone() const {
509 // Return false if any loop blocks contain indirectbrs, or there are any calls
510 // to noduplicate functions.
511 for (BasicBlock *BB : this->blocks()) {
512 if (isa<IndirectBrInst>(Val: BB->getTerminator()))
513 return false;
514
515 for (Instruction &I : *BB)
516 if (auto *CB = dyn_cast<CallBase>(Val: &I))
517 if (CB->cannotDuplicate())
518 return false;
519 }
520 return true;
521}
522
523MDNode *Loop::getLoopID() const {
524 MDNode *LoopID = nullptr;
525
526 // Go through the latch blocks and check the terminator for the metadata.
527 SmallVector<BasicBlock *, 4> LatchesBlocks;
528 getLoopLatches(LoopLatches&: LatchesBlocks);
529 for (BasicBlock *BB : LatchesBlocks) {
530 Instruction *TI = BB->getTerminator();
531 MDNode *MD = TI->getMetadata(KindID: LLVMContext::MD_loop);
532
533 if (!MD)
534 return nullptr;
535
536 if (!LoopID)
537 LoopID = MD;
538 else if (MD != LoopID)
539 return nullptr;
540 }
541 if (!LoopID || LoopID->getNumOperands() == 0 ||
542 LoopID->getOperand(I: 0) != LoopID)
543 return nullptr;
544 return LoopID;
545}
546
547void Loop::setLoopID(MDNode *LoopID) const {
548 assert((!LoopID || LoopID->getNumOperands() > 0) &&
549 "Loop ID needs at least one operand");
550 assert((!LoopID || LoopID->getOperand(0) == LoopID) &&
551 "Loop ID should refer to itself");
552
553 SmallVector<BasicBlock *, 4> LoopLatches;
554 getLoopLatches(LoopLatches);
555 for (BasicBlock *BB : LoopLatches)
556 BB->getTerminator()->setMetadata(KindID: LLVMContext::MD_loop, Node: LoopID);
557}
558
559void Loop::setLoopAlreadyUnrolled() {
560 LLVMContext &Context = getHeader()->getContext();
561
562 MDNode *DisableUnrollMD =
563 MDNode::get(Context, MDs: MDString::get(Context, Str: "llvm.loop.unroll.disable"));
564 MDNode *LoopID = getLoopID();
565 MDNode *NewLoopID = makePostTransformationMetadata(
566 Context, OrigLoopID: LoopID, RemovePrefixes: {"llvm.loop.unroll."}, AddAttrs: {DisableUnrollMD});
567 setLoopID(NewLoopID);
568}
569
570void Loop::setLoopMustProgress() {
571 LLVMContext &Context = getHeader()->getContext();
572
573 MDNode *MustProgress = findOptionMDForLoop(TheLoop: this, Name: "llvm.loop.mustprogress");
574
575 if (MustProgress)
576 return;
577
578 MDNode *MustProgressMD =
579 MDNode::get(Context, MDs: MDString::get(Context, Str: "llvm.loop.mustprogress"));
580 MDNode *LoopID = getLoopID();
581 MDNode *NewLoopID =
582 makePostTransformationMetadata(Context, OrigLoopID: LoopID, RemovePrefixes: {}, AddAttrs: {MustProgressMD});
583 setLoopID(NewLoopID);
584}
585
586bool Loop::isAnnotatedParallel() const {
587 MDNode *DesiredLoopIdMetadata = getLoopID();
588
589 if (!DesiredLoopIdMetadata)
590 return false;
591
592 MDNode *ParallelAccesses =
593 findOptionMDForLoop(TheLoop: this, Name: "llvm.loop.parallel_accesses");
594 SmallPtrSet<MDNode *, 4>
595 ParallelAccessGroups; // For scalable 'contains' check.
596 if (ParallelAccesses) {
597 for (const MDOperand &MD : drop_begin(RangeOrContainer: ParallelAccesses->operands())) {
598 MDNode *AccGroup = cast<MDNode>(Val: MD.get());
599 assert(isValidAsAccessGroup(AccGroup) &&
600 "List item must be an access group");
601 ParallelAccessGroups.insert(Ptr: AccGroup);
602 }
603 }
604
605 // The loop branch contains the parallel loop metadata. In order to ensure
606 // that any parallel-loop-unaware optimization pass hasn't added loop-carried
607 // dependencies (thus converted the loop back to a sequential loop), check
608 // that all the memory instructions in the loop belong to an access group that
609 // is parallel to this loop.
610 for (BasicBlock *BB : this->blocks()) {
611 for (Instruction &I : *BB) {
612 if (!I.mayReadOrWriteMemory())
613 continue;
614
615 if (MDNode *AccessGroup = I.getMetadata(KindID: LLVMContext::MD_access_group)) {
616 auto ContainsAccessGroup = [&ParallelAccessGroups](MDNode *AG) -> bool {
617 if (AG->getNumOperands() == 0) {
618 assert(isValidAsAccessGroup(AG) && "Item must be an access group");
619 return ParallelAccessGroups.count(Ptr: AG);
620 }
621
622 for (const MDOperand &AccessListItem : AG->operands()) {
623 MDNode *AccGroup = cast<MDNode>(Val: AccessListItem.get());
624 assert(isValidAsAccessGroup(AccGroup) &&
625 "List item must be an access group");
626 if (ParallelAccessGroups.count(Ptr: AccGroup))
627 return true;
628 }
629 return false;
630 };
631
632 if (ContainsAccessGroup(AccessGroup))
633 continue;
634 }
635
636 // The memory instruction can refer to the loop identifier metadata
637 // directly or indirectly through another list metadata (in case of
638 // nested parallel loops). The loop identifier metadata refers to
639 // itself so we can check both cases with the same routine.
640 MDNode *LoopIdMD =
641 I.getMetadata(KindID: LLVMContext::MD_mem_parallel_loop_access);
642
643 if (!LoopIdMD)
644 return false;
645
646 if (!llvm::is_contained(Range: LoopIdMD->operands(), Element: DesiredLoopIdMetadata))
647 return false;
648 }
649 }
650 return true;
651}
652
653DebugLoc Loop::getStartLoc() const { return getLocRange().getStart(); }
654
655Loop::LocRange Loop::getLocRange() const {
656 // If we have a debug location in the loop ID, then use it.
657 if (MDNode *LoopID = getLoopID()) {
658 DebugLoc Start;
659 // We use the first DebugLoc in the header as the start location of the loop
660 // and if there is a second DebugLoc in the header we use it as end location
661 // of the loop.
662 for (const MDOperand &MDO : llvm::drop_begin(RangeOrContainer: LoopID->operands())) {
663 if (DILocation *L = dyn_cast<DILocation>(Val: MDO)) {
664 if (!Start)
665 Start = DebugLoc(L);
666 else
667 return LocRange(Start, DebugLoc(L));
668 }
669 }
670
671 if (Start)
672 return LocRange(Start);
673 }
674
675 // Try the pre-header first.
676 if (BasicBlock *PHeadBB = getLoopPreheader())
677 if (DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc())
678 return LocRange(DL);
679
680 // If we have no pre-header or there are no instructions with debug
681 // info in it, try the header.
682 if (BasicBlock *HeadBB = getHeader())
683 return LocRange(HeadBB->getTerminator()->getDebugLoc());
684
685 return LocRange();
686}
687
688std::string Loop::getLocStr() const {
689 std::string Result;
690 raw_string_ostream OS(Result);
691 if (const DebugLoc LoopDbgLoc = getStartLoc())
692 LoopDbgLoc.print(OS);
693 else
694 // Just print the module name.
695 OS << getHeader()->getParent()->getParent()->getModuleIdentifier();
696 return Result;
697}
698
699#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
700LLVM_DUMP_METHOD void Loop::dump() const { print(dbgs()); }
701
702LLVM_DUMP_METHOD void Loop::dumpVerbose() const {
703 print(dbgs(), /*Verbose=*/true);
704}
705#endif
706
707//===----------------------------------------------------------------------===//
708// UnloopUpdater implementation
709//
710
711namespace {
712/// Find the new parent loop for all blocks within the "unloop" whose last
713/// backedges has just been removed.
714class UnloopUpdater {
715 Loop &Unloop;
716 LoopInfo *LI;
717
718 LoopBlocksDFS DFS;
719
720 // Map unloop's immediate subloops to their nearest reachable parents. Nested
721 // loops within these subloops will not change parents. However, an immediate
722 // subloop's new parent will be the nearest loop reachable from either its own
723 // exits *or* any of its nested loop's exits.
724 DenseMap<Loop *, Loop *> SubloopParents;
725
726 // Flag the presence of an irreducible backedge whose destination is a block
727 // directly contained by the original unloop.
728 bool FoundIB = false;
729
730public:
731 UnloopUpdater(Loop *UL, LoopInfo *LInfo) : Unloop(*UL), LI(LInfo), DFS(UL) {}
732
733 void updateBlockParents();
734
735 void removeBlocksFromAncestors();
736
737 void updateSubloopParents();
738
739protected:
740 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
741};
742} // end anonymous namespace
743
744/// Update the parent loop for all blocks that are directly contained within the
745/// original "unloop".
746void UnloopUpdater::updateBlockParents() {
747 if (Unloop.getNumBlocks()) {
748 // Perform a post order CFG traversal of all blocks within this loop,
749 // propagating the nearest loop from successors to predecessors.
750 LoopBlocksTraversal Traversal(DFS, LI);
751 for (BasicBlock *POI : Traversal) {
752
753 Loop *L = LI->getLoopFor(BB: POI);
754 Loop *NL = getNearestLoop(BB: POI, BBLoop: L);
755
756 if (NL != L) {
757 // For reducible loops, NL is now an ancestor of Unloop.
758 assert((NL != &Unloop && (!NL || NL->contains(&Unloop))) &&
759 "uninitialized successor");
760 LI->changeLoopFor(BB: POI, L: NL);
761 } else {
762 // Or the current block is part of a subloop, in which case its parent
763 // is unchanged.
764 assert((FoundIB || Unloop.contains(L)) && "uninitialized successor");
765 }
766 }
767 }
768 // Each irreducible loop within the unloop induces a round of iteration using
769 // the DFS result cached by Traversal.
770 bool Changed = FoundIB;
771 for (unsigned NIters = 0; Changed; ++NIters) {
772 assert(NIters < Unloop.getNumBlocks() && "runaway iterative algorithm");
773 (void)NIters;
774
775 // Iterate over the postorder list of blocks, propagating the nearest loop
776 // from successors to predecessors as before.
777 Changed = false;
778 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
779 POE = DFS.endPostorder();
780 POI != POE; ++POI) {
781
782 Loop *L = LI->getLoopFor(BB: *POI);
783 Loop *NL = getNearestLoop(BB: *POI, BBLoop: L);
784 if (NL != L) {
785 assert(NL != &Unloop && (!NL || NL->contains(&Unloop)) &&
786 "uninitialized successor");
787 LI->changeLoopFor(BB: *POI, L: NL);
788 Changed = true;
789 }
790 }
791 }
792}
793
794/// Remove unloop's blocks from all ancestors below their new parents.
795void UnloopUpdater::removeBlocksFromAncestors() {
796 // Remove all unloop's blocks (including those in nested subloops) from
797 // ancestors below the new parent loop.
798 for (BasicBlock *BB : Unloop.blocks()) {
799 Loop *OuterParent = LI->getLoopFor(BB);
800 if (Unloop.contains(L: OuterParent)) {
801 while (OuterParent->getParentLoop() != &Unloop)
802 OuterParent = OuterParent->getParentLoop();
803 OuterParent = SubloopParents[OuterParent];
804 }
805 // Remove blocks from former Ancestors except Unloop itself which will be
806 // deleted.
807 for (Loop *OldParent = Unloop.getParentLoop(); OldParent != OuterParent;
808 OldParent = OldParent->getParentLoop()) {
809 assert(OldParent && "new loop is not an ancestor of the original");
810 OldParent->removeBlockFromLoop(BB);
811 }
812 }
813}
814
815/// Update the parent loop for all subloops directly nested within unloop.
816void UnloopUpdater::updateSubloopParents() {
817 while (!Unloop.isInnermost()) {
818 Loop *Subloop = *std::prev(x: Unloop.end());
819 Unloop.removeChildLoop(I: std::prev(x: Unloop.end()));
820
821 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
822 if (Loop *Parent = SubloopParents[Subloop])
823 Parent->addChildLoop(NewChild: Subloop);
824 else
825 LI->addTopLevelLoop(New: Subloop);
826 }
827}
828
829/// Return the nearest parent loop among this block's successors. If a successor
830/// is a subloop header, consider its parent to be the nearest parent of the
831/// subloop's exits.
832///
833/// For subloop blocks, simply update SubloopParents and return NULL.
834Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
835
836 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
837 // is considered uninitialized.
838 Loop *NearLoop = BBLoop;
839
840 Loop *Subloop = nullptr;
841 if (NearLoop != &Unloop && Unloop.contains(L: NearLoop)) {
842 Subloop = NearLoop;
843 // Find the subloop ancestor that is directly contained within Unloop.
844 while (Subloop->getParentLoop() != &Unloop) {
845 Subloop = Subloop->getParentLoop();
846 assert(Subloop && "subloop is not an ancestor of the original loop");
847 }
848 // Get the current nearest parent of the Subloop exits, initially Unloop.
849 NearLoop = SubloopParents.insert(KV: {Subloop, &Unloop}).first->second;
850 }
851
852 if (succ_empty(BB)) {
853 assert(!Subloop && "subloop blocks must have a successor");
854 NearLoop = nullptr; // unloop blocks may now exit the function.
855 }
856 for (BasicBlock *Succ : successors(BB)) {
857 if (Succ == BB)
858 continue; // self loops are uninteresting
859
860 Loop *L = LI->getLoopFor(BB: Succ);
861 if (L == &Unloop) {
862 // This successor has not been processed. This path must lead to an
863 // irreducible backedge.
864 assert((FoundIB || !DFS.hasPostorder(Succ)) && "should have seen IB");
865 FoundIB = true;
866 }
867 if (L != &Unloop && Unloop.contains(L)) {
868 // Successor is in a subloop.
869 if (Subloop)
870 continue; // Branching within subloops. Ignore it.
871
872 // BB branches from the original into a subloop header.
873 assert(L->getParentLoop() == &Unloop && "cannot skip into nested loops");
874
875 // Get the current nearest parent of the Subloop's exits.
876 L = SubloopParents[L];
877 // L could be Unloop if the only exit was an irreducible backedge.
878 }
879 if (L == &Unloop) {
880 continue;
881 }
882 // Handle critical edges from Unloop into a sibling loop.
883 if (L && !L->contains(L: &Unloop)) {
884 L = L->getParentLoop();
885 }
886 // Remember the nearest parent loop among successors or subloop exits.
887 if (NearLoop == &Unloop || !NearLoop || NearLoop->contains(L))
888 NearLoop = L;
889 }
890 if (Subloop) {
891 SubloopParents[Subloop] = NearLoop;
892 return BBLoop;
893 }
894 return NearLoop;
895}
896
897LoopInfo::LoopInfo(const DomTreeBase<BasicBlock> &DomTree) { analyze(DomTree); }
898
899bool LoopInfo::invalidate(Function &F, const PreservedAnalyses &PA,
900 FunctionAnalysisManager::Invalidator &) {
901 // Check whether the analysis, all analyses on functions, or the function's
902 // CFG have been preserved.
903 auto PAC = PA.getChecker<LoopAnalysis>();
904 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
905 PAC.preservedSet<CFGAnalyses>());
906}
907
908void LoopInfo::erase(Loop *Unloop) {
909 assert(!Unloop->isInvalid() && "Loop has already been erased!");
910
911 llvm::scope_exit InvalidateOnExit([&]() { destroy(L: Unloop); });
912
913 // First handle the special case of no parent loop to simplify the algorithm.
914 if (Unloop->isOutermost()) {
915 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
916 for (BasicBlock *BB : Unloop->blocks()) {
917 // Don't reparent blocks in subloops.
918 if (getLoopFor(BB) != Unloop)
919 continue;
920
921 // Blocks no longer have a parent but are still referenced by Unloop until
922 // the Unloop object is deleted.
923 changeLoopFor(BB, L: nullptr);
924 }
925
926 // Remove the loop from the top-level LoopInfo object.
927 for (iterator I = begin();; ++I) {
928 assert(I != end() && "Couldn't find loop");
929 if (*I == Unloop) {
930 removeLoop(I);
931 break;
932 }
933 }
934
935 // Move all of the subloops to the top-level.
936 while (!Unloop->isInnermost())
937 addTopLevelLoop(New: Unloop->removeChildLoop(I: std::prev(x: Unloop->end())));
938
939 return;
940 }
941
942 // Update the parent loop for all blocks within the loop. Blocks within
943 // subloops will not change parents.
944 UnloopUpdater Updater(Unloop, this);
945 Updater.updateBlockParents();
946
947 // Remove blocks from former ancestor loops.
948 Updater.removeBlocksFromAncestors();
949
950 // Add direct subloops as children in their new parent loop.
951 Updater.updateSubloopParents();
952
953 // Remove unloop from its parent loop.
954 Loop *ParentLoop = Unloop->getParentLoop();
955 for (Loop::iterator I = ParentLoop->begin();; ++I) {
956 assert(I != ParentLoop->end() && "Couldn't find loop");
957 if (*I == Unloop) {
958 ParentLoop->removeChildLoop(I);
959 break;
960 }
961 }
962}
963
964bool LoopInfo::wouldBeOutOfLoopUseRequiringLCSSA(
965 const Value *V, const BasicBlock *ExitBB) const {
966 if (V->getType()->isTokenTy())
967 // We can't form PHIs of token type, so the definition of LCSSA excludes
968 // values of that type.
969 return false;
970
971 const Instruction *I = dyn_cast<Instruction>(Val: V);
972 if (!I)
973 return false;
974 const Loop *L = getLoopFor(BB: I->getParent());
975 if (!L)
976 return false;
977 if (L->contains(BB: ExitBB))
978 // Could be an exit bb of a subloop and contained in defining loop
979 return false;
980
981 // We found a (new) out-of-loop use location, for a value defined in-loop.
982 // (Note that because of LCSSA, we don't have to account for values defined
983 // in sibling loops. Such values will have LCSSA phis of their own in the
984 // common parent loop.)
985 return true;
986}
987
988AnalysisKey LoopAnalysis::Key;
989
990LoopInfo LoopAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
991 // FIXME: Currently we create a LoopInfo from scratch for every function.
992 // This may prove to be too wasteful due to deallocating and re-allocating
993 // memory each time for the underlying map and vector datastructures. At some
994 // point it may prove worthwhile to use a freelist and recycle LoopInfo
995 // objects. I don't want to add that kind of complexity until the scope of
996 // the problem is better understood.
997 LoopInfo LI;
998 LI.analyze(DomTree: AM.getResult<DominatorTreeAnalysis>(IR&: F));
999 return LI;
1000}
1001
1002PreservedAnalyses LoopPrinterPass::run(Function &F,
1003 FunctionAnalysisManager &AM) {
1004 auto &LI = AM.getResult<LoopAnalysis>(IR&: F);
1005 OS << "Loop info for function '" << F.getName() << "':\n";
1006 LI.print(OS);
1007 return PreservedAnalyses::all();
1008}
1009
1010void llvm::printLoop(const Loop &L, raw_ostream &OS,
1011 const std::string &Banner) {
1012 if (forcePrintModuleIR()) {
1013 // handling -print-module-scope
1014 OS << Banner << " (loop: ";
1015 L.getHeader()->printAsOperand(O&: OS, PrintType: false);
1016 OS << ")\n";
1017
1018 // printing whole module
1019 OS << *L.getHeader()->getModule();
1020 return;
1021 }
1022
1023 if (forcePrintFuncIR()) {
1024 // handling -print-loop-func-scope.
1025 // -print-module-scope overrides this.
1026 OS << Banner << " (loop: ";
1027 L.getHeader()->printAsOperand(O&: OS, PrintType: false);
1028 OS << ")\n";
1029
1030 // printing whole function.
1031 OS << *L.getHeader()->getParent();
1032 return;
1033 }
1034
1035 OS << Banner;
1036
1037 auto *PreHeader = L.getLoopPreheader();
1038 if (PreHeader) {
1039 OS << "\n; Preheader:";
1040 PreHeader->print(OS);
1041 OS << "\n; Loop:";
1042 }
1043
1044 for (auto *Block : L.blocks())
1045 if (Block)
1046 Block->print(OS);
1047 else
1048 OS << "Printing <null> block";
1049
1050 SmallVector<BasicBlock *, 8> ExitBlocks;
1051 L.getExitBlocks(ExitBlocks);
1052 if (!ExitBlocks.empty()) {
1053 OS << "\n; Exit blocks";
1054 for (auto *Block : ExitBlocks)
1055 if (Block)
1056 Block->print(OS);
1057 else
1058 OS << "Printing <null> block";
1059 }
1060}
1061
1062MDNode *llvm::findOptionMDForLoopID(MDNode *LoopID, StringRef Name) {
1063 // No loop metadata node, no loop properties.
1064 if (!LoopID)
1065 return nullptr;
1066
1067 // First operand should refer to the metadata node itself, for legacy reasons.
1068 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1069 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1070
1071 // Iterate over the metdata node operands and look for MDString metadata.
1072 for (const MDOperand &MDO : llvm::drop_begin(RangeOrContainer: LoopID->operands())) {
1073 MDNode *MD = dyn_cast<MDNode>(Val: MDO);
1074 if (!MD || MD->getNumOperands() < 1)
1075 continue;
1076 MDString *S = dyn_cast<MDString>(Val: MD->getOperand(I: 0));
1077 if (!S)
1078 continue;
1079 // Return the operand node if MDString holds expected metadata.
1080 if (Name == S->getString())
1081 return MD;
1082 }
1083
1084 // Loop property not found.
1085 return nullptr;
1086}
1087
1088MDNode *llvm::findOptionMDForLoop(const Loop *TheLoop, StringRef Name) {
1089 return findOptionMDForLoopID(LoopID: TheLoop->getLoopID(), Name);
1090}
1091
1092/// Find string metadata for loop
1093///
1094/// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
1095/// operand or null otherwise. If the string metadata is not found return
1096/// Optional's not-a-value.
1097std::optional<const MDOperand *>
1098llvm::findStringMetadataForLoop(const Loop *TheLoop, StringRef Name) {
1099 MDNode *MD = findOptionMDForLoop(TheLoop, Name);
1100 if (!MD)
1101 return std::nullopt;
1102 switch (MD->getNumOperands()) {
1103 case 1:
1104 return nullptr;
1105 case 2:
1106 return &MD->getOperand(I: 1);
1107 default:
1108 llvm_unreachable("loop metadata has 0 or 1 operand");
1109 }
1110}
1111
1112std::optional<bool> llvm::getOptionalBoolLoopAttribute(const Loop *TheLoop,
1113 StringRef Name) {
1114 MDNode *MD = findOptionMDForLoop(TheLoop, Name);
1115 if (!MD)
1116 return std::nullopt;
1117 switch (MD->getNumOperands()) {
1118 case 1:
1119 // When the value is absent it is interpreted as 'attribute set'.
1120 return true;
1121 case 2:
1122 if (ConstantInt *IntMD =
1123 mdconst::extract_or_null<ConstantInt>(MD: MD->getOperand(I: 1).get()))
1124 return IntMD->getZExtValue();
1125 return true;
1126 }
1127 llvm_unreachable("unexpected number of options");
1128}
1129
1130bool llvm::getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name) {
1131 return getOptionalBoolLoopAttribute(TheLoop, Name).value_or(u: false);
1132}
1133
1134std::optional<int> llvm::getOptionalIntLoopAttribute(const Loop *TheLoop,
1135 StringRef Name) {
1136 const MDOperand *AttrMD =
1137 findStringMetadataForLoop(TheLoop, Name).value_or(u: nullptr);
1138 if (!AttrMD)
1139 return std::nullopt;
1140
1141 ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(MD: AttrMD->get());
1142 if (!IntMD)
1143 return std::nullopt;
1144
1145 return IntMD->getSExtValue();
1146}
1147
1148int llvm::getIntLoopAttribute(const Loop *TheLoop, StringRef Name,
1149 int Default) {
1150 return getOptionalIntLoopAttribute(TheLoop, Name).value_or(u&: Default);
1151}
1152
1153CallBase *llvm::getLoopConvergenceHeart(const Loop *TheLoop) {
1154 BasicBlock *H = TheLoop->getHeader();
1155 for (Instruction &II : *H) {
1156 if (auto *CB = dyn_cast<CallBase>(Val: &II)) {
1157 if (!CB->isConvergent())
1158 continue;
1159 // This is the heart if it uses a token defined outside the loop. The
1160 // verifier has already checked that only the loop intrinsic can use such
1161 // a token.
1162 if (auto *Token = CB->getConvergenceControlToken()) {
1163 auto *TokenDef = cast<Instruction>(Val: Token);
1164 if (!TheLoop->contains(BB: TokenDef->getParent()))
1165 return CB;
1166 }
1167 return nullptr;
1168 }
1169 }
1170 return nullptr;
1171}
1172
1173bool llvm::isFinite(const Loop *L) {
1174 return L->getHeader()->getParent()->willReturn();
1175}
1176
1177static const char *LLVMLoopMustProgress = "llvm.loop.mustprogress";
1178
1179bool llvm::hasMustProgress(const Loop *L) {
1180 return getBooleanLoopAttribute(TheLoop: L, Name: LLVMLoopMustProgress);
1181}
1182
1183bool llvm::isMustProgress(const Loop *L) {
1184 return L->getHeader()->getParent()->mustProgress() || hasMustProgress(L);
1185}
1186
1187bool llvm::isValidAsAccessGroup(MDNode *Node) {
1188 return Node->getNumOperands() == 0 && Node->isDistinct();
1189}
1190
1191MDNode *llvm::makePostTransformationMetadata(LLVMContext &Context,
1192 MDNode *OrigLoopID,
1193 ArrayRef<StringRef> RemovePrefixes,
1194 ArrayRef<MDNode *> AddAttrs) {
1195 // First remove any existing loop metadata related to this transformation.
1196 SmallVector<Metadata *, 4> MDs;
1197
1198 // Reserve first location for self reference to the LoopID metadata node.
1199 MDs.push_back(Elt: nullptr);
1200
1201 // Remove metadata for the transformation that has been applied or that became
1202 // outdated.
1203 if (OrigLoopID) {
1204 for (const MDOperand &MDO : llvm::drop_begin(RangeOrContainer: OrigLoopID->operands())) {
1205 bool IsVectorMetadata = false;
1206 Metadata *Op = MDO;
1207 if (MDNode *MD = dyn_cast<MDNode>(Val: Op)) {
1208 const MDString *S = dyn_cast<MDString>(Val: MD->getOperand(I: 0));
1209 if (S)
1210 IsVectorMetadata =
1211 llvm::any_of(Range&: RemovePrefixes, P: [S](StringRef Prefix) -> bool {
1212 return S->getString().starts_with(Prefix);
1213 });
1214 }
1215 if (!IsVectorMetadata)
1216 MDs.push_back(Elt: Op);
1217 }
1218 }
1219
1220 // Add metadata to avoid reapplying a transformation, such as
1221 // llvm.loop.unroll.disable and llvm.loop.isvectorized.
1222 MDs.append(in_start: AddAttrs.begin(), in_end: AddAttrs.end());
1223
1224 MDNode *NewLoopID = MDNode::getDistinct(Context, MDs);
1225 // Replace the temporary node with a self-reference.
1226 NewLoopID->replaceOperandWith(I: 0, New: NewLoopID);
1227 return NewLoopID;
1228}
1229
1230//===----------------------------------------------------------------------===//
1231// LoopInfo implementation
1232//
1233
1234LoopInfoWrapperPass::LoopInfoWrapperPass() : FunctionPass(ID) {}
1235
1236char LoopInfoWrapperPass::ID = 0;
1237INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
1238 true, true)
1239INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1240INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
1241 true, true)
1242
1243bool LoopInfoWrapperPass::runOnFunction(Function &) {
1244 releaseMemory();
1245 LI.analyze(DomTree: getAnalysis<DominatorTreeWrapperPass>().getDomTree());
1246 return false;
1247}
1248
1249void LoopInfoWrapperPass::verifyAnalysis() const {
1250 // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
1251 // function each time verifyAnalysis is called is very expensive. The
1252 // -verify-loop-info option can enable this. In order to perform some
1253 // checking by default, LoopPass has been taught to call verifyLoop manually
1254 // during loop pass sequences.
1255 if (VerifyLoopInfo) {
1256 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1257 LI.verify(DomTree: DT);
1258 }
1259}
1260
1261void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1262 AU.setPreservesAll();
1263 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
1264}
1265
1266void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
1267 LI.print(OS);
1268}
1269
1270PreservedAnalyses LoopVerifierPass::run(Function &F,
1271 FunctionAnalysisManager &AM) {
1272 LoopInfo &LI = AM.getResult<LoopAnalysis>(IR&: F);
1273 auto &DT = AM.getResult<DominatorTreeAnalysis>(IR&: F);
1274 LI.verify(DomTree: DT);
1275 return PreservedAnalyses::all();
1276}
1277
1278//===----------------------------------------------------------------------===//
1279// LoopBlocksDFS implementation
1280//
1281
1282/// Traverse the loop blocks and store the DFS result.
1283/// Useful for clients that just want the final DFS result and don't need to
1284/// visit blocks during the initial traversal.
1285void LoopBlocksDFS::perform(const LoopInfo *LI) {
1286 LoopBlocksTraversal Traversal(*this, LI);
1287 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
1288 POE = Traversal.end();
1289 POI != POE; ++POI)
1290 ;
1291}
1292