xref: /freebsd-src/contrib/llvm-project/llvm/lib/Analysis/LoopInfo.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file defines the LoopInfo class that is used to identify natural loops
100b57cec5SDimitry Andric // and determine the loop depth of various nodes of the CFG.  Note that the
110b57cec5SDimitry Andric // loops identified may actually be several natural loops that share the same
120b57cec5SDimitry Andric // header node... not just a single natural loop.
130b57cec5SDimitry Andric //
140b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
150b57cec5SDimitry Andric 
160b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
170b57cec5SDimitry Andric #include "llvm/ADT/ScopeExit.h"
180b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
190b57cec5SDimitry Andric #include "llvm/Analysis/IVDescriptors.h"
200b57cec5SDimitry Andric #include "llvm/Analysis/LoopIterator.h"
21fe6060f1SDimitry Andric #include "llvm/Analysis/LoopNestAnalysis.h"
220b57cec5SDimitry Andric #include "llvm/Analysis/MemorySSA.h"
230b57cec5SDimitry Andric #include "llvm/Analysis/MemorySSAUpdater.h"
240b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h"
250b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
260b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
270b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
280b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
290b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
300b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
310b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
320b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
330b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
34*0fca6ea1SDimitry Andric #include "llvm/IR/Module.h"
350b57cec5SDimitry Andric #include "llvm/IR/PassManager.h"
36e8d8bef9SDimitry Andric #include "llvm/IR/PrintPasses.h"
37480093f4SDimitry Andric #include "llvm/InitializePasses.h"
380b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
3906c3fb27SDimitry Andric #include "llvm/Support/GenericLoopInfoImpl.h"
400b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
410b57cec5SDimitry Andric using namespace llvm;
420b57cec5SDimitry Andric 
430b57cec5SDimitry Andric // Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
440b57cec5SDimitry Andric template class llvm::LoopBase<BasicBlock, Loop>;
450b57cec5SDimitry Andric template class llvm::LoopInfoBase<BasicBlock, Loop>;
460b57cec5SDimitry Andric 
470b57cec5SDimitry Andric // Always verify loopinfo if expensive checking is enabled.
480b57cec5SDimitry Andric #ifdef EXPENSIVE_CHECKS
490b57cec5SDimitry Andric bool llvm::VerifyLoopInfo = true;
500b57cec5SDimitry Andric #else
510b57cec5SDimitry Andric bool llvm::VerifyLoopInfo = false;
520b57cec5SDimitry Andric #endif
530b57cec5SDimitry Andric static cl::opt<bool, true>
540b57cec5SDimitry Andric     VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
550b57cec5SDimitry Andric                     cl::Hidden, cl::desc("Verify loop info (time consuming)"));
560b57cec5SDimitry Andric 
570b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
580b57cec5SDimitry Andric // Loop implementation
590b57cec5SDimitry Andric //
600b57cec5SDimitry Andric 
610b57cec5SDimitry Andric bool Loop::isLoopInvariant(const Value *V) const {
620b57cec5SDimitry Andric   if (const Instruction *I = dyn_cast<Instruction>(V))
630b57cec5SDimitry Andric     return !contains(I);
640b57cec5SDimitry Andric   return true; // All non-instructions are loop invariant
650b57cec5SDimitry Andric }
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric bool Loop::hasLoopInvariantOperands(const Instruction *I) const {
680b57cec5SDimitry Andric   return all_of(I->operands(), [this](Value *V) { return isLoopInvariant(V); });
690b57cec5SDimitry Andric }
700b57cec5SDimitry Andric 
710b57cec5SDimitry Andric bool Loop::makeLoopInvariant(Value *V, bool &Changed, Instruction *InsertPt,
72bdd1243dSDimitry Andric                              MemorySSAUpdater *MSSAU,
73bdd1243dSDimitry Andric                              ScalarEvolution *SE) const {
740b57cec5SDimitry Andric   if (Instruction *I = dyn_cast<Instruction>(V))
75bdd1243dSDimitry Andric     return makeLoopInvariant(I, Changed, InsertPt, MSSAU, SE);
760b57cec5SDimitry Andric   return true; // All non-instructions are loop-invariant.
770b57cec5SDimitry Andric }
780b57cec5SDimitry Andric 
790b57cec5SDimitry Andric bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
80bdd1243dSDimitry Andric                              Instruction *InsertPt, MemorySSAUpdater *MSSAU,
81bdd1243dSDimitry Andric                              ScalarEvolution *SE) const {
820b57cec5SDimitry Andric   // Test if the value is already loop-invariant.
830b57cec5SDimitry Andric   if (isLoopInvariant(I))
840b57cec5SDimitry Andric     return true;
850b57cec5SDimitry Andric   if (!isSafeToSpeculativelyExecute(I))
860b57cec5SDimitry Andric     return false;
870b57cec5SDimitry Andric   if (I->mayReadFromMemory())
880b57cec5SDimitry Andric     return false;
890b57cec5SDimitry Andric   // EH block instructions are immobile.
900b57cec5SDimitry Andric   if (I->isEHPad())
910b57cec5SDimitry Andric     return false;
920b57cec5SDimitry Andric   // Determine the insertion point, unless one was given.
930b57cec5SDimitry Andric   if (!InsertPt) {
940b57cec5SDimitry Andric     BasicBlock *Preheader = getLoopPreheader();
950b57cec5SDimitry Andric     // Without a preheader, hoisting is not feasible.
960b57cec5SDimitry Andric     if (!Preheader)
970b57cec5SDimitry Andric       return false;
980b57cec5SDimitry Andric     InsertPt = Preheader->getTerminator();
990b57cec5SDimitry Andric   }
1000b57cec5SDimitry Andric   // Don't hoist instructions with loop-variant operands.
1010b57cec5SDimitry Andric   for (Value *Operand : I->operands())
102bdd1243dSDimitry Andric     if (!makeLoopInvariant(Operand, Changed, InsertPt, MSSAU, SE))
1030b57cec5SDimitry Andric       return false;
1040b57cec5SDimitry Andric 
1050b57cec5SDimitry Andric   // Hoist.
1060b57cec5SDimitry Andric   I->moveBefore(InsertPt);
1070b57cec5SDimitry Andric   if (MSSAU)
1080b57cec5SDimitry Andric     if (auto *MUD = MSSAU->getMemorySSA()->getMemoryAccess(I))
109480093f4SDimitry Andric       MSSAU->moveToPlace(MUD, InsertPt->getParent(),
110480093f4SDimitry Andric                          MemorySSA::BeforeTerminator);
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric   // There is possibility of hoisting this instruction above some arbitrary
1130b57cec5SDimitry Andric   // condition. Any metadata defined on it can be control dependent on this
1140b57cec5SDimitry Andric   // condition. Conservatively strip it here so that we don't give any wrong
1150b57cec5SDimitry Andric   // information to the optimizer.
1160b57cec5SDimitry Andric   I->dropUnknownNonDebugMetadata();
1170b57cec5SDimitry Andric 
118bdd1243dSDimitry Andric   if (SE)
119bdd1243dSDimitry Andric     SE->forgetBlockAndLoopDispositions(I);
120bdd1243dSDimitry Andric 
1210b57cec5SDimitry Andric   Changed = true;
1220b57cec5SDimitry Andric   return true;
1230b57cec5SDimitry Andric }
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric bool Loop::getIncomingAndBackEdge(BasicBlock *&Incoming,
1260b57cec5SDimitry Andric                                   BasicBlock *&Backedge) const {
1270b57cec5SDimitry Andric   BasicBlock *H = getHeader();
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric   Incoming = nullptr;
1300b57cec5SDimitry Andric   Backedge = nullptr;
1310b57cec5SDimitry Andric   pred_iterator PI = pred_begin(H);
1320b57cec5SDimitry Andric   assert(PI != pred_end(H) && "Loop must have at least one backedge!");
1330b57cec5SDimitry Andric   Backedge = *PI++;
1340b57cec5SDimitry Andric   if (PI == pred_end(H))
1350b57cec5SDimitry Andric     return false; // dead loop
1360b57cec5SDimitry Andric   Incoming = *PI++;
1370b57cec5SDimitry Andric   if (PI != pred_end(H))
1380b57cec5SDimitry Andric     return false; // multiple backedges?
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric   if (contains(Incoming)) {
1410b57cec5SDimitry Andric     if (contains(Backedge))
1420b57cec5SDimitry Andric       return false;
1430b57cec5SDimitry Andric     std::swap(Incoming, Backedge);
1440b57cec5SDimitry Andric   } else if (!contains(Backedge))
1450b57cec5SDimitry Andric     return false;
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric   assert(Incoming && Backedge && "expected non-null incoming and backedges");
1480b57cec5SDimitry Andric   return true;
1490b57cec5SDimitry Andric }
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric PHINode *Loop::getCanonicalInductionVariable() const {
1520b57cec5SDimitry Andric   BasicBlock *H = getHeader();
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric   BasicBlock *Incoming = nullptr, *Backedge = nullptr;
1550b57cec5SDimitry Andric   if (!getIncomingAndBackEdge(Incoming, Backedge))
1560b57cec5SDimitry Andric     return nullptr;
1570b57cec5SDimitry Andric 
1580b57cec5SDimitry Andric   // Loop over all of the PHI nodes, looking for a canonical indvar.
1590b57cec5SDimitry Andric   for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
1600b57cec5SDimitry Andric     PHINode *PN = cast<PHINode>(I);
1610b57cec5SDimitry Andric     if (ConstantInt *CI =
1620b57cec5SDimitry Andric             dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
1630b57cec5SDimitry Andric       if (CI->isZero())
1640b57cec5SDimitry Andric         if (Instruction *Inc =
1650b57cec5SDimitry Andric                 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
1660b57cec5SDimitry Andric           if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
1670b57cec5SDimitry Andric             if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
1680b57cec5SDimitry Andric               if (CI->isOne())
1690b57cec5SDimitry Andric                 return PN;
1700b57cec5SDimitry Andric   }
1710b57cec5SDimitry Andric   return nullptr;
1720b57cec5SDimitry Andric }
1730b57cec5SDimitry Andric 
1740b57cec5SDimitry Andric /// Get the latch condition instruction.
175fe6060f1SDimitry Andric ICmpInst *Loop::getLatchCmpInst() const {
176fe6060f1SDimitry Andric   if (BasicBlock *Latch = getLoopLatch())
1770b57cec5SDimitry Andric     if (BranchInst *BI = dyn_cast_or_null<BranchInst>(Latch->getTerminator()))
1780b57cec5SDimitry Andric       if (BI->isConditional())
1790b57cec5SDimitry Andric         return dyn_cast<ICmpInst>(BI->getCondition());
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric   return nullptr;
1820b57cec5SDimitry Andric }
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric /// Return the final value of the loop induction variable if found.
1850b57cec5SDimitry Andric static Value *findFinalIVValue(const Loop &L, const PHINode &IndVar,
1860b57cec5SDimitry Andric                                const Instruction &StepInst) {
187fe6060f1SDimitry Andric   ICmpInst *LatchCmpInst = L.getLatchCmpInst();
1880b57cec5SDimitry Andric   if (!LatchCmpInst)
1890b57cec5SDimitry Andric     return nullptr;
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric   Value *Op0 = LatchCmpInst->getOperand(0);
1920b57cec5SDimitry Andric   Value *Op1 = LatchCmpInst->getOperand(1);
1930b57cec5SDimitry Andric   if (Op0 == &IndVar || Op0 == &StepInst)
1940b57cec5SDimitry Andric     return Op1;
1950b57cec5SDimitry Andric 
1960b57cec5SDimitry Andric   if (Op1 == &IndVar || Op1 == &StepInst)
1970b57cec5SDimitry Andric     return Op0;
1980b57cec5SDimitry Andric 
1990b57cec5SDimitry Andric   return nullptr;
2000b57cec5SDimitry Andric }
2010b57cec5SDimitry Andric 
202bdd1243dSDimitry Andric std::optional<Loop::LoopBounds>
203bdd1243dSDimitry Andric Loop::LoopBounds::getBounds(const Loop &L, PHINode &IndVar,
2040b57cec5SDimitry Andric                             ScalarEvolution &SE) {
2050b57cec5SDimitry Andric   InductionDescriptor IndDesc;
2060b57cec5SDimitry Andric   if (!InductionDescriptor::isInductionPHI(&IndVar, &L, &SE, IndDesc))
207bdd1243dSDimitry Andric     return std::nullopt;
2080b57cec5SDimitry Andric 
2090b57cec5SDimitry Andric   Value *InitialIVValue = IndDesc.getStartValue();
2100b57cec5SDimitry Andric   Instruction *StepInst = IndDesc.getInductionBinOp();
2110b57cec5SDimitry Andric   if (!InitialIVValue || !StepInst)
212bdd1243dSDimitry Andric     return std::nullopt;
2130b57cec5SDimitry Andric 
2140b57cec5SDimitry Andric   const SCEV *Step = IndDesc.getStep();
2150b57cec5SDimitry Andric   Value *StepInstOp1 = StepInst->getOperand(1);
2160b57cec5SDimitry Andric   Value *StepInstOp0 = StepInst->getOperand(0);
2170b57cec5SDimitry Andric   Value *StepValue = nullptr;
2180b57cec5SDimitry Andric   if (SE.getSCEV(StepInstOp1) == Step)
2190b57cec5SDimitry Andric     StepValue = StepInstOp1;
2200b57cec5SDimitry Andric   else if (SE.getSCEV(StepInstOp0) == Step)
2210b57cec5SDimitry Andric     StepValue = StepInstOp0;
2220b57cec5SDimitry Andric 
2230b57cec5SDimitry Andric   Value *FinalIVValue = findFinalIVValue(L, IndVar, *StepInst);
2240b57cec5SDimitry Andric   if (!FinalIVValue)
225bdd1243dSDimitry Andric     return std::nullopt;
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric   return LoopBounds(L, *InitialIVValue, *StepInst, StepValue, *FinalIVValue,
2280b57cec5SDimitry Andric                     SE);
2290b57cec5SDimitry Andric }
2300b57cec5SDimitry Andric 
2310b57cec5SDimitry Andric using Direction = Loop::LoopBounds::Direction;
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric ICmpInst::Predicate Loop::LoopBounds::getCanonicalPredicate() const {
2340b57cec5SDimitry Andric   BasicBlock *Latch = L.getLoopLatch();
2350b57cec5SDimitry Andric   assert(Latch && "Expecting valid latch");
2360b57cec5SDimitry Andric 
2370b57cec5SDimitry Andric   BranchInst *BI = dyn_cast_or_null<BranchInst>(Latch->getTerminator());
2380b57cec5SDimitry Andric   assert(BI && BI->isConditional() && "Expecting conditional latch branch");
2390b57cec5SDimitry Andric 
2400b57cec5SDimitry Andric   ICmpInst *LatchCmpInst = dyn_cast<ICmpInst>(BI->getCondition());
2410b57cec5SDimitry Andric   assert(LatchCmpInst &&
2420b57cec5SDimitry Andric          "Expecting the latch compare instruction to be a CmpInst");
2430b57cec5SDimitry Andric 
2440b57cec5SDimitry Andric   // Need to inverse the predicate when first successor is not the loop
2450b57cec5SDimitry Andric   // header
2460b57cec5SDimitry Andric   ICmpInst::Predicate Pred = (BI->getSuccessor(0) == L.getHeader())
2470b57cec5SDimitry Andric                                  ? LatchCmpInst->getPredicate()
2480b57cec5SDimitry Andric                                  : LatchCmpInst->getInversePredicate();
2490b57cec5SDimitry Andric 
2500b57cec5SDimitry Andric   if (LatchCmpInst->getOperand(0) == &getFinalIVValue())
2510b57cec5SDimitry Andric     Pred = ICmpInst::getSwappedPredicate(Pred);
2520b57cec5SDimitry Andric 
2530b57cec5SDimitry Andric   // Need to flip strictness of the predicate when the latch compare instruction
2540b57cec5SDimitry Andric   // is not using StepInst
2550b57cec5SDimitry Andric   if (LatchCmpInst->getOperand(0) == &getStepInst() ||
2560b57cec5SDimitry Andric       LatchCmpInst->getOperand(1) == &getStepInst())
2570b57cec5SDimitry Andric     return Pred;
2580b57cec5SDimitry Andric 
2590b57cec5SDimitry Andric   // Cannot flip strictness of NE and EQ
2600b57cec5SDimitry Andric   if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
2610b57cec5SDimitry Andric     return ICmpInst::getFlippedStrictnessPredicate(Pred);
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric   Direction D = getDirection();
2640b57cec5SDimitry Andric   if (D == Direction::Increasing)
2650b57cec5SDimitry Andric     return ICmpInst::ICMP_SLT;
2660b57cec5SDimitry Andric 
2670b57cec5SDimitry Andric   if (D == Direction::Decreasing)
2680b57cec5SDimitry Andric     return ICmpInst::ICMP_SGT;
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric   // If cannot determine the direction, then unable to find the canonical
2710b57cec5SDimitry Andric   // predicate
2720b57cec5SDimitry Andric   return ICmpInst::BAD_ICMP_PREDICATE;
2730b57cec5SDimitry Andric }
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric Direction Loop::LoopBounds::getDirection() const {
2760b57cec5SDimitry Andric   if (const SCEVAddRecExpr *StepAddRecExpr =
2770b57cec5SDimitry Andric           dyn_cast<SCEVAddRecExpr>(SE.getSCEV(&getStepInst())))
2780b57cec5SDimitry Andric     if (const SCEV *StepRecur = StepAddRecExpr->getStepRecurrence(SE)) {
2790b57cec5SDimitry Andric       if (SE.isKnownPositive(StepRecur))
2800b57cec5SDimitry Andric         return Direction::Increasing;
2810b57cec5SDimitry Andric       if (SE.isKnownNegative(StepRecur))
2820b57cec5SDimitry Andric         return Direction::Decreasing;
2830b57cec5SDimitry Andric     }
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric   return Direction::Unknown;
2860b57cec5SDimitry Andric }
2870b57cec5SDimitry Andric 
288bdd1243dSDimitry Andric std::optional<Loop::LoopBounds> Loop::getBounds(ScalarEvolution &SE) const {
2890b57cec5SDimitry Andric   if (PHINode *IndVar = getInductionVariable(SE))
2900b57cec5SDimitry Andric     return LoopBounds::getBounds(*this, *IndVar, SE);
2910b57cec5SDimitry Andric 
292bdd1243dSDimitry Andric   return std::nullopt;
2930b57cec5SDimitry Andric }
2940b57cec5SDimitry Andric 
2950b57cec5SDimitry Andric PHINode *Loop::getInductionVariable(ScalarEvolution &SE) const {
2960b57cec5SDimitry Andric   if (!isLoopSimplifyForm())
2970b57cec5SDimitry Andric     return nullptr;
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric   BasicBlock *Header = getHeader();
3000b57cec5SDimitry Andric   assert(Header && "Expected a valid loop header");
301fe6060f1SDimitry Andric   ICmpInst *CmpInst = getLatchCmpInst();
3020b57cec5SDimitry Andric   if (!CmpInst)
3030b57cec5SDimitry Andric     return nullptr;
3040b57cec5SDimitry Andric 
305349cc55cSDimitry Andric   Value *LatchCmpOp0 = CmpInst->getOperand(0);
306349cc55cSDimitry Andric   Value *LatchCmpOp1 = CmpInst->getOperand(1);
3070b57cec5SDimitry Andric 
3080b57cec5SDimitry Andric   for (PHINode &IndVar : Header->phis()) {
3090b57cec5SDimitry Andric     InductionDescriptor IndDesc;
3100b57cec5SDimitry Andric     if (!InductionDescriptor::isInductionPHI(&IndVar, this, &SE, IndDesc))
3110b57cec5SDimitry Andric       continue;
3120b57cec5SDimitry Andric 
313349cc55cSDimitry Andric     BasicBlock *Latch = getLoopLatch();
314349cc55cSDimitry Andric     Value *StepInst = IndVar.getIncomingValueForBlock(Latch);
3150b57cec5SDimitry Andric 
3160b57cec5SDimitry Andric     // case 1:
3170b57cec5SDimitry Andric     // IndVar = phi[{InitialValue, preheader}, {StepInst, latch}]
3180b57cec5SDimitry Andric     // StepInst = IndVar + step
3190b57cec5SDimitry Andric     // cmp = StepInst < FinalValue
3200b57cec5SDimitry Andric     if (StepInst == LatchCmpOp0 || StepInst == LatchCmpOp1)
3210b57cec5SDimitry Andric       return &IndVar;
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric     // case 2:
3240b57cec5SDimitry Andric     // IndVar = phi[{InitialValue, preheader}, {StepInst, latch}]
3250b57cec5SDimitry Andric     // StepInst = IndVar + step
3260b57cec5SDimitry Andric     // cmp = IndVar < FinalValue
3270b57cec5SDimitry Andric     if (&IndVar == LatchCmpOp0 || &IndVar == LatchCmpOp1)
3280b57cec5SDimitry Andric       return &IndVar;
3290b57cec5SDimitry Andric   }
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric   return nullptr;
3320b57cec5SDimitry Andric }
3330b57cec5SDimitry Andric 
3340b57cec5SDimitry Andric bool Loop::getInductionDescriptor(ScalarEvolution &SE,
3350b57cec5SDimitry Andric                                   InductionDescriptor &IndDesc) const {
3360b57cec5SDimitry Andric   if (PHINode *IndVar = getInductionVariable(SE))
3370b57cec5SDimitry Andric     return InductionDescriptor::isInductionPHI(IndVar, this, &SE, IndDesc);
3380b57cec5SDimitry Andric 
3390b57cec5SDimitry Andric   return false;
3400b57cec5SDimitry Andric }
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric bool Loop::isAuxiliaryInductionVariable(PHINode &AuxIndVar,
3430b57cec5SDimitry Andric                                         ScalarEvolution &SE) const {
3440b57cec5SDimitry Andric   // Located in the loop header
3450b57cec5SDimitry Andric   BasicBlock *Header = getHeader();
3460b57cec5SDimitry Andric   if (AuxIndVar.getParent() != Header)
3470b57cec5SDimitry Andric     return false;
3480b57cec5SDimitry Andric 
3490b57cec5SDimitry Andric   // No uses outside of the loop
3500b57cec5SDimitry Andric   for (User *U : AuxIndVar.users())
3510b57cec5SDimitry Andric     if (const Instruction *I = dyn_cast<Instruction>(U))
3520b57cec5SDimitry Andric       if (!contains(I))
3530b57cec5SDimitry Andric         return false;
3540b57cec5SDimitry Andric 
3550b57cec5SDimitry Andric   InductionDescriptor IndDesc;
3560b57cec5SDimitry Andric   if (!InductionDescriptor::isInductionPHI(&AuxIndVar, this, &SE, IndDesc))
3570b57cec5SDimitry Andric     return false;
3580b57cec5SDimitry Andric 
3590b57cec5SDimitry Andric   // The step instruction opcode should be add or sub.
3600b57cec5SDimitry Andric   if (IndDesc.getInductionOpcode() != Instruction::Add &&
3610b57cec5SDimitry Andric       IndDesc.getInductionOpcode() != Instruction::Sub)
3620b57cec5SDimitry Andric     return false;
3630b57cec5SDimitry Andric 
3640b57cec5SDimitry Andric   // Incremented by a loop invariant step for each loop iteration
3650b57cec5SDimitry Andric   return SE.isLoopInvariant(IndDesc.getStep(), this);
3660b57cec5SDimitry Andric }
3670b57cec5SDimitry Andric 
3688bcb0991SDimitry Andric BranchInst *Loop::getLoopGuardBranch() const {
3698bcb0991SDimitry Andric   if (!isLoopSimplifyForm())
3708bcb0991SDimitry Andric     return nullptr;
3718bcb0991SDimitry Andric 
3728bcb0991SDimitry Andric   BasicBlock *Preheader = getLoopPreheader();
373480093f4SDimitry Andric   assert(Preheader && getLoopLatch() &&
3748bcb0991SDimitry Andric          "Expecting a loop with valid preheader and latch");
3758bcb0991SDimitry Andric 
3768bcb0991SDimitry Andric   // Loop should be in rotate form.
377480093f4SDimitry Andric   if (!isRotatedForm())
3788bcb0991SDimitry Andric     return nullptr;
3798bcb0991SDimitry Andric 
3808bcb0991SDimitry Andric   // Disallow loops with more than one unique exit block, as we do not verify
3818bcb0991SDimitry Andric   // that GuardOtherSucc post dominates all exit blocks.
3828bcb0991SDimitry Andric   BasicBlock *ExitFromLatch = getUniqueExitBlock();
3838bcb0991SDimitry Andric   if (!ExitFromLatch)
3848bcb0991SDimitry Andric     return nullptr;
3858bcb0991SDimitry Andric 
3868bcb0991SDimitry Andric   BasicBlock *GuardBB = Preheader->getUniquePredecessor();
3878bcb0991SDimitry Andric   if (!GuardBB)
3888bcb0991SDimitry Andric     return nullptr;
3898bcb0991SDimitry Andric 
3908bcb0991SDimitry Andric   assert(GuardBB->getTerminator() && "Expecting valid guard terminator");
3918bcb0991SDimitry Andric 
3928bcb0991SDimitry Andric   BranchInst *GuardBI = dyn_cast<BranchInst>(GuardBB->getTerminator());
3938bcb0991SDimitry Andric   if (!GuardBI || GuardBI->isUnconditional())
3948bcb0991SDimitry Andric     return nullptr;
3958bcb0991SDimitry Andric 
3968bcb0991SDimitry Andric   BasicBlock *GuardOtherSucc = (GuardBI->getSuccessor(0) == Preheader)
3978bcb0991SDimitry Andric                                    ? GuardBI->getSuccessor(1)
3988bcb0991SDimitry Andric                                    : GuardBI->getSuccessor(0);
399fe6060f1SDimitry Andric 
400fe6060f1SDimitry Andric   // Check if ExitFromLatch (or any BasicBlock which is an empty unique
401fe6060f1SDimitry Andric   // successor of ExitFromLatch) is equal to GuardOtherSucc. If
402fe6060f1SDimitry Andric   // skipEmptyBlockUntil returns GuardOtherSucc, then the guard branch for the
403fe6060f1SDimitry Andric   // loop is GuardBI (return GuardBI), otherwise return nullptr.
404fe6060f1SDimitry Andric   if (&LoopNest::skipEmptyBlockUntil(ExitFromLatch, GuardOtherSucc,
405fe6060f1SDimitry Andric                                      /*CheckUniquePred=*/true) ==
406fe6060f1SDimitry Andric       GuardOtherSucc)
407fe6060f1SDimitry Andric     return GuardBI;
408fe6060f1SDimitry Andric   else
409fe6060f1SDimitry Andric     return nullptr;
4108bcb0991SDimitry Andric }
4118bcb0991SDimitry Andric 
4120b57cec5SDimitry Andric bool Loop::isCanonical(ScalarEvolution &SE) const {
4130b57cec5SDimitry Andric   InductionDescriptor IndDesc;
4140b57cec5SDimitry Andric   if (!getInductionDescriptor(SE, IndDesc))
4150b57cec5SDimitry Andric     return false;
4160b57cec5SDimitry Andric 
4170b57cec5SDimitry Andric   ConstantInt *Init = dyn_cast_or_null<ConstantInt>(IndDesc.getStartValue());
4180b57cec5SDimitry Andric   if (!Init || !Init->isZero())
4190b57cec5SDimitry Andric     return false;
4200b57cec5SDimitry Andric 
4210b57cec5SDimitry Andric   if (IndDesc.getInductionOpcode() != Instruction::Add)
4220b57cec5SDimitry Andric     return false;
4230b57cec5SDimitry Andric 
4240b57cec5SDimitry Andric   ConstantInt *Step = IndDesc.getConstIntStepValue();
4250b57cec5SDimitry Andric   if (!Step || !Step->isOne())
4260b57cec5SDimitry Andric     return false;
4270b57cec5SDimitry Andric 
4280b57cec5SDimitry Andric   return true;
4290b57cec5SDimitry Andric }
4300b57cec5SDimitry Andric 
4310b57cec5SDimitry Andric // Check that 'BB' doesn't have any uses outside of the 'L'
4320b57cec5SDimitry Andric static bool isBlockInLCSSAForm(const Loop &L, const BasicBlock &BB,
433fcaf7f86SDimitry Andric                                const DominatorTree &DT, bool IgnoreTokens) {
4340b57cec5SDimitry Andric   for (const Instruction &I : BB) {
4350b57cec5SDimitry Andric     // Tokens can't be used in PHI nodes and live-out tokens prevent loop
4360b57cec5SDimitry Andric     // optimizations, so for the purposes of considered LCSSA form, we
4370b57cec5SDimitry Andric     // can ignore them.
438fcaf7f86SDimitry Andric     if (IgnoreTokens && I.getType()->isTokenTy())
4390b57cec5SDimitry Andric       continue;
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric     for (const Use &U : I.uses()) {
4420b57cec5SDimitry Andric       const Instruction *UI = cast<Instruction>(U.getUser());
4430b57cec5SDimitry Andric       const BasicBlock *UserBB = UI->getParent();
444e8d8bef9SDimitry Andric 
445e8d8bef9SDimitry Andric       // For practical purposes, we consider that the use in a PHI
446e8d8bef9SDimitry Andric       // occurs in the respective predecessor block. For more info,
447e8d8bef9SDimitry Andric       // see the `phi` doc in LangRef and the LCSSA doc.
4480b57cec5SDimitry Andric       if (const PHINode *P = dyn_cast<PHINode>(UI))
4490b57cec5SDimitry Andric         UserBB = P->getIncomingBlock(U);
4500b57cec5SDimitry Andric 
4510b57cec5SDimitry Andric       // Check the current block, as a fast-path, before checking whether
4520b57cec5SDimitry Andric       // the use is anywhere in the loop.  Most values are used in the same
4530b57cec5SDimitry Andric       // block they are defined in.  Also, blocks not reachable from the
4540b57cec5SDimitry Andric       // entry are special; uses in them don't need to go through PHIs.
4550b57cec5SDimitry Andric       if (UserBB != &BB && !L.contains(UserBB) &&
4560b57cec5SDimitry Andric           DT.isReachableFromEntry(UserBB))
4570b57cec5SDimitry Andric         return false;
4580b57cec5SDimitry Andric     }
4590b57cec5SDimitry Andric   }
4600b57cec5SDimitry Andric   return true;
4610b57cec5SDimitry Andric }
4620b57cec5SDimitry Andric 
463fcaf7f86SDimitry Andric bool Loop::isLCSSAForm(const DominatorTree &DT, bool IgnoreTokens) const {
4640b57cec5SDimitry Andric   // For each block we check that it doesn't have any uses outside of this loop.
4650b57cec5SDimitry Andric   return all_of(this->blocks(), [&](const BasicBlock *BB) {
466fcaf7f86SDimitry Andric     return isBlockInLCSSAForm(*this, *BB, DT, IgnoreTokens);
4670b57cec5SDimitry Andric   });
4680b57cec5SDimitry Andric }
4690b57cec5SDimitry Andric 
470fcaf7f86SDimitry Andric bool Loop::isRecursivelyLCSSAForm(const DominatorTree &DT, const LoopInfo &LI,
471fcaf7f86SDimitry Andric                                   bool IgnoreTokens) const {
4720b57cec5SDimitry Andric   // For each block we check that it doesn't have any uses outside of its
4730b57cec5SDimitry Andric   // innermost loop. This process will transitively guarantee that the current
4740b57cec5SDimitry Andric   // loop and all of the nested loops are in LCSSA form.
4750b57cec5SDimitry Andric   return all_of(this->blocks(), [&](const BasicBlock *BB) {
476fcaf7f86SDimitry Andric     return isBlockInLCSSAForm(*LI.getLoopFor(BB), *BB, DT, IgnoreTokens);
4770b57cec5SDimitry Andric   });
4780b57cec5SDimitry Andric }
4790b57cec5SDimitry Andric 
4800b57cec5SDimitry Andric bool Loop::isLoopSimplifyForm() const {
4810b57cec5SDimitry Andric   // Normal-form loops have a preheader, a single backedge, and all of their
4820b57cec5SDimitry Andric   // exits have all their predecessors inside the loop.
4830b57cec5SDimitry Andric   return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
4840b57cec5SDimitry Andric }
4850b57cec5SDimitry Andric 
4860b57cec5SDimitry Andric // Routines that reform the loop CFG and split edges often fail on indirectbr.
4870b57cec5SDimitry Andric bool Loop::isSafeToClone() const {
4880b57cec5SDimitry Andric   // Return false if any loop blocks contain indirectbrs, or there are any calls
4890b57cec5SDimitry Andric   // to noduplicate functions.
4900b57cec5SDimitry Andric   for (BasicBlock *BB : this->blocks()) {
491fcaf7f86SDimitry Andric     if (isa<IndirectBrInst>(BB->getTerminator()))
4920b57cec5SDimitry Andric       return false;
4930b57cec5SDimitry Andric 
4940b57cec5SDimitry Andric     for (Instruction &I : *BB)
4955ffd83dbSDimitry Andric       if (auto *CB = dyn_cast<CallBase>(&I))
4965ffd83dbSDimitry Andric         if (CB->cannotDuplicate())
4970b57cec5SDimitry Andric           return false;
4980b57cec5SDimitry Andric   }
4990b57cec5SDimitry Andric   return true;
5000b57cec5SDimitry Andric }
5010b57cec5SDimitry Andric 
5020b57cec5SDimitry Andric MDNode *Loop::getLoopID() const {
5030b57cec5SDimitry Andric   MDNode *LoopID = nullptr;
5040b57cec5SDimitry Andric 
5050b57cec5SDimitry Andric   // Go through the latch blocks and check the terminator for the metadata.
5060b57cec5SDimitry Andric   SmallVector<BasicBlock *, 4> LatchesBlocks;
5070b57cec5SDimitry Andric   getLoopLatches(LatchesBlocks);
5080b57cec5SDimitry Andric   for (BasicBlock *BB : LatchesBlocks) {
5090b57cec5SDimitry Andric     Instruction *TI = BB->getTerminator();
5100b57cec5SDimitry Andric     MDNode *MD = TI->getMetadata(LLVMContext::MD_loop);
5110b57cec5SDimitry Andric 
5120b57cec5SDimitry Andric     if (!MD)
5130b57cec5SDimitry Andric       return nullptr;
5140b57cec5SDimitry Andric 
5150b57cec5SDimitry Andric     if (!LoopID)
5160b57cec5SDimitry Andric       LoopID = MD;
5170b57cec5SDimitry Andric     else if (MD != LoopID)
5180b57cec5SDimitry Andric       return nullptr;
5190b57cec5SDimitry Andric   }
5200b57cec5SDimitry Andric   if (!LoopID || LoopID->getNumOperands() == 0 ||
5210b57cec5SDimitry Andric       LoopID->getOperand(0) != LoopID)
5220b57cec5SDimitry Andric     return nullptr;
5230b57cec5SDimitry Andric   return LoopID;
5240b57cec5SDimitry Andric }
5250b57cec5SDimitry Andric 
5260b57cec5SDimitry Andric void Loop::setLoopID(MDNode *LoopID) const {
5270b57cec5SDimitry Andric   assert((!LoopID || LoopID->getNumOperands() > 0) &&
5280b57cec5SDimitry Andric          "Loop ID needs at least one operand");
5290b57cec5SDimitry Andric   assert((!LoopID || LoopID->getOperand(0) == LoopID) &&
5300b57cec5SDimitry Andric          "Loop ID should refer to itself");
5310b57cec5SDimitry Andric 
5320b57cec5SDimitry Andric   SmallVector<BasicBlock *, 4> LoopLatches;
5330b57cec5SDimitry Andric   getLoopLatches(LoopLatches);
5340b57cec5SDimitry Andric   for (BasicBlock *BB : LoopLatches)
5350b57cec5SDimitry Andric     BB->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID);
5360b57cec5SDimitry Andric }
5370b57cec5SDimitry Andric 
5380b57cec5SDimitry Andric void Loop::setLoopAlreadyUnrolled() {
5390b57cec5SDimitry Andric   LLVMContext &Context = getHeader()->getContext();
5400b57cec5SDimitry Andric 
5410b57cec5SDimitry Andric   MDNode *DisableUnrollMD =
5420b57cec5SDimitry Andric       MDNode::get(Context, MDString::get(Context, "llvm.loop.unroll.disable"));
5430b57cec5SDimitry Andric   MDNode *LoopID = getLoopID();
5440b57cec5SDimitry Andric   MDNode *NewLoopID = makePostTransformationMetadata(
5450b57cec5SDimitry Andric       Context, LoopID, {"llvm.loop.unroll."}, {DisableUnrollMD});
5460b57cec5SDimitry Andric   setLoopID(NewLoopID);
5470b57cec5SDimitry Andric }
5480b57cec5SDimitry Andric 
549e8d8bef9SDimitry Andric void Loop::setLoopMustProgress() {
550e8d8bef9SDimitry Andric   LLVMContext &Context = getHeader()->getContext();
551e8d8bef9SDimitry Andric 
552e8d8bef9SDimitry Andric   MDNode *MustProgress = findOptionMDForLoop(this, "llvm.loop.mustprogress");
553e8d8bef9SDimitry Andric 
554e8d8bef9SDimitry Andric   if (MustProgress)
555e8d8bef9SDimitry Andric     return;
556e8d8bef9SDimitry Andric 
557e8d8bef9SDimitry Andric   MDNode *MustProgressMD =
558e8d8bef9SDimitry Andric       MDNode::get(Context, MDString::get(Context, "llvm.loop.mustprogress"));
559e8d8bef9SDimitry Andric   MDNode *LoopID = getLoopID();
560e8d8bef9SDimitry Andric   MDNode *NewLoopID =
561e8d8bef9SDimitry Andric       makePostTransformationMetadata(Context, LoopID, {}, {MustProgressMD});
562e8d8bef9SDimitry Andric   setLoopID(NewLoopID);
563e8d8bef9SDimitry Andric }
564e8d8bef9SDimitry Andric 
5650b57cec5SDimitry Andric bool Loop::isAnnotatedParallel() const {
5660b57cec5SDimitry Andric   MDNode *DesiredLoopIdMetadata = getLoopID();
5670b57cec5SDimitry Andric 
5680b57cec5SDimitry Andric   if (!DesiredLoopIdMetadata)
5690b57cec5SDimitry Andric     return false;
5700b57cec5SDimitry Andric 
5710b57cec5SDimitry Andric   MDNode *ParallelAccesses =
5720b57cec5SDimitry Andric       findOptionMDForLoop(this, "llvm.loop.parallel_accesses");
5730b57cec5SDimitry Andric   SmallPtrSet<MDNode *, 4>
5740b57cec5SDimitry Andric       ParallelAccessGroups; // For scalable 'contains' check.
5750b57cec5SDimitry Andric   if (ParallelAccesses) {
576e8d8bef9SDimitry Andric     for (const MDOperand &MD : drop_begin(ParallelAccesses->operands())) {
5770b57cec5SDimitry Andric       MDNode *AccGroup = cast<MDNode>(MD.get());
5780b57cec5SDimitry Andric       assert(isValidAsAccessGroup(AccGroup) &&
5790b57cec5SDimitry Andric              "List item must be an access group");
5800b57cec5SDimitry Andric       ParallelAccessGroups.insert(AccGroup);
5810b57cec5SDimitry Andric     }
5820b57cec5SDimitry Andric   }
5830b57cec5SDimitry Andric 
5840b57cec5SDimitry Andric   // The loop branch contains the parallel loop metadata. In order to ensure
5850b57cec5SDimitry Andric   // that any parallel-loop-unaware optimization pass hasn't added loop-carried
5860b57cec5SDimitry Andric   // dependencies (thus converted the loop back to a sequential loop), check
5870b57cec5SDimitry Andric   // that all the memory instructions in the loop belong to an access group that
5880b57cec5SDimitry Andric   // is parallel to this loop.
5890b57cec5SDimitry Andric   for (BasicBlock *BB : this->blocks()) {
5900b57cec5SDimitry Andric     for (Instruction &I : *BB) {
5910b57cec5SDimitry Andric       if (!I.mayReadOrWriteMemory())
5920b57cec5SDimitry Andric         continue;
5930b57cec5SDimitry Andric 
5940b57cec5SDimitry Andric       if (MDNode *AccessGroup = I.getMetadata(LLVMContext::MD_access_group)) {
5950b57cec5SDimitry Andric         auto ContainsAccessGroup = [&ParallelAccessGroups](MDNode *AG) -> bool {
5960b57cec5SDimitry Andric           if (AG->getNumOperands() == 0) {
5970b57cec5SDimitry Andric             assert(isValidAsAccessGroup(AG) && "Item must be an access group");
5980b57cec5SDimitry Andric             return ParallelAccessGroups.count(AG);
5990b57cec5SDimitry Andric           }
6000b57cec5SDimitry Andric 
6010b57cec5SDimitry Andric           for (const MDOperand &AccessListItem : AG->operands()) {
6020b57cec5SDimitry Andric             MDNode *AccGroup = cast<MDNode>(AccessListItem.get());
6030b57cec5SDimitry Andric             assert(isValidAsAccessGroup(AccGroup) &&
6040b57cec5SDimitry Andric                    "List item must be an access group");
6050b57cec5SDimitry Andric             if (ParallelAccessGroups.count(AccGroup))
6060b57cec5SDimitry Andric               return true;
6070b57cec5SDimitry Andric           }
6080b57cec5SDimitry Andric           return false;
6090b57cec5SDimitry Andric         };
6100b57cec5SDimitry Andric 
6110b57cec5SDimitry Andric         if (ContainsAccessGroup(AccessGroup))
6120b57cec5SDimitry Andric           continue;
6130b57cec5SDimitry Andric       }
6140b57cec5SDimitry Andric 
6150b57cec5SDimitry Andric       // The memory instruction can refer to the loop identifier metadata
6160b57cec5SDimitry Andric       // directly or indirectly through another list metadata (in case of
6170b57cec5SDimitry Andric       // nested parallel loops). The loop identifier metadata refers to
6180b57cec5SDimitry Andric       // itself so we can check both cases with the same routine.
6190b57cec5SDimitry Andric       MDNode *LoopIdMD =
6200b57cec5SDimitry Andric           I.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
6210b57cec5SDimitry Andric 
6220b57cec5SDimitry Andric       if (!LoopIdMD)
6230b57cec5SDimitry Andric         return false;
6240b57cec5SDimitry Andric 
625fe6060f1SDimitry Andric       if (!llvm::is_contained(LoopIdMD->operands(), DesiredLoopIdMetadata))
6260b57cec5SDimitry Andric         return false;
6270b57cec5SDimitry Andric     }
6280b57cec5SDimitry Andric   }
6290b57cec5SDimitry Andric   return true;
6300b57cec5SDimitry Andric }
6310b57cec5SDimitry Andric 
6320b57cec5SDimitry Andric DebugLoc Loop::getStartLoc() const { return getLocRange().getStart(); }
6330b57cec5SDimitry Andric 
6340b57cec5SDimitry Andric Loop::LocRange Loop::getLocRange() const {
6350b57cec5SDimitry Andric   // If we have a debug location in the loop ID, then use it.
6360b57cec5SDimitry Andric   if (MDNode *LoopID = getLoopID()) {
6370b57cec5SDimitry Andric     DebugLoc Start;
6380b57cec5SDimitry Andric     // We use the first DebugLoc in the header as the start location of the loop
6390b57cec5SDimitry Andric     // and if there is a second DebugLoc in the header we use it as end location
6400b57cec5SDimitry Andric     // of the loop.
641*0fca6ea1SDimitry Andric     for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
642*0fca6ea1SDimitry Andric       if (DILocation *L = dyn_cast<DILocation>(MDO)) {
6430b57cec5SDimitry Andric         if (!Start)
6440b57cec5SDimitry Andric           Start = DebugLoc(L);
6450b57cec5SDimitry Andric         else
6460b57cec5SDimitry Andric           return LocRange(Start, DebugLoc(L));
6470b57cec5SDimitry Andric       }
6480b57cec5SDimitry Andric     }
6490b57cec5SDimitry Andric 
6500b57cec5SDimitry Andric     if (Start)
6510b57cec5SDimitry Andric       return LocRange(Start);
6520b57cec5SDimitry Andric   }
6530b57cec5SDimitry Andric 
6540b57cec5SDimitry Andric   // Try the pre-header first.
6550b57cec5SDimitry Andric   if (BasicBlock *PHeadBB = getLoopPreheader())
6560b57cec5SDimitry Andric     if (DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc())
6570b57cec5SDimitry Andric       return LocRange(DL);
6580b57cec5SDimitry Andric 
6590b57cec5SDimitry Andric   // If we have no pre-header or there are no instructions with debug
6600b57cec5SDimitry Andric   // info in it, try the header.
6610b57cec5SDimitry Andric   if (BasicBlock *HeadBB = getHeader())
6620b57cec5SDimitry Andric     return LocRange(HeadBB->getTerminator()->getDebugLoc());
6630b57cec5SDimitry Andric 
6640b57cec5SDimitry Andric   return LocRange();
6650b57cec5SDimitry Andric }
6660b57cec5SDimitry Andric 
667*0fca6ea1SDimitry Andric std::string Loop::getLocStr() const {
668*0fca6ea1SDimitry Andric   std::string Result;
669*0fca6ea1SDimitry Andric   raw_string_ostream OS(Result);
670*0fca6ea1SDimitry Andric   if (const DebugLoc LoopDbgLoc = getStartLoc())
671*0fca6ea1SDimitry Andric     LoopDbgLoc.print(OS);
672*0fca6ea1SDimitry Andric   else
673*0fca6ea1SDimitry Andric     // Just print the module name.
674*0fca6ea1SDimitry Andric     OS << getHeader()->getParent()->getParent()->getModuleIdentifier();
675*0fca6ea1SDimitry Andric   return Result;
676*0fca6ea1SDimitry Andric }
677*0fca6ea1SDimitry Andric 
6780b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
6790b57cec5SDimitry Andric LLVM_DUMP_METHOD void Loop::dump() const { print(dbgs()); }
6800b57cec5SDimitry Andric 
6810b57cec5SDimitry Andric LLVM_DUMP_METHOD void Loop::dumpVerbose() const {
682fe6060f1SDimitry Andric   print(dbgs(), /*Verbose=*/true);
6830b57cec5SDimitry Andric }
6840b57cec5SDimitry Andric #endif
6850b57cec5SDimitry Andric 
6860b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
6870b57cec5SDimitry Andric // UnloopUpdater implementation
6880b57cec5SDimitry Andric //
6890b57cec5SDimitry Andric 
6900b57cec5SDimitry Andric namespace {
6910b57cec5SDimitry Andric /// Find the new parent loop for all blocks within the "unloop" whose last
6920b57cec5SDimitry Andric /// backedges has just been removed.
6930b57cec5SDimitry Andric class UnloopUpdater {
6940b57cec5SDimitry Andric   Loop &Unloop;
6950b57cec5SDimitry Andric   LoopInfo *LI;
6960b57cec5SDimitry Andric 
6970b57cec5SDimitry Andric   LoopBlocksDFS DFS;
6980b57cec5SDimitry Andric 
6990b57cec5SDimitry Andric   // Map unloop's immediate subloops to their nearest reachable parents. Nested
7000b57cec5SDimitry Andric   // loops within these subloops will not change parents. However, an immediate
7010b57cec5SDimitry Andric   // subloop's new parent will be the nearest loop reachable from either its own
7020b57cec5SDimitry Andric   // exits *or* any of its nested loop's exits.
7030b57cec5SDimitry Andric   DenseMap<Loop *, Loop *> SubloopParents;
7040b57cec5SDimitry Andric 
7050b57cec5SDimitry Andric   // Flag the presence of an irreducible backedge whose destination is a block
7060b57cec5SDimitry Andric   // directly contained by the original unloop.
70704eeddc0SDimitry Andric   bool FoundIB = false;
7080b57cec5SDimitry Andric 
7090b57cec5SDimitry Andric public:
71004eeddc0SDimitry Andric   UnloopUpdater(Loop *UL, LoopInfo *LInfo) : Unloop(*UL), LI(LInfo), DFS(UL) {}
7110b57cec5SDimitry Andric 
7120b57cec5SDimitry Andric   void updateBlockParents();
7130b57cec5SDimitry Andric 
7140b57cec5SDimitry Andric   void removeBlocksFromAncestors();
7150b57cec5SDimitry Andric 
7160b57cec5SDimitry Andric   void updateSubloopParents();
7170b57cec5SDimitry Andric 
7180b57cec5SDimitry Andric protected:
7190b57cec5SDimitry Andric   Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
7200b57cec5SDimitry Andric };
7210b57cec5SDimitry Andric } // end anonymous namespace
7220b57cec5SDimitry Andric 
7230b57cec5SDimitry Andric /// Update the parent loop for all blocks that are directly contained within the
7240b57cec5SDimitry Andric /// original "unloop".
7250b57cec5SDimitry Andric void UnloopUpdater::updateBlockParents() {
7260b57cec5SDimitry Andric   if (Unloop.getNumBlocks()) {
7270b57cec5SDimitry Andric     // Perform a post order CFG traversal of all blocks within this loop,
7280b57cec5SDimitry Andric     // propagating the nearest loop from successors to predecessors.
7290b57cec5SDimitry Andric     LoopBlocksTraversal Traversal(DFS, LI);
7300b57cec5SDimitry Andric     for (BasicBlock *POI : Traversal) {
7310b57cec5SDimitry Andric 
7320b57cec5SDimitry Andric       Loop *L = LI->getLoopFor(POI);
7330b57cec5SDimitry Andric       Loop *NL = getNearestLoop(POI, L);
7340b57cec5SDimitry Andric 
7350b57cec5SDimitry Andric       if (NL != L) {
7360b57cec5SDimitry Andric         // For reducible loops, NL is now an ancestor of Unloop.
7370b57cec5SDimitry Andric         assert((NL != &Unloop && (!NL || NL->contains(&Unloop))) &&
7380b57cec5SDimitry Andric                "uninitialized successor");
7390b57cec5SDimitry Andric         LI->changeLoopFor(POI, NL);
7400b57cec5SDimitry Andric       } else {
7410b57cec5SDimitry Andric         // Or the current block is part of a subloop, in which case its parent
7420b57cec5SDimitry Andric         // is unchanged.
7430b57cec5SDimitry Andric         assert((FoundIB || Unloop.contains(L)) && "uninitialized successor");
7440b57cec5SDimitry Andric       }
7450b57cec5SDimitry Andric     }
7460b57cec5SDimitry Andric   }
7470b57cec5SDimitry Andric   // Each irreducible loop within the unloop induces a round of iteration using
7480b57cec5SDimitry Andric   // the DFS result cached by Traversal.
7490b57cec5SDimitry Andric   bool Changed = FoundIB;
7500b57cec5SDimitry Andric   for (unsigned NIters = 0; Changed; ++NIters) {
7510b57cec5SDimitry Andric     assert(NIters < Unloop.getNumBlocks() && "runaway iterative algorithm");
75281ad6265SDimitry Andric     (void)NIters;
7530b57cec5SDimitry Andric 
7540b57cec5SDimitry Andric     // Iterate over the postorder list of blocks, propagating the nearest loop
7550b57cec5SDimitry Andric     // from successors to predecessors as before.
7560b57cec5SDimitry Andric     Changed = false;
7570b57cec5SDimitry Andric     for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
7580b57cec5SDimitry Andric                                    POE = DFS.endPostorder();
7590b57cec5SDimitry Andric          POI != POE; ++POI) {
7600b57cec5SDimitry Andric 
7610b57cec5SDimitry Andric       Loop *L = LI->getLoopFor(*POI);
7620b57cec5SDimitry Andric       Loop *NL = getNearestLoop(*POI, L);
7630b57cec5SDimitry Andric       if (NL != L) {
7640b57cec5SDimitry Andric         assert(NL != &Unloop && (!NL || NL->contains(&Unloop)) &&
7650b57cec5SDimitry Andric                "uninitialized successor");
7660b57cec5SDimitry Andric         LI->changeLoopFor(*POI, NL);
7670b57cec5SDimitry Andric         Changed = true;
7680b57cec5SDimitry Andric       }
7690b57cec5SDimitry Andric     }
7700b57cec5SDimitry Andric   }
7710b57cec5SDimitry Andric }
7720b57cec5SDimitry Andric 
7730b57cec5SDimitry Andric /// Remove unloop's blocks from all ancestors below their new parents.
7740b57cec5SDimitry Andric void UnloopUpdater::removeBlocksFromAncestors() {
7750b57cec5SDimitry Andric   // Remove all unloop's blocks (including those in nested subloops) from
7760b57cec5SDimitry Andric   // ancestors below the new parent loop.
777fe6060f1SDimitry Andric   for (BasicBlock *BB : Unloop.blocks()) {
778fe6060f1SDimitry Andric     Loop *OuterParent = LI->getLoopFor(BB);
7790b57cec5SDimitry Andric     if (Unloop.contains(OuterParent)) {
7800b57cec5SDimitry Andric       while (OuterParent->getParentLoop() != &Unloop)
7810b57cec5SDimitry Andric         OuterParent = OuterParent->getParentLoop();
7820b57cec5SDimitry Andric       OuterParent = SubloopParents[OuterParent];
7830b57cec5SDimitry Andric     }
7840b57cec5SDimitry Andric     // Remove blocks from former Ancestors except Unloop itself which will be
7850b57cec5SDimitry Andric     // deleted.
7860b57cec5SDimitry Andric     for (Loop *OldParent = Unloop.getParentLoop(); OldParent != OuterParent;
7870b57cec5SDimitry Andric          OldParent = OldParent->getParentLoop()) {
7880b57cec5SDimitry Andric       assert(OldParent && "new loop is not an ancestor of the original");
789fe6060f1SDimitry Andric       OldParent->removeBlockFromLoop(BB);
7900b57cec5SDimitry Andric     }
7910b57cec5SDimitry Andric   }
7920b57cec5SDimitry Andric }
7930b57cec5SDimitry Andric 
7940b57cec5SDimitry Andric /// Update the parent loop for all subloops directly nested within unloop.
7950b57cec5SDimitry Andric void UnloopUpdater::updateSubloopParents() {
796e8d8bef9SDimitry Andric   while (!Unloop.isInnermost()) {
7970b57cec5SDimitry Andric     Loop *Subloop = *std::prev(Unloop.end());
7980b57cec5SDimitry Andric     Unloop.removeChildLoop(std::prev(Unloop.end()));
7990b57cec5SDimitry Andric 
8000b57cec5SDimitry Andric     assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
8010b57cec5SDimitry Andric     if (Loop *Parent = SubloopParents[Subloop])
8020b57cec5SDimitry Andric       Parent->addChildLoop(Subloop);
8030b57cec5SDimitry Andric     else
8040b57cec5SDimitry Andric       LI->addTopLevelLoop(Subloop);
8050b57cec5SDimitry Andric   }
8060b57cec5SDimitry Andric }
8070b57cec5SDimitry Andric 
8080b57cec5SDimitry Andric /// Return the nearest parent loop among this block's successors. If a successor
8090b57cec5SDimitry Andric /// is a subloop header, consider its parent to be the nearest parent of the
8100b57cec5SDimitry Andric /// subloop's exits.
8110b57cec5SDimitry Andric ///
8120b57cec5SDimitry Andric /// For subloop blocks, simply update SubloopParents and return NULL.
8130b57cec5SDimitry Andric Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
8140b57cec5SDimitry Andric 
8150b57cec5SDimitry Andric   // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
8160b57cec5SDimitry Andric   // is considered uninitialized.
8170b57cec5SDimitry Andric   Loop *NearLoop = BBLoop;
8180b57cec5SDimitry Andric 
8190b57cec5SDimitry Andric   Loop *Subloop = nullptr;
8200b57cec5SDimitry Andric   if (NearLoop != &Unloop && Unloop.contains(NearLoop)) {
8210b57cec5SDimitry Andric     Subloop = NearLoop;
8220b57cec5SDimitry Andric     // Find the subloop ancestor that is directly contained within Unloop.
8230b57cec5SDimitry Andric     while (Subloop->getParentLoop() != &Unloop) {
8240b57cec5SDimitry Andric       Subloop = Subloop->getParentLoop();
8250b57cec5SDimitry Andric       assert(Subloop && "subloop is not an ancestor of the original loop");
8260b57cec5SDimitry Andric     }
8270b57cec5SDimitry Andric     // Get the current nearest parent of the Subloop exits, initially Unloop.
8280b57cec5SDimitry Andric     NearLoop = SubloopParents.insert({Subloop, &Unloop}).first->second;
8290b57cec5SDimitry Andric   }
8300b57cec5SDimitry Andric 
831*0fca6ea1SDimitry Andric   if (succ_empty(BB)) {
8320b57cec5SDimitry Andric     assert(!Subloop && "subloop blocks must have a successor");
8330b57cec5SDimitry Andric     NearLoop = nullptr; // unloop blocks may now exit the function.
8340b57cec5SDimitry Andric   }
835*0fca6ea1SDimitry Andric   for (BasicBlock *Succ : successors(BB)) {
836*0fca6ea1SDimitry Andric     if (Succ == BB)
8370b57cec5SDimitry Andric       continue; // self loops are uninteresting
8380b57cec5SDimitry Andric 
839*0fca6ea1SDimitry Andric     Loop *L = LI->getLoopFor(Succ);
8400b57cec5SDimitry Andric     if (L == &Unloop) {
8410b57cec5SDimitry Andric       // This successor has not been processed. This path must lead to an
8420b57cec5SDimitry Andric       // irreducible backedge.
843*0fca6ea1SDimitry Andric       assert((FoundIB || !DFS.hasPostorder(Succ)) && "should have seen IB");
8440b57cec5SDimitry Andric       FoundIB = true;
8450b57cec5SDimitry Andric     }
8460b57cec5SDimitry Andric     if (L != &Unloop && Unloop.contains(L)) {
8470b57cec5SDimitry Andric       // Successor is in a subloop.
8480b57cec5SDimitry Andric       if (Subloop)
8490b57cec5SDimitry Andric         continue; // Branching within subloops. Ignore it.
8500b57cec5SDimitry Andric 
8510b57cec5SDimitry Andric       // BB branches from the original into a subloop header.
8520b57cec5SDimitry Andric       assert(L->getParentLoop() == &Unloop && "cannot skip into nested loops");
8530b57cec5SDimitry Andric 
8540b57cec5SDimitry Andric       // Get the current nearest parent of the Subloop's exits.
8550b57cec5SDimitry Andric       L = SubloopParents[L];
8560b57cec5SDimitry Andric       // L could be Unloop if the only exit was an irreducible backedge.
8570b57cec5SDimitry Andric     }
8580b57cec5SDimitry Andric     if (L == &Unloop) {
8590b57cec5SDimitry Andric       continue;
8600b57cec5SDimitry Andric     }
8610b57cec5SDimitry Andric     // Handle critical edges from Unloop into a sibling loop.
8620b57cec5SDimitry Andric     if (L && !L->contains(&Unloop)) {
8630b57cec5SDimitry Andric       L = L->getParentLoop();
8640b57cec5SDimitry Andric     }
8650b57cec5SDimitry Andric     // Remember the nearest parent loop among successors or subloop exits.
8660b57cec5SDimitry Andric     if (NearLoop == &Unloop || !NearLoop || NearLoop->contains(L))
8670b57cec5SDimitry Andric       NearLoop = L;
8680b57cec5SDimitry Andric   }
8690b57cec5SDimitry Andric   if (Subloop) {
8700b57cec5SDimitry Andric     SubloopParents[Subloop] = NearLoop;
8710b57cec5SDimitry Andric     return BBLoop;
8720b57cec5SDimitry Andric   }
8730b57cec5SDimitry Andric   return NearLoop;
8740b57cec5SDimitry Andric }
8750b57cec5SDimitry Andric 
8760b57cec5SDimitry Andric LoopInfo::LoopInfo(const DomTreeBase<BasicBlock> &DomTree) { analyze(DomTree); }
8770b57cec5SDimitry Andric 
8780b57cec5SDimitry Andric bool LoopInfo::invalidate(Function &F, const PreservedAnalyses &PA,
8790b57cec5SDimitry Andric                           FunctionAnalysisManager::Invalidator &) {
8800b57cec5SDimitry Andric   // Check whether the analysis, all analyses on functions, or the function's
8810b57cec5SDimitry Andric   // CFG have been preserved.
8820b57cec5SDimitry Andric   auto PAC = PA.getChecker<LoopAnalysis>();
8830b57cec5SDimitry Andric   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
8840b57cec5SDimitry Andric            PAC.preservedSet<CFGAnalyses>());
8850b57cec5SDimitry Andric }
8860b57cec5SDimitry Andric 
8870b57cec5SDimitry Andric void LoopInfo::erase(Loop *Unloop) {
8880b57cec5SDimitry Andric   assert(!Unloop->isInvalid() && "Loop has already been erased!");
8890b57cec5SDimitry Andric 
8900b57cec5SDimitry Andric   auto InvalidateOnExit = make_scope_exit([&]() { destroy(Unloop); });
8910b57cec5SDimitry Andric 
8920b57cec5SDimitry Andric   // First handle the special case of no parent loop to simplify the algorithm.
893e8d8bef9SDimitry Andric   if (Unloop->isOutermost()) {
8940b57cec5SDimitry Andric     // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
895fe6060f1SDimitry Andric     for (BasicBlock *BB : Unloop->blocks()) {
8960b57cec5SDimitry Andric       // Don't reparent blocks in subloops.
897fe6060f1SDimitry Andric       if (getLoopFor(BB) != Unloop)
8980b57cec5SDimitry Andric         continue;
8990b57cec5SDimitry Andric 
9000b57cec5SDimitry Andric       // Blocks no longer have a parent but are still referenced by Unloop until
9010b57cec5SDimitry Andric       // the Unloop object is deleted.
902fe6060f1SDimitry Andric       changeLoopFor(BB, nullptr);
9030b57cec5SDimitry Andric     }
9040b57cec5SDimitry Andric 
9050b57cec5SDimitry Andric     // Remove the loop from the top-level LoopInfo object.
9060b57cec5SDimitry Andric     for (iterator I = begin();; ++I) {
9070b57cec5SDimitry Andric       assert(I != end() && "Couldn't find loop");
9080b57cec5SDimitry Andric       if (*I == Unloop) {
9090b57cec5SDimitry Andric         removeLoop(I);
9100b57cec5SDimitry Andric         break;
9110b57cec5SDimitry Andric       }
9120b57cec5SDimitry Andric     }
9130b57cec5SDimitry Andric 
9140b57cec5SDimitry Andric     // Move all of the subloops to the top-level.
915e8d8bef9SDimitry Andric     while (!Unloop->isInnermost())
9160b57cec5SDimitry Andric       addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
9170b57cec5SDimitry Andric 
9180b57cec5SDimitry Andric     return;
9190b57cec5SDimitry Andric   }
9200b57cec5SDimitry Andric 
9210b57cec5SDimitry Andric   // Update the parent loop for all blocks within the loop. Blocks within
9220b57cec5SDimitry Andric   // subloops will not change parents.
9230b57cec5SDimitry Andric   UnloopUpdater Updater(Unloop, this);
9240b57cec5SDimitry Andric   Updater.updateBlockParents();
9250b57cec5SDimitry Andric 
9260b57cec5SDimitry Andric   // Remove blocks from former ancestor loops.
9270b57cec5SDimitry Andric   Updater.removeBlocksFromAncestors();
9280b57cec5SDimitry Andric 
9290b57cec5SDimitry Andric   // Add direct subloops as children in their new parent loop.
9300b57cec5SDimitry Andric   Updater.updateSubloopParents();
9310b57cec5SDimitry Andric 
9320b57cec5SDimitry Andric   // Remove unloop from its parent loop.
9330b57cec5SDimitry Andric   Loop *ParentLoop = Unloop->getParentLoop();
9340b57cec5SDimitry Andric   for (Loop::iterator I = ParentLoop->begin();; ++I) {
9350b57cec5SDimitry Andric     assert(I != ParentLoop->end() && "Couldn't find loop");
9360b57cec5SDimitry Andric     if (*I == Unloop) {
9370b57cec5SDimitry Andric       ParentLoop->removeChildLoop(I);
9380b57cec5SDimitry Andric       break;
9390b57cec5SDimitry Andric     }
9400b57cec5SDimitry Andric   }
9410b57cec5SDimitry Andric }
9420b57cec5SDimitry Andric 
94306c3fb27SDimitry Andric bool LoopInfo::wouldBeOutOfLoopUseRequiringLCSSA(
94406c3fb27SDimitry Andric     const Value *V, const BasicBlock *ExitBB) const {
945fe6060f1SDimitry Andric   if (V->getType()->isTokenTy())
946fe6060f1SDimitry Andric     // We can't form PHIs of token type, so the definition of LCSSA excludes
947fe6060f1SDimitry Andric     // values of that type.
948fe6060f1SDimitry Andric     return false;
949fe6060f1SDimitry Andric 
950fe6060f1SDimitry Andric   const Instruction *I = dyn_cast<Instruction>(V);
951fe6060f1SDimitry Andric   if (!I)
952fe6060f1SDimitry Andric     return false;
953fe6060f1SDimitry Andric   const Loop *L = getLoopFor(I->getParent());
954fe6060f1SDimitry Andric   if (!L)
955fe6060f1SDimitry Andric     return false;
956fe6060f1SDimitry Andric   if (L->contains(ExitBB))
957fe6060f1SDimitry Andric     // Could be an exit bb of a subloop and contained in defining loop
958fe6060f1SDimitry Andric     return false;
959fe6060f1SDimitry Andric 
960fe6060f1SDimitry Andric   // We found a (new) out-of-loop use location, for a value defined in-loop.
961fe6060f1SDimitry Andric   // (Note that because of LCSSA, we don't have to account for values defined
962fe6060f1SDimitry Andric   // in sibling loops.  Such values will have LCSSA phis of their own in the
963fe6060f1SDimitry Andric   // common parent loop.)
964fe6060f1SDimitry Andric   return true;
965fe6060f1SDimitry Andric }
966fe6060f1SDimitry Andric 
9670b57cec5SDimitry Andric AnalysisKey LoopAnalysis::Key;
9680b57cec5SDimitry Andric 
9690b57cec5SDimitry Andric LoopInfo LoopAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
9700b57cec5SDimitry Andric   // FIXME: Currently we create a LoopInfo from scratch for every function.
9710b57cec5SDimitry Andric   // This may prove to be too wasteful due to deallocating and re-allocating
9720b57cec5SDimitry Andric   // memory each time for the underlying map and vector datastructures. At some
9730b57cec5SDimitry Andric   // point it may prove worthwhile to use a freelist and recycle LoopInfo
9740b57cec5SDimitry Andric   // objects. I don't want to add that kind of complexity until the scope of
9750b57cec5SDimitry Andric   // the problem is better understood.
9760b57cec5SDimitry Andric   LoopInfo LI;
9770b57cec5SDimitry Andric   LI.analyze(AM.getResult<DominatorTreeAnalysis>(F));
9780b57cec5SDimitry Andric   return LI;
9790b57cec5SDimitry Andric }
9800b57cec5SDimitry Andric 
9810b57cec5SDimitry Andric PreservedAnalyses LoopPrinterPass::run(Function &F,
9820b57cec5SDimitry Andric                                        FunctionAnalysisManager &AM) {
9831db9f3b2SDimitry Andric   auto &LI = AM.getResult<LoopAnalysis>(F);
9841db9f3b2SDimitry Andric   OS << "Loop info for function '" << F.getName() << "':\n";
9851db9f3b2SDimitry Andric   LI.print(OS);
9860b57cec5SDimitry Andric   return PreservedAnalyses::all();
9870b57cec5SDimitry Andric }
9880b57cec5SDimitry Andric 
9890b57cec5SDimitry Andric void llvm::printLoop(Loop &L, raw_ostream &OS, const std::string &Banner) {
9900b57cec5SDimitry Andric 
9910b57cec5SDimitry Andric   if (forcePrintModuleIR()) {
9920b57cec5SDimitry Andric     // handling -print-module-scope
9930b57cec5SDimitry Andric     OS << Banner << " (loop: ";
9940b57cec5SDimitry Andric     L.getHeader()->printAsOperand(OS, false);
9950b57cec5SDimitry Andric     OS << ")\n";
9960b57cec5SDimitry Andric 
9970b57cec5SDimitry Andric     // printing whole module
9980b57cec5SDimitry Andric     OS << *L.getHeader()->getModule();
9990b57cec5SDimitry Andric     return;
10000b57cec5SDimitry Andric   }
10010b57cec5SDimitry Andric 
10020b57cec5SDimitry Andric   OS << Banner;
10030b57cec5SDimitry Andric 
10040b57cec5SDimitry Andric   auto *PreHeader = L.getLoopPreheader();
10050b57cec5SDimitry Andric   if (PreHeader) {
10060b57cec5SDimitry Andric     OS << "\n; Preheader:";
10070b57cec5SDimitry Andric     PreHeader->print(OS);
10080b57cec5SDimitry Andric     OS << "\n; Loop:";
10090b57cec5SDimitry Andric   }
10100b57cec5SDimitry Andric 
10110b57cec5SDimitry Andric   for (auto *Block : L.blocks())
10120b57cec5SDimitry Andric     if (Block)
10130b57cec5SDimitry Andric       Block->print(OS);
10140b57cec5SDimitry Andric     else
10150b57cec5SDimitry Andric       OS << "Printing <null> block";
10160b57cec5SDimitry Andric 
10170b57cec5SDimitry Andric   SmallVector<BasicBlock *, 8> ExitBlocks;
10180b57cec5SDimitry Andric   L.getExitBlocks(ExitBlocks);
10190b57cec5SDimitry Andric   if (!ExitBlocks.empty()) {
10200b57cec5SDimitry Andric     OS << "\n; Exit blocks";
10210b57cec5SDimitry Andric     for (auto *Block : ExitBlocks)
10220b57cec5SDimitry Andric       if (Block)
10230b57cec5SDimitry Andric         Block->print(OS);
10240b57cec5SDimitry Andric       else
10250b57cec5SDimitry Andric         OS << "Printing <null> block";
10260b57cec5SDimitry Andric   }
10270b57cec5SDimitry Andric }
10280b57cec5SDimitry Andric 
10290b57cec5SDimitry Andric MDNode *llvm::findOptionMDForLoopID(MDNode *LoopID, StringRef Name) {
10300b57cec5SDimitry Andric   // No loop metadata node, no loop properties.
10310b57cec5SDimitry Andric   if (!LoopID)
10320b57cec5SDimitry Andric     return nullptr;
10330b57cec5SDimitry Andric 
10340b57cec5SDimitry Andric   // First operand should refer to the metadata node itself, for legacy reasons.
10350b57cec5SDimitry Andric   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
10360b57cec5SDimitry Andric   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
10370b57cec5SDimitry Andric 
10380b57cec5SDimitry Andric   // Iterate over the metdata node operands and look for MDString metadata.
1039*0fca6ea1SDimitry Andric   for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
1040*0fca6ea1SDimitry Andric     MDNode *MD = dyn_cast<MDNode>(MDO);
10410b57cec5SDimitry Andric     if (!MD || MD->getNumOperands() < 1)
10420b57cec5SDimitry Andric       continue;
10430b57cec5SDimitry Andric     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
10440b57cec5SDimitry Andric     if (!S)
10450b57cec5SDimitry Andric       continue;
10460b57cec5SDimitry Andric     // Return the operand node if MDString holds expected metadata.
1047*0fca6ea1SDimitry Andric     if (Name == S->getString())
10480b57cec5SDimitry Andric       return MD;
10490b57cec5SDimitry Andric   }
10500b57cec5SDimitry Andric 
10510b57cec5SDimitry Andric   // Loop property not found.
10520b57cec5SDimitry Andric   return nullptr;
10530b57cec5SDimitry Andric }
10540b57cec5SDimitry Andric 
10550b57cec5SDimitry Andric MDNode *llvm::findOptionMDForLoop(const Loop *TheLoop, StringRef Name) {
10560b57cec5SDimitry Andric   return findOptionMDForLoopID(TheLoop->getLoopID(), Name);
10570b57cec5SDimitry Andric }
10580b57cec5SDimitry Andric 
1059fe6060f1SDimitry Andric /// Find string metadata for loop
1060fe6060f1SDimitry Andric ///
1061fe6060f1SDimitry Andric /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
1062fe6060f1SDimitry Andric /// operand or null otherwise.  If the string metadata is not found return
1063fe6060f1SDimitry Andric /// Optional's not-a-value.
1064bdd1243dSDimitry Andric std::optional<const MDOperand *>
1065bdd1243dSDimitry Andric llvm::findStringMetadataForLoop(const Loop *TheLoop, StringRef Name) {
1066fe6060f1SDimitry Andric   MDNode *MD = findOptionMDForLoop(TheLoop, Name);
1067fe6060f1SDimitry Andric   if (!MD)
1068bdd1243dSDimitry Andric     return std::nullopt;
1069fe6060f1SDimitry Andric   switch (MD->getNumOperands()) {
1070fe6060f1SDimitry Andric   case 1:
1071fe6060f1SDimitry Andric     return nullptr;
1072fe6060f1SDimitry Andric   case 2:
1073fe6060f1SDimitry Andric     return &MD->getOperand(1);
1074fe6060f1SDimitry Andric   default:
1075fe6060f1SDimitry Andric     llvm_unreachable("loop metadata has 0 or 1 operand");
1076fe6060f1SDimitry Andric   }
1077fe6060f1SDimitry Andric }
1078fe6060f1SDimitry Andric 
1079bdd1243dSDimitry Andric std::optional<bool> llvm::getOptionalBoolLoopAttribute(const Loop *TheLoop,
1080fe6060f1SDimitry Andric                                                        StringRef Name) {
1081fe6060f1SDimitry Andric   MDNode *MD = findOptionMDForLoop(TheLoop, Name);
1082fe6060f1SDimitry Andric   if (!MD)
1083bdd1243dSDimitry Andric     return std::nullopt;
1084fe6060f1SDimitry Andric   switch (MD->getNumOperands()) {
1085fe6060f1SDimitry Andric   case 1:
1086fe6060f1SDimitry Andric     // When the value is absent it is interpreted as 'attribute set'.
1087fe6060f1SDimitry Andric     return true;
1088fe6060f1SDimitry Andric   case 2:
1089fe6060f1SDimitry Andric     if (ConstantInt *IntMD =
1090fe6060f1SDimitry Andric             mdconst::extract_or_null<ConstantInt>(MD->getOperand(1).get()))
1091fe6060f1SDimitry Andric       return IntMD->getZExtValue();
1092fe6060f1SDimitry Andric     return true;
1093fe6060f1SDimitry Andric   }
1094fe6060f1SDimitry Andric   llvm_unreachable("unexpected number of options");
1095fe6060f1SDimitry Andric }
1096fe6060f1SDimitry Andric 
1097fe6060f1SDimitry Andric bool llvm::getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name) {
109881ad6265SDimitry Andric   return getOptionalBoolLoopAttribute(TheLoop, Name).value_or(false);
1099fe6060f1SDimitry Andric }
1100fe6060f1SDimitry Andric 
1101bdd1243dSDimitry Andric std::optional<int> llvm::getOptionalIntLoopAttribute(const Loop *TheLoop,
1102fe6060f1SDimitry Andric                                                      StringRef Name) {
1103fe6060f1SDimitry Andric   const MDOperand *AttrMD =
110481ad6265SDimitry Andric       findStringMetadataForLoop(TheLoop, Name).value_or(nullptr);
1105fe6060f1SDimitry Andric   if (!AttrMD)
1106bdd1243dSDimitry Andric     return std::nullopt;
1107fe6060f1SDimitry Andric 
1108fe6060f1SDimitry Andric   ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get());
1109fe6060f1SDimitry Andric   if (!IntMD)
1110bdd1243dSDimitry Andric     return std::nullopt;
1111fe6060f1SDimitry Andric 
1112fe6060f1SDimitry Andric   return IntMD->getSExtValue();
1113fe6060f1SDimitry Andric }
1114fe6060f1SDimitry Andric 
1115349cc55cSDimitry Andric int llvm::getIntLoopAttribute(const Loop *TheLoop, StringRef Name,
1116349cc55cSDimitry Andric                               int Default) {
111781ad6265SDimitry Andric   return getOptionalIntLoopAttribute(TheLoop, Name).value_or(Default);
1118349cc55cSDimitry Andric }
1119349cc55cSDimitry Andric 
1120*0fca6ea1SDimitry Andric CallBase *llvm::getLoopConvergenceHeart(const Loop *TheLoop) {
1121*0fca6ea1SDimitry Andric   BasicBlock *H = TheLoop->getHeader();
1122*0fca6ea1SDimitry Andric   for (Instruction &II : *H) {
1123*0fca6ea1SDimitry Andric     if (auto *CB = dyn_cast<CallBase>(&II)) {
1124*0fca6ea1SDimitry Andric       if (!CB->isConvergent())
1125*0fca6ea1SDimitry Andric         continue;
1126*0fca6ea1SDimitry Andric       // This is the heart if it uses a token defined outside the loop. The
1127*0fca6ea1SDimitry Andric       // verifier has already checked that only the loop intrinsic can use such
1128*0fca6ea1SDimitry Andric       // a token.
1129*0fca6ea1SDimitry Andric       if (auto *Token = CB->getConvergenceControlToken()) {
1130*0fca6ea1SDimitry Andric         auto *TokenDef = cast<Instruction>(Token);
1131*0fca6ea1SDimitry Andric         if (!TheLoop->contains(TokenDef->getParent()))
1132*0fca6ea1SDimitry Andric           return CB;
1133*0fca6ea1SDimitry Andric       }
1134*0fca6ea1SDimitry Andric       return nullptr;
1135*0fca6ea1SDimitry Andric     }
1136*0fca6ea1SDimitry Andric   }
1137*0fca6ea1SDimitry Andric   return nullptr;
1138*0fca6ea1SDimitry Andric }
1139*0fca6ea1SDimitry Andric 
11401fd87a68SDimitry Andric bool llvm::isFinite(const Loop *L) {
11411fd87a68SDimitry Andric   return L->getHeader()->getParent()->willReturn();
11421fd87a68SDimitry Andric }
11431fd87a68SDimitry Andric 
1144fe6060f1SDimitry Andric static const char *LLVMLoopMustProgress = "llvm.loop.mustprogress";
1145fe6060f1SDimitry Andric 
1146fe6060f1SDimitry Andric bool llvm::hasMustProgress(const Loop *L) {
1147fe6060f1SDimitry Andric   return getBooleanLoopAttribute(L, LLVMLoopMustProgress);
1148fe6060f1SDimitry Andric }
1149fe6060f1SDimitry Andric 
1150fe6060f1SDimitry Andric bool llvm::isMustProgress(const Loop *L) {
1151fe6060f1SDimitry Andric   return L->getHeader()->getParent()->mustProgress() || hasMustProgress(L);
1152fe6060f1SDimitry Andric }
1153fe6060f1SDimitry Andric 
11540b57cec5SDimitry Andric bool llvm::isValidAsAccessGroup(MDNode *Node) {
11550b57cec5SDimitry Andric   return Node->getNumOperands() == 0 && Node->isDistinct();
11560b57cec5SDimitry Andric }
11570b57cec5SDimitry Andric 
11580b57cec5SDimitry Andric MDNode *llvm::makePostTransformationMetadata(LLVMContext &Context,
11590b57cec5SDimitry Andric                                              MDNode *OrigLoopID,
11600b57cec5SDimitry Andric                                              ArrayRef<StringRef> RemovePrefixes,
11610b57cec5SDimitry Andric                                              ArrayRef<MDNode *> AddAttrs) {
11620b57cec5SDimitry Andric   // First remove any existing loop metadata related to this transformation.
11630b57cec5SDimitry Andric   SmallVector<Metadata *, 4> MDs;
11640b57cec5SDimitry Andric 
11650b57cec5SDimitry Andric   // Reserve first location for self reference to the LoopID metadata node.
1166e8d8bef9SDimitry Andric   MDs.push_back(nullptr);
11670b57cec5SDimitry Andric 
11680b57cec5SDimitry Andric   // Remove metadata for the transformation that has been applied or that became
11690b57cec5SDimitry Andric   // outdated.
11700b57cec5SDimitry Andric   if (OrigLoopID) {
1171*0fca6ea1SDimitry Andric     for (const MDOperand &MDO : llvm::drop_begin(OrigLoopID->operands())) {
11720b57cec5SDimitry Andric       bool IsVectorMetadata = false;
1173*0fca6ea1SDimitry Andric       Metadata *Op = MDO;
11740b57cec5SDimitry Andric       if (MDNode *MD = dyn_cast<MDNode>(Op)) {
11750b57cec5SDimitry Andric         const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
11760b57cec5SDimitry Andric         if (S)
11770b57cec5SDimitry Andric           IsVectorMetadata =
11780b57cec5SDimitry Andric               llvm::any_of(RemovePrefixes, [S](StringRef Prefix) -> bool {
11795f757f3fSDimitry Andric                 return S->getString().starts_with(Prefix);
11800b57cec5SDimitry Andric               });
11810b57cec5SDimitry Andric       }
11820b57cec5SDimitry Andric       if (!IsVectorMetadata)
11830b57cec5SDimitry Andric         MDs.push_back(Op);
11840b57cec5SDimitry Andric     }
11850b57cec5SDimitry Andric   }
11860b57cec5SDimitry Andric 
11870b57cec5SDimitry Andric   // Add metadata to avoid reapplying a transformation, such as
11880b57cec5SDimitry Andric   // llvm.loop.unroll.disable and llvm.loop.isvectorized.
11890b57cec5SDimitry Andric   MDs.append(AddAttrs.begin(), AddAttrs.end());
11900b57cec5SDimitry Andric 
11910b57cec5SDimitry Andric   MDNode *NewLoopID = MDNode::getDistinct(Context, MDs);
11920b57cec5SDimitry Andric   // Replace the temporary node with a self-reference.
11930b57cec5SDimitry Andric   NewLoopID->replaceOperandWith(0, NewLoopID);
11940b57cec5SDimitry Andric   return NewLoopID;
11950b57cec5SDimitry Andric }
11960b57cec5SDimitry Andric 
11970b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
11980b57cec5SDimitry Andric // LoopInfo implementation
11990b57cec5SDimitry Andric //
12000b57cec5SDimitry Andric 
1201480093f4SDimitry Andric LoopInfoWrapperPass::LoopInfoWrapperPass() : FunctionPass(ID) {
1202480093f4SDimitry Andric   initializeLoopInfoWrapperPassPass(*PassRegistry::getPassRegistry());
1203480093f4SDimitry Andric }
1204480093f4SDimitry Andric 
12050b57cec5SDimitry Andric char LoopInfoWrapperPass::ID = 0;
12060b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
12070b57cec5SDimitry Andric                       true, true)
12080b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
12090b57cec5SDimitry Andric INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
12100b57cec5SDimitry Andric                     true, true)
12110b57cec5SDimitry Andric 
12120b57cec5SDimitry Andric bool LoopInfoWrapperPass::runOnFunction(Function &) {
12130b57cec5SDimitry Andric   releaseMemory();
12140b57cec5SDimitry Andric   LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
12150b57cec5SDimitry Andric   return false;
12160b57cec5SDimitry Andric }
12170b57cec5SDimitry Andric 
12180b57cec5SDimitry Andric void LoopInfoWrapperPass::verifyAnalysis() const {
12190b57cec5SDimitry Andric   // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
12200b57cec5SDimitry Andric   // function each time verifyAnalysis is called is very expensive. The
12210b57cec5SDimitry Andric   // -verify-loop-info option can enable this. In order to perform some
12220b57cec5SDimitry Andric   // checking by default, LoopPass has been taught to call verifyLoop manually
12230b57cec5SDimitry Andric   // during loop pass sequences.
12240b57cec5SDimitry Andric   if (VerifyLoopInfo) {
12250b57cec5SDimitry Andric     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
12260b57cec5SDimitry Andric     LI.verify(DT);
12270b57cec5SDimitry Andric   }
12280b57cec5SDimitry Andric }
12290b57cec5SDimitry Andric 
12300b57cec5SDimitry Andric void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
12310b57cec5SDimitry Andric   AU.setPreservesAll();
12320b57cec5SDimitry Andric   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
12330b57cec5SDimitry Andric }
12340b57cec5SDimitry Andric 
12350b57cec5SDimitry Andric void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
12360b57cec5SDimitry Andric   LI.print(OS);
12370b57cec5SDimitry Andric }
12380b57cec5SDimitry Andric 
12390b57cec5SDimitry Andric PreservedAnalyses LoopVerifierPass::run(Function &F,
12400b57cec5SDimitry Andric                                         FunctionAnalysisManager &AM) {
12410b57cec5SDimitry Andric   LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
12420b57cec5SDimitry Andric   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
12430b57cec5SDimitry Andric   LI.verify(DT);
12440b57cec5SDimitry Andric   return PreservedAnalyses::all();
12450b57cec5SDimitry Andric }
12460b57cec5SDimitry Andric 
12470b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12480b57cec5SDimitry Andric // LoopBlocksDFS implementation
12490b57cec5SDimitry Andric //
12500b57cec5SDimitry Andric 
12510b57cec5SDimitry Andric /// Traverse the loop blocks and store the DFS result.
12520b57cec5SDimitry Andric /// Useful for clients that just want the final DFS result and don't need to
12530b57cec5SDimitry Andric /// visit blocks during the initial traversal.
12545f757f3fSDimitry Andric void LoopBlocksDFS::perform(const LoopInfo *LI) {
12550b57cec5SDimitry Andric   LoopBlocksTraversal Traversal(*this, LI);
12560b57cec5SDimitry Andric   for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
12570b57cec5SDimitry Andric                                         POE = Traversal.end();
12580b57cec5SDimitry Andric        POI != POE; ++POI)
12590b57cec5SDimitry Andric     ;
12600b57cec5SDimitry Andric }
1261