1 //===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
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 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.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Analysis/LoopInfo.h"
17 #include "llvm/ADT/DepthFirstIterator.h"
18 #include "llvm/ADT/ScopeExit.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/Analysis/IVDescriptors.h"
21 #include "llvm/Analysis/LoopInfoImpl.h"
22 #include "llvm/Analysis/LoopIterator.h"
23 #include "llvm/Analysis/MemorySSA.h"
24 #include "llvm/Analysis/MemorySSAUpdater.h"
25 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
26 #include "llvm/Analysis/ValueTracking.h"
27 #include "llvm/Config/llvm-config.h"
28 #include "llvm/IR/CFG.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DebugLoc.h"
31 #include "llvm/IR/Dominators.h"
32 #include "llvm/IR/IRPrintingPasses.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Metadata.h"
36 #include "llvm/IR/PassManager.h"
37 #include "llvm/InitializePasses.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/raw_ostream.h"
44 // Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
45 template class llvm::LoopBase<BasicBlock, Loop>;
46 template class llvm::LoopInfoBase<BasicBlock, Loop>;
48 // Always verify loopinfo if expensive checking is enabled.
49 #ifdef EXPENSIVE_CHECKS
50 bool llvm::VerifyLoopInfo = true;
52 bool llvm::VerifyLoopInfo = false;
54 static cl::opt<bool, true>
55 VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
56 cl::Hidden, cl::desc("Verify loop info (time consuming)"));
58 //===----------------------------------------------------------------------===//
59 // Loop implementation
62 bool Loop::isLoopInvariant(const Value *V) const {
63 if (const Instruction *I = dyn_cast<Instruction>(V))
65 return true; // All non-instructions are loop invariant
68 bool Loop::hasLoopInvariantOperands(const Instruction *I) const {
69 return all_of(I->operands(), [this](Value *V) { return isLoopInvariant(V); });
72 bool Loop::makeLoopInvariant(Value *V, bool &Changed, Instruction *InsertPt,
73 MemorySSAUpdater *MSSAU) const {
74 if (Instruction *I = dyn_cast<Instruction>(V))
75 return makeLoopInvariant(I, Changed, InsertPt, MSSAU);
76 return true; // All non-instructions are loop-invariant.
79 bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
80 Instruction *InsertPt,
81 MemorySSAUpdater *MSSAU) const {
82 // Test if the value is already loop-invariant.
83 if (isLoopInvariant(I))
85 if (!isSafeToSpeculativelyExecute(I))
87 if (I->mayReadFromMemory())
89 // EH block instructions are immobile.
92 // Determine the insertion point, unless one was given.
94 BasicBlock *Preheader = getLoopPreheader();
95 // Without a preheader, hoisting is not feasible.
98 InsertPt = Preheader->getTerminator();
100 // Don't hoist instructions with loop-variant operands.
101 for (Value *Operand : I->operands())
102 if (!makeLoopInvariant(Operand, Changed, InsertPt, MSSAU))
106 I->moveBefore(InsertPt);
108 if (auto *MUD = MSSAU->getMemorySSA()->getMemoryAccess(I))
109 MSSAU->moveToPlace(MUD, InsertPt->getParent(),
110 MemorySSA::BeforeTerminator);
112 // There is possibility of hoisting this instruction above some arbitrary
113 // condition. Any metadata defined on it can be control dependent on this
114 // condition. Conservatively strip it here so that we don't give any wrong
115 // information to the optimizer.
116 I->dropUnknownNonDebugMetadata();
122 bool Loop::getIncomingAndBackEdge(BasicBlock *&Incoming,
123 BasicBlock *&Backedge) const {
124 BasicBlock *H = getHeader();
128 pred_iterator PI = pred_begin(H);
129 assert(PI != pred_end(H) && "Loop must have at least one backedge!");
131 if (PI == pred_end(H))
132 return false; // dead loop
134 if (PI != pred_end(H))
135 return false; // multiple backedges?
137 if (contains(Incoming)) {
138 if (contains(Backedge))
140 std::swap(Incoming, Backedge);
141 } else if (!contains(Backedge))
144 assert(Incoming && Backedge && "expected non-null incoming and backedges");
148 PHINode *Loop::getCanonicalInductionVariable() const {
149 BasicBlock *H = getHeader();
151 BasicBlock *Incoming = nullptr, *Backedge = nullptr;
152 if (!getIncomingAndBackEdge(Incoming, Backedge))
155 // Loop over all of the PHI nodes, looking for a canonical indvar.
156 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
157 PHINode *PN = cast<PHINode>(I);
158 if (ConstantInt *CI =
159 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
161 if (Instruction *Inc =
162 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
163 if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
164 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
171 /// Get the latch condition instruction.
172 static ICmpInst *getLatchCmpInst(const Loop &L) {
173 if (BasicBlock *Latch = L.getLoopLatch())
174 if (BranchInst *BI = dyn_cast_or_null<BranchInst>(Latch->getTerminator()))
175 if (BI->isConditional())
176 return dyn_cast<ICmpInst>(BI->getCondition());
181 /// Return the final value of the loop induction variable if found.
182 static Value *findFinalIVValue(const Loop &L, const PHINode &IndVar,
183 const Instruction &StepInst) {
184 ICmpInst *LatchCmpInst = getLatchCmpInst(L);
188 Value *Op0 = LatchCmpInst->getOperand(0);
189 Value *Op1 = LatchCmpInst->getOperand(1);
190 if (Op0 == &IndVar || Op0 == &StepInst)
193 if (Op1 == &IndVar || Op1 == &StepInst)
199 Optional<Loop::LoopBounds> Loop::LoopBounds::getBounds(const Loop &L,
201 ScalarEvolution &SE) {
202 InductionDescriptor IndDesc;
203 if (!InductionDescriptor::isInductionPHI(&IndVar, &L, &SE, IndDesc))
206 Value *InitialIVValue = IndDesc.getStartValue();
207 Instruction *StepInst = IndDesc.getInductionBinOp();
208 if (!InitialIVValue || !StepInst)
211 const SCEV *Step = IndDesc.getStep();
212 Value *StepInstOp1 = StepInst->getOperand(1);
213 Value *StepInstOp0 = StepInst->getOperand(0);
214 Value *StepValue = nullptr;
215 if (SE.getSCEV(StepInstOp1) == Step)
216 StepValue = StepInstOp1;
217 else if (SE.getSCEV(StepInstOp0) == Step)
218 StepValue = StepInstOp0;
220 Value *FinalIVValue = findFinalIVValue(L, IndVar, *StepInst);
224 return LoopBounds(L, *InitialIVValue, *StepInst, StepValue, *FinalIVValue,
228 using Direction = Loop::LoopBounds::Direction;
230 ICmpInst::Predicate Loop::LoopBounds::getCanonicalPredicate() const {
231 BasicBlock *Latch = L.getLoopLatch();
232 assert(Latch && "Expecting valid latch");
234 BranchInst *BI = dyn_cast_or_null<BranchInst>(Latch->getTerminator());
235 assert(BI && BI->isConditional() && "Expecting conditional latch branch");
237 ICmpInst *LatchCmpInst = dyn_cast<ICmpInst>(BI->getCondition());
238 assert(LatchCmpInst &&
239 "Expecting the latch compare instruction to be a CmpInst");
241 // Need to inverse the predicate when first successor is not the loop
243 ICmpInst::Predicate Pred = (BI->getSuccessor(0) == L.getHeader())
244 ? LatchCmpInst->getPredicate()
245 : LatchCmpInst->getInversePredicate();
247 if (LatchCmpInst->getOperand(0) == &getFinalIVValue())
248 Pred = ICmpInst::getSwappedPredicate(Pred);
250 // Need to flip strictness of the predicate when the latch compare instruction
251 // is not using StepInst
252 if (LatchCmpInst->getOperand(0) == &getStepInst() ||
253 LatchCmpInst->getOperand(1) == &getStepInst())
256 // Cannot flip strictness of NE and EQ
257 if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
258 return ICmpInst::getFlippedStrictnessPredicate(Pred);
260 Direction D = getDirection();
261 if (D == Direction::Increasing)
262 return ICmpInst::ICMP_SLT;
264 if (D == Direction::Decreasing)
265 return ICmpInst::ICMP_SGT;
267 // If cannot determine the direction, then unable to find the canonical
269 return ICmpInst::BAD_ICMP_PREDICATE;
272 Direction Loop::LoopBounds::getDirection() const {
273 if (const SCEVAddRecExpr *StepAddRecExpr =
274 dyn_cast<SCEVAddRecExpr>(SE.getSCEV(&getStepInst())))
275 if (const SCEV *StepRecur = StepAddRecExpr->getStepRecurrence(SE)) {
276 if (SE.isKnownPositive(StepRecur))
277 return Direction::Increasing;
278 if (SE.isKnownNegative(StepRecur))
279 return Direction::Decreasing;
282 return Direction::Unknown;
285 Optional<Loop::LoopBounds> Loop::getBounds(ScalarEvolution &SE) const {
286 if (PHINode *IndVar = getInductionVariable(SE))
287 return LoopBounds::getBounds(*this, *IndVar, SE);
292 PHINode *Loop::getInductionVariable(ScalarEvolution &SE) const {
293 if (!isLoopSimplifyForm())
296 BasicBlock *Header = getHeader();
297 assert(Header && "Expected a valid loop header");
298 ICmpInst *CmpInst = getLatchCmpInst(*this);
302 Instruction *LatchCmpOp0 = dyn_cast<Instruction>(CmpInst->getOperand(0));
303 Instruction *LatchCmpOp1 = dyn_cast<Instruction>(CmpInst->getOperand(1));
305 for (PHINode &IndVar : Header->phis()) {
306 InductionDescriptor IndDesc;
307 if (!InductionDescriptor::isInductionPHI(&IndVar, this, &SE, IndDesc))
310 Instruction *StepInst = IndDesc.getInductionBinOp();
313 // IndVar = phi[{InitialValue, preheader}, {StepInst, latch}]
314 // StepInst = IndVar + step
315 // cmp = StepInst < FinalValue
316 if (StepInst == LatchCmpOp0 || StepInst == LatchCmpOp1)
320 // IndVar = phi[{InitialValue, preheader}, {StepInst, latch}]
321 // StepInst = IndVar + step
322 // cmp = IndVar < FinalValue
323 if (&IndVar == LatchCmpOp0 || &IndVar == LatchCmpOp1)
330 bool Loop::getInductionDescriptor(ScalarEvolution &SE,
331 InductionDescriptor &IndDesc) const {
332 if (PHINode *IndVar = getInductionVariable(SE))
333 return InductionDescriptor::isInductionPHI(IndVar, this, &SE, IndDesc);
338 bool Loop::isAuxiliaryInductionVariable(PHINode &AuxIndVar,
339 ScalarEvolution &SE) const {
340 // Located in the loop header
341 BasicBlock *Header = getHeader();
342 if (AuxIndVar.getParent() != Header)
345 // No uses outside of the loop
346 for (User *U : AuxIndVar.users())
347 if (const Instruction *I = dyn_cast<Instruction>(U))
351 InductionDescriptor IndDesc;
352 if (!InductionDescriptor::isInductionPHI(&AuxIndVar, this, &SE, IndDesc))
355 // The step instruction opcode should be add or sub.
356 if (IndDesc.getInductionOpcode() != Instruction::Add &&
357 IndDesc.getInductionOpcode() != Instruction::Sub)
360 // Incremented by a loop invariant step for each loop iteration
361 return SE.isLoopInvariant(IndDesc.getStep(), this);
364 BranchInst *Loop::getLoopGuardBranch() const {
365 if (!isLoopSimplifyForm())
368 BasicBlock *Preheader = getLoopPreheader();
369 assert(Preheader && getLoopLatch() &&
370 "Expecting a loop with valid preheader and latch");
372 // Loop should be in rotate form.
373 if (!isRotatedForm())
376 // Disallow loops with more than one unique exit block, as we do not verify
377 // that GuardOtherSucc post dominates all exit blocks.
378 BasicBlock *ExitFromLatch = getUniqueExitBlock();
382 BasicBlock *ExitFromLatchSucc = ExitFromLatch->getUniqueSuccessor();
383 if (!ExitFromLatchSucc)
386 BasicBlock *GuardBB = Preheader->getUniquePredecessor();
390 assert(GuardBB->getTerminator() && "Expecting valid guard terminator");
392 BranchInst *GuardBI = dyn_cast<BranchInst>(GuardBB->getTerminator());
393 if (!GuardBI || GuardBI->isUnconditional())
396 BasicBlock *GuardOtherSucc = (GuardBI->getSuccessor(0) == Preheader)
397 ? GuardBI->getSuccessor(1)
398 : GuardBI->getSuccessor(0);
399 return (GuardOtherSucc == ExitFromLatchSucc) ? GuardBI : nullptr;
402 bool Loop::isCanonical(ScalarEvolution &SE) const {
403 InductionDescriptor IndDesc;
404 if (!getInductionDescriptor(SE, IndDesc))
407 ConstantInt *Init = dyn_cast_or_null<ConstantInt>(IndDesc.getStartValue());
408 if (!Init || !Init->isZero())
411 if (IndDesc.getInductionOpcode() != Instruction::Add)
414 ConstantInt *Step = IndDesc.getConstIntStepValue();
415 if (!Step || !Step->isOne())
421 // Check that 'BB' doesn't have any uses outside of the 'L'
422 static bool isBlockInLCSSAForm(const Loop &L, const BasicBlock &BB,
423 const DominatorTree &DT) {
424 for (const Instruction &I : BB) {
425 // Tokens can't be used in PHI nodes and live-out tokens prevent loop
426 // optimizations, so for the purposes of considered LCSSA form, we
428 if (I.getType()->isTokenTy())
431 for (const Use &U : I.uses()) {
432 const Instruction *UI = cast<Instruction>(U.getUser());
433 const BasicBlock *UserBB = UI->getParent();
434 if (const PHINode *P = dyn_cast<PHINode>(UI))
435 UserBB = P->getIncomingBlock(U);
437 // Check the current block, as a fast-path, before checking whether
438 // the use is anywhere in the loop. Most values are used in the same
439 // block they are defined in. Also, blocks not reachable from the
440 // entry are special; uses in them don't need to go through PHIs.
441 if (UserBB != &BB && !L.contains(UserBB) &&
442 DT.isReachableFromEntry(UserBB))
449 bool Loop::isLCSSAForm(const DominatorTree &DT) const {
450 // For each block we check that it doesn't have any uses outside of this loop.
451 return all_of(this->blocks(), [&](const BasicBlock *BB) {
452 return isBlockInLCSSAForm(*this, *BB, DT);
456 bool Loop::isRecursivelyLCSSAForm(const DominatorTree &DT,
457 const LoopInfo &LI) const {
458 // For each block we check that it doesn't have any uses outside of its
459 // innermost loop. This process will transitively guarantee that the current
460 // loop and all of the nested loops are in LCSSA form.
461 return all_of(this->blocks(), [&](const BasicBlock *BB) {
462 return isBlockInLCSSAForm(*LI.getLoopFor(BB), *BB, DT);
466 bool Loop::isLoopSimplifyForm() const {
467 // Normal-form loops have a preheader, a single backedge, and all of their
468 // exits have all their predecessors inside the loop.
469 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
472 // Routines that reform the loop CFG and split edges often fail on indirectbr.
473 bool Loop::isSafeToClone() const {
474 // Return false if any loop blocks contain indirectbrs, or there are any calls
475 // to noduplicate functions.
476 // FIXME: it should be ok to clone CallBrInst's if we correctly update the
477 // operand list to reflect the newly cloned labels.
478 for (BasicBlock *BB : this->blocks()) {
479 if (isa<IndirectBrInst>(BB->getTerminator()) ||
480 isa<CallBrInst>(BB->getTerminator()))
483 for (Instruction &I : *BB)
484 if (auto *CB = dyn_cast<CallBase>(&I))
485 if (CB->cannotDuplicate())
491 MDNode *Loop::getLoopID() const {
492 MDNode *LoopID = nullptr;
494 // Go through the latch blocks and check the terminator for the metadata.
495 SmallVector<BasicBlock *, 4> LatchesBlocks;
496 getLoopLatches(LatchesBlocks);
497 for (BasicBlock *BB : LatchesBlocks) {
498 Instruction *TI = BB->getTerminator();
499 MDNode *MD = TI->getMetadata(LLVMContext::MD_loop);
506 else if (MD != LoopID)
509 if (!LoopID || LoopID->getNumOperands() == 0 ||
510 LoopID->getOperand(0) != LoopID)
515 void Loop::setLoopID(MDNode *LoopID) const {
516 assert((!LoopID || LoopID->getNumOperands() > 0) &&
517 "Loop ID needs at least one operand");
518 assert((!LoopID || LoopID->getOperand(0) == LoopID) &&
519 "Loop ID should refer to itself");
521 SmallVector<BasicBlock *, 4> LoopLatches;
522 getLoopLatches(LoopLatches);
523 for (BasicBlock *BB : LoopLatches)
524 BB->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID);
527 void Loop::setLoopAlreadyUnrolled() {
528 LLVMContext &Context = getHeader()->getContext();
530 MDNode *DisableUnrollMD =
531 MDNode::get(Context, MDString::get(Context, "llvm.loop.unroll.disable"));
532 MDNode *LoopID = getLoopID();
533 MDNode *NewLoopID = makePostTransformationMetadata(
534 Context, LoopID, {"llvm.loop.unroll."}, {DisableUnrollMD});
535 setLoopID(NewLoopID);
538 bool Loop::isAnnotatedParallel() const {
539 MDNode *DesiredLoopIdMetadata = getLoopID();
541 if (!DesiredLoopIdMetadata)
544 MDNode *ParallelAccesses =
545 findOptionMDForLoop(this, "llvm.loop.parallel_accesses");
546 SmallPtrSet<MDNode *, 4>
547 ParallelAccessGroups; // For scalable 'contains' check.
548 if (ParallelAccesses) {
549 for (const MDOperand &MD : drop_begin(ParallelAccesses->operands(), 1)) {
550 MDNode *AccGroup = cast<MDNode>(MD.get());
551 assert(isValidAsAccessGroup(AccGroup) &&
552 "List item must be an access group");
553 ParallelAccessGroups.insert(AccGroup);
557 // The loop branch contains the parallel loop metadata. In order to ensure
558 // that any parallel-loop-unaware optimization pass hasn't added loop-carried
559 // dependencies (thus converted the loop back to a sequential loop), check
560 // that all the memory instructions in the loop belong to an access group that
561 // is parallel to this loop.
562 for (BasicBlock *BB : this->blocks()) {
563 for (Instruction &I : *BB) {
564 if (!I.mayReadOrWriteMemory())
567 if (MDNode *AccessGroup = I.getMetadata(LLVMContext::MD_access_group)) {
568 auto ContainsAccessGroup = [&ParallelAccessGroups](MDNode *AG) -> bool {
569 if (AG->getNumOperands() == 0) {
570 assert(isValidAsAccessGroup(AG) && "Item must be an access group");
571 return ParallelAccessGroups.count(AG);
574 for (const MDOperand &AccessListItem : AG->operands()) {
575 MDNode *AccGroup = cast<MDNode>(AccessListItem.get());
576 assert(isValidAsAccessGroup(AccGroup) &&
577 "List item must be an access group");
578 if (ParallelAccessGroups.count(AccGroup))
584 if (ContainsAccessGroup(AccessGroup))
588 // The memory instruction can refer to the loop identifier metadata
589 // directly or indirectly through another list metadata (in case of
590 // nested parallel loops). The loop identifier metadata refers to
591 // itself so we can check both cases with the same routine.
593 I.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
598 bool LoopIdMDFound = false;
599 for (const MDOperand &MDOp : LoopIdMD->operands()) {
600 if (MDOp == DesiredLoopIdMetadata) {
601 LoopIdMDFound = true;
613 DebugLoc Loop::getStartLoc() const { return getLocRange().getStart(); }
615 Loop::LocRange Loop::getLocRange() const {
616 // If we have a debug location in the loop ID, then use it.
617 if (MDNode *LoopID = getLoopID()) {
619 // We use the first DebugLoc in the header as the start location of the loop
620 // and if there is a second DebugLoc in the header we use it as end location
622 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
623 if (DILocation *L = dyn_cast<DILocation>(LoopID->getOperand(i))) {
627 return LocRange(Start, DebugLoc(L));
632 return LocRange(Start);
635 // Try the pre-header first.
636 if (BasicBlock *PHeadBB = getLoopPreheader())
637 if (DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc())
640 // If we have no pre-header or there are no instructions with debug
641 // info in it, try the header.
642 if (BasicBlock *HeadBB = getHeader())
643 return LocRange(HeadBB->getTerminator()->getDebugLoc());
648 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
649 LLVM_DUMP_METHOD void Loop::dump() const { print(dbgs()); }
651 LLVM_DUMP_METHOD void Loop::dumpVerbose() const {
652 print(dbgs(), /*Depth=*/0, /*Verbose=*/true);
656 //===----------------------------------------------------------------------===//
657 // UnloopUpdater implementation
661 /// Find the new parent loop for all blocks within the "unloop" whose last
662 /// backedges has just been removed.
663 class UnloopUpdater {
669 // Map unloop's immediate subloops to their nearest reachable parents. Nested
670 // loops within these subloops will not change parents. However, an immediate
671 // subloop's new parent will be the nearest loop reachable from either its own
672 // exits *or* any of its nested loop's exits.
673 DenseMap<Loop *, Loop *> SubloopParents;
675 // Flag the presence of an irreducible backedge whose destination is a block
676 // directly contained by the original unloop.
680 UnloopUpdater(Loop *UL, LoopInfo *LInfo)
681 : Unloop(*UL), LI(LInfo), DFS(UL), FoundIB(false) {}
683 void updateBlockParents();
685 void removeBlocksFromAncestors();
687 void updateSubloopParents();
690 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
692 } // end anonymous namespace
694 /// Update the parent loop for all blocks that are directly contained within the
695 /// original "unloop".
696 void UnloopUpdater::updateBlockParents() {
697 if (Unloop.getNumBlocks()) {
698 // Perform a post order CFG traversal of all blocks within this loop,
699 // propagating the nearest loop from successors to predecessors.
700 LoopBlocksTraversal Traversal(DFS, LI);
701 for (BasicBlock *POI : Traversal) {
703 Loop *L = LI->getLoopFor(POI);
704 Loop *NL = getNearestLoop(POI, L);
707 // For reducible loops, NL is now an ancestor of Unloop.
708 assert((NL != &Unloop && (!NL || NL->contains(&Unloop))) &&
709 "uninitialized successor");
710 LI->changeLoopFor(POI, NL);
712 // Or the current block is part of a subloop, in which case its parent
714 assert((FoundIB || Unloop.contains(L)) && "uninitialized successor");
718 // Each irreducible loop within the unloop induces a round of iteration using
719 // the DFS result cached by Traversal.
720 bool Changed = FoundIB;
721 for (unsigned NIters = 0; Changed; ++NIters) {
722 assert(NIters < Unloop.getNumBlocks() && "runaway iterative algorithm");
724 // Iterate over the postorder list of blocks, propagating the nearest loop
725 // from successors to predecessors as before.
727 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
728 POE = DFS.endPostorder();
731 Loop *L = LI->getLoopFor(*POI);
732 Loop *NL = getNearestLoop(*POI, L);
734 assert(NL != &Unloop && (!NL || NL->contains(&Unloop)) &&
735 "uninitialized successor");
736 LI->changeLoopFor(*POI, NL);
743 /// Remove unloop's blocks from all ancestors below their new parents.
744 void UnloopUpdater::removeBlocksFromAncestors() {
745 // Remove all unloop's blocks (including those in nested subloops) from
746 // ancestors below the new parent loop.
747 for (Loop::block_iterator BI = Unloop.block_begin(), BE = Unloop.block_end();
749 Loop *OuterParent = LI->getLoopFor(*BI);
750 if (Unloop.contains(OuterParent)) {
751 while (OuterParent->getParentLoop() != &Unloop)
752 OuterParent = OuterParent->getParentLoop();
753 OuterParent = SubloopParents[OuterParent];
755 // Remove blocks from former Ancestors except Unloop itself which will be
757 for (Loop *OldParent = Unloop.getParentLoop(); OldParent != OuterParent;
758 OldParent = OldParent->getParentLoop()) {
759 assert(OldParent && "new loop is not an ancestor of the original");
760 OldParent->removeBlockFromLoop(*BI);
765 /// Update the parent loop for all subloops directly nested within unloop.
766 void UnloopUpdater::updateSubloopParents() {
767 while (!Unloop.empty()) {
768 Loop *Subloop = *std::prev(Unloop.end());
769 Unloop.removeChildLoop(std::prev(Unloop.end()));
771 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
772 if (Loop *Parent = SubloopParents[Subloop])
773 Parent->addChildLoop(Subloop);
775 LI->addTopLevelLoop(Subloop);
779 /// Return the nearest parent loop among this block's successors. If a successor
780 /// is a subloop header, consider its parent to be the nearest parent of the
783 /// For subloop blocks, simply update SubloopParents and return NULL.
784 Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
786 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
787 // is considered uninitialized.
788 Loop *NearLoop = BBLoop;
790 Loop *Subloop = nullptr;
791 if (NearLoop != &Unloop && Unloop.contains(NearLoop)) {
793 // Find the subloop ancestor that is directly contained within Unloop.
794 while (Subloop->getParentLoop() != &Unloop) {
795 Subloop = Subloop->getParentLoop();
796 assert(Subloop && "subloop is not an ancestor of the original loop");
798 // Get the current nearest parent of the Subloop exits, initially Unloop.
799 NearLoop = SubloopParents.insert({Subloop, &Unloop}).first->second;
802 succ_iterator I = succ_begin(BB), E = succ_end(BB);
804 assert(!Subloop && "subloop blocks must have a successor");
805 NearLoop = nullptr; // unloop blocks may now exit the function.
807 for (; I != E; ++I) {
809 continue; // self loops are uninteresting
811 Loop *L = LI->getLoopFor(*I);
813 // This successor has not been processed. This path must lead to an
814 // irreducible backedge.
815 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
818 if (L != &Unloop && Unloop.contains(L)) {
819 // Successor is in a subloop.
821 continue; // Branching within subloops. Ignore it.
823 // BB branches from the original into a subloop header.
824 assert(L->getParentLoop() == &Unloop && "cannot skip into nested loops");
826 // Get the current nearest parent of the Subloop's exits.
827 L = SubloopParents[L];
828 // L could be Unloop if the only exit was an irreducible backedge.
833 // Handle critical edges from Unloop into a sibling loop.
834 if (L && !L->contains(&Unloop)) {
835 L = L->getParentLoop();
837 // Remember the nearest parent loop among successors or subloop exits.
838 if (NearLoop == &Unloop || !NearLoop || NearLoop->contains(L))
842 SubloopParents[Subloop] = NearLoop;
848 LoopInfo::LoopInfo(const DomTreeBase<BasicBlock> &DomTree) { analyze(DomTree); }
850 bool LoopInfo::invalidate(Function &F, const PreservedAnalyses &PA,
851 FunctionAnalysisManager::Invalidator &) {
852 // Check whether the analysis, all analyses on functions, or the function's
853 // CFG have been preserved.
854 auto PAC = PA.getChecker<LoopAnalysis>();
855 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
856 PAC.preservedSet<CFGAnalyses>());
859 void LoopInfo::erase(Loop *Unloop) {
860 assert(!Unloop->isInvalid() && "Loop has already been erased!");
862 auto InvalidateOnExit = make_scope_exit([&]() { destroy(Unloop); });
864 // First handle the special case of no parent loop to simplify the algorithm.
865 if (!Unloop->getParentLoop()) {
866 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
867 for (Loop::block_iterator I = Unloop->block_begin(),
868 E = Unloop->block_end();
871 // Don't reparent blocks in subloops.
872 if (getLoopFor(*I) != Unloop)
875 // Blocks no longer have a parent but are still referenced by Unloop until
876 // the Unloop object is deleted.
877 changeLoopFor(*I, nullptr);
880 // Remove the loop from the top-level LoopInfo object.
881 for (iterator I = begin();; ++I) {
882 assert(I != end() && "Couldn't find loop");
889 // Move all of the subloops to the top-level.
890 while (!Unloop->empty())
891 addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
896 // Update the parent loop for all blocks within the loop. Blocks within
897 // subloops will not change parents.
898 UnloopUpdater Updater(Unloop, this);
899 Updater.updateBlockParents();
901 // Remove blocks from former ancestor loops.
902 Updater.removeBlocksFromAncestors();
904 // Add direct subloops as children in their new parent loop.
905 Updater.updateSubloopParents();
907 // Remove unloop from its parent loop.
908 Loop *ParentLoop = Unloop->getParentLoop();
909 for (Loop::iterator I = ParentLoop->begin();; ++I) {
910 assert(I != ParentLoop->end() && "Couldn't find loop");
912 ParentLoop->removeChildLoop(I);
918 AnalysisKey LoopAnalysis::Key;
920 LoopInfo LoopAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
921 // FIXME: Currently we create a LoopInfo from scratch for every function.
922 // This may prove to be too wasteful due to deallocating and re-allocating
923 // memory each time for the underlying map and vector datastructures. At some
924 // point it may prove worthwhile to use a freelist and recycle LoopInfo
925 // objects. I don't want to add that kind of complexity until the scope of
926 // the problem is better understood.
928 LI.analyze(AM.getResult<DominatorTreeAnalysis>(F));
932 PreservedAnalyses LoopPrinterPass::run(Function &F,
933 FunctionAnalysisManager &AM) {
934 AM.getResult<LoopAnalysis>(F).print(OS);
935 return PreservedAnalyses::all();
938 void llvm::printLoop(Loop &L, raw_ostream &OS, const std::string &Banner) {
940 if (forcePrintModuleIR()) {
941 // handling -print-module-scope
942 OS << Banner << " (loop: ";
943 L.getHeader()->printAsOperand(OS, false);
946 // printing whole module
947 OS << *L.getHeader()->getModule();
953 auto *PreHeader = L.getLoopPreheader();
955 OS << "\n; Preheader:";
956 PreHeader->print(OS);
960 for (auto *Block : L.blocks())
964 OS << "Printing <null> block";
966 SmallVector<BasicBlock *, 8> ExitBlocks;
967 L.getExitBlocks(ExitBlocks);
968 if (!ExitBlocks.empty()) {
969 OS << "\n; Exit blocks";
970 for (auto *Block : ExitBlocks)
974 OS << "Printing <null> block";
978 MDNode *llvm::findOptionMDForLoopID(MDNode *LoopID, StringRef Name) {
979 // No loop metadata node, no loop properties.
983 // First operand should refer to the metadata node itself, for legacy reasons.
984 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
985 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
987 // Iterate over the metdata node operands and look for MDString metadata.
988 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
989 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
990 if (!MD || MD->getNumOperands() < 1)
992 MDString *S = dyn_cast<MDString>(MD->getOperand(0));
995 // Return the operand node if MDString holds expected metadata.
996 if (Name.equals(S->getString()))
1000 // Loop property not found.
1004 MDNode *llvm::findOptionMDForLoop(const Loop *TheLoop, StringRef Name) {
1005 return findOptionMDForLoopID(TheLoop->getLoopID(), Name);
1008 bool llvm::isValidAsAccessGroup(MDNode *Node) {
1009 return Node->getNumOperands() == 0 && Node->isDistinct();
1012 MDNode *llvm::makePostTransformationMetadata(LLVMContext &Context,
1014 ArrayRef<StringRef> RemovePrefixes,
1015 ArrayRef<MDNode *> AddAttrs) {
1016 // First remove any existing loop metadata related to this transformation.
1017 SmallVector<Metadata *, 4> MDs;
1019 // Reserve first location for self reference to the LoopID metadata node.
1020 TempMDTuple TempNode = MDNode::getTemporary(Context, None);
1021 MDs.push_back(TempNode.get());
1023 // Remove metadata for the transformation that has been applied or that became
1026 for (unsigned i = 1, ie = OrigLoopID->getNumOperands(); i < ie; ++i) {
1027 bool IsVectorMetadata = false;
1028 Metadata *Op = OrigLoopID->getOperand(i);
1029 if (MDNode *MD = dyn_cast<MDNode>(Op)) {
1030 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1033 llvm::any_of(RemovePrefixes, [S](StringRef Prefix) -> bool {
1034 return S->getString().startswith(Prefix);
1037 if (!IsVectorMetadata)
1042 // Add metadata to avoid reapplying a transformation, such as
1043 // llvm.loop.unroll.disable and llvm.loop.isvectorized.
1044 MDs.append(AddAttrs.begin(), AddAttrs.end());
1046 MDNode *NewLoopID = MDNode::getDistinct(Context, MDs);
1047 // Replace the temporary node with a self-reference.
1048 NewLoopID->replaceOperandWith(0, NewLoopID);
1052 //===----------------------------------------------------------------------===//
1053 // LoopInfo implementation
1056 LoopInfoWrapperPass::LoopInfoWrapperPass() : FunctionPass(ID) {
1057 initializeLoopInfoWrapperPassPass(*PassRegistry::getPassRegistry());
1060 char LoopInfoWrapperPass::ID = 0;
1061 INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
1063 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1064 INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
1067 bool LoopInfoWrapperPass::runOnFunction(Function &) {
1069 LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
1073 void LoopInfoWrapperPass::verifyAnalysis() const {
1074 // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
1075 // function each time verifyAnalysis is called is very expensive. The
1076 // -verify-loop-info option can enable this. In order to perform some
1077 // checking by default, LoopPass has been taught to call verifyLoop manually
1078 // during loop pass sequences.
1079 if (VerifyLoopInfo) {
1080 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1085 void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1086 AU.setPreservesAll();
1087 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
1090 void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
1094 PreservedAnalyses LoopVerifierPass::run(Function &F,
1095 FunctionAnalysisManager &AM) {
1096 LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
1097 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1099 return PreservedAnalyses::all();
1102 //===----------------------------------------------------------------------===//
1103 // LoopBlocksDFS implementation
1106 /// Traverse the loop blocks and store the DFS result.
1107 /// Useful for clients that just want the final DFS result and don't need to
1108 /// visit blocks during the initial traversal.
1109 void LoopBlocksDFS::perform(LoopInfo *LI) {
1110 LoopBlocksTraversal Traversal(*this, LI);
1111 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
1112 POE = Traversal.end();