1 //===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the LoopInfo class that is used to identify natural loops
10 // and determine the loop depth of various nodes of the CFG.  Note that the
11 // loops identified may actually be several natural loops that share the same
12 // header node... not just a single natural loop.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/Analysis/LoopInfo.h"
17 #include "llvm/ADT/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/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include <algorithm>
41 using namespace llvm;
42 
43 // Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
44 template class llvm::LoopBase<BasicBlock, Loop>;
45 template class llvm::LoopInfoBase<BasicBlock, Loop>;
46 
47 // Always verify loopinfo if expensive checking is enabled.
48 #ifdef EXPENSIVE_CHECKS
49 bool llvm::VerifyLoopInfo = true;
50 #else
51 bool llvm::VerifyLoopInfo = false;
52 #endif
53 static cl::opt<bool, true>
54     VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
55                     cl::Hidden, cl::desc("Verify loop info (time consuming)"));
56 
57 //===----------------------------------------------------------------------===//
58 // Loop implementation
59 //
60 
61 bool Loop::isLoopInvariant(const Value *V) const {
62   if (const Instruction *I = dyn_cast<Instruction>(V))
63     return !contains(I);
64   return true; // All non-instructions are loop invariant
65 }
66 
67 bool Loop::hasLoopInvariantOperands(const Instruction *I) const {
68   return all_of(I->operands(), [this](Value *V) { return isLoopInvariant(V); });
69 }
70 
71 bool Loop::makeLoopInvariant(Value *V, bool &Changed, Instruction *InsertPt,
72                              MemorySSAUpdater *MSSAU) const {
73   if (Instruction *I = dyn_cast<Instruction>(V))
74     return makeLoopInvariant(I, Changed, InsertPt, MSSAU);
75   return true; // All non-instructions are loop-invariant.
76 }
77 
78 bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
79                              Instruction *InsertPt,
80                              MemorySSAUpdater *MSSAU) const {
81   // Test if the value is already loop-invariant.
82   if (isLoopInvariant(I))
83     return true;
84   if (!isSafeToSpeculativelyExecute(I))
85     return false;
86   if (I->mayReadFromMemory())
87     return false;
88   // EH block instructions are immobile.
89   if (I->isEHPad())
90     return false;
91   // Determine the insertion point, unless one was given.
92   if (!InsertPt) {
93     BasicBlock *Preheader = getLoopPreheader();
94     // Without a preheader, hoisting is not feasible.
95     if (!Preheader)
96       return false;
97     InsertPt = Preheader->getTerminator();
98   }
99   // Don't hoist instructions with loop-variant operands.
100   for (Value *Operand : I->operands())
101     if (!makeLoopInvariant(Operand, Changed, InsertPt, MSSAU))
102       return false;
103 
104   // Hoist.
105   I->moveBefore(InsertPt);
106   if (MSSAU)
107     if (auto *MUD = MSSAU->getMemorySSA()->getMemoryAccess(I))
108       MSSAU->moveToPlace(MUD, InsertPt->getParent(), MemorySSA::End);
109 
110   // There is possibility of hoisting this instruction above some arbitrary
111   // condition. Any metadata defined on it can be control dependent on this
112   // condition. Conservatively strip it here so that we don't give any wrong
113   // information to the optimizer.
114   I->dropUnknownNonDebugMetadata();
115 
116   Changed = true;
117   return true;
118 }
119 
120 bool Loop::getIncomingAndBackEdge(BasicBlock *&Incoming,
121                                   BasicBlock *&Backedge) const {
122   BasicBlock *H = getHeader();
123 
124   Incoming = nullptr;
125   Backedge = nullptr;
126   pred_iterator PI = pred_begin(H);
127   assert(PI != pred_end(H) && "Loop must have at least one backedge!");
128   Backedge = *PI++;
129   if (PI == pred_end(H))
130     return false; // dead loop
131   Incoming = *PI++;
132   if (PI != pred_end(H))
133     return false; // multiple backedges?
134 
135   if (contains(Incoming)) {
136     if (contains(Backedge))
137       return false;
138     std::swap(Incoming, Backedge);
139   } else if (!contains(Backedge))
140     return false;
141 
142   assert(Incoming && Backedge && "expected non-null incoming and backedges");
143   return true;
144 }
145 
146 PHINode *Loop::getCanonicalInductionVariable() const {
147   BasicBlock *H = getHeader();
148 
149   BasicBlock *Incoming = nullptr, *Backedge = nullptr;
150   if (!getIncomingAndBackEdge(Incoming, Backedge))
151     return nullptr;
152 
153   // Loop over all of the PHI nodes, looking for a canonical indvar.
154   for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
155     PHINode *PN = cast<PHINode>(I);
156     if (ConstantInt *CI =
157             dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
158       if (CI->isZero())
159         if (Instruction *Inc =
160                 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
161           if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
162             if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
163               if (CI->isOne())
164                 return PN;
165   }
166   return nullptr;
167 }
168 
169 /// Get the latch condition instruction.
170 static ICmpInst *getLatchCmpInst(const Loop &L) {
171   if (BasicBlock *Latch = L.getLoopLatch())
172     if (BranchInst *BI = dyn_cast_or_null<BranchInst>(Latch->getTerminator()))
173       if (BI->isConditional())
174         return dyn_cast<ICmpInst>(BI->getCondition());
175 
176   return nullptr;
177 }
178 
179 /// Return the final value of the loop induction variable if found.
180 static Value *findFinalIVValue(const Loop &L, const PHINode &IndVar,
181                                const Instruction &StepInst) {
182   ICmpInst *LatchCmpInst = getLatchCmpInst(L);
183   if (!LatchCmpInst)
184     return nullptr;
185 
186   Value *Op0 = LatchCmpInst->getOperand(0);
187   Value *Op1 = LatchCmpInst->getOperand(1);
188   if (Op0 == &IndVar || Op0 == &StepInst)
189     return Op1;
190 
191   if (Op1 == &IndVar || Op1 == &StepInst)
192     return Op0;
193 
194   return nullptr;
195 }
196 
197 Optional<Loop::LoopBounds> Loop::LoopBounds::getBounds(const Loop &L,
198                                                        PHINode &IndVar,
199                                                        ScalarEvolution &SE) {
200   InductionDescriptor IndDesc;
201   if (!InductionDescriptor::isInductionPHI(&IndVar, &L, &SE, IndDesc))
202     return None;
203 
204   Value *InitialIVValue = IndDesc.getStartValue();
205   Instruction *StepInst = IndDesc.getInductionBinOp();
206   if (!InitialIVValue || !StepInst)
207     return None;
208 
209   const SCEV *Step = IndDesc.getStep();
210   Value *StepInstOp1 = StepInst->getOperand(1);
211   Value *StepInstOp0 = StepInst->getOperand(0);
212   Value *StepValue = nullptr;
213   if (SE.getSCEV(StepInstOp1) == Step)
214     StepValue = StepInstOp1;
215   else if (SE.getSCEV(StepInstOp0) == Step)
216     StepValue = StepInstOp0;
217 
218   Value *FinalIVValue = findFinalIVValue(L, IndVar, *StepInst);
219   if (!FinalIVValue)
220     return None;
221 
222   return LoopBounds(L, *InitialIVValue, *StepInst, StepValue, *FinalIVValue,
223                     SE);
224 }
225 
226 using Direction = Loop::LoopBounds::Direction;
227 
228 ICmpInst::Predicate Loop::LoopBounds::getCanonicalPredicate() const {
229   BasicBlock *Latch = L.getLoopLatch();
230   assert(Latch && "Expecting valid latch");
231 
232   BranchInst *BI = dyn_cast_or_null<BranchInst>(Latch->getTerminator());
233   assert(BI && BI->isConditional() && "Expecting conditional latch branch");
234 
235   ICmpInst *LatchCmpInst = dyn_cast<ICmpInst>(BI->getCondition());
236   assert(LatchCmpInst &&
237          "Expecting the latch compare instruction to be a CmpInst");
238 
239   // Need to inverse the predicate when first successor is not the loop
240   // header
241   ICmpInst::Predicate Pred = (BI->getSuccessor(0) == L.getHeader())
242                                  ? LatchCmpInst->getPredicate()
243                                  : LatchCmpInst->getInversePredicate();
244 
245   if (LatchCmpInst->getOperand(0) == &getFinalIVValue())
246     Pred = ICmpInst::getSwappedPredicate(Pred);
247 
248   // Need to flip strictness of the predicate when the latch compare instruction
249   // is not using StepInst
250   if (LatchCmpInst->getOperand(0) == &getStepInst() ||
251       LatchCmpInst->getOperand(1) == &getStepInst())
252     return Pred;
253 
254   // Cannot flip strictness of NE and EQ
255   if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
256     return ICmpInst::getFlippedStrictnessPredicate(Pred);
257 
258   Direction D = getDirection();
259   if (D == Direction::Increasing)
260     return ICmpInst::ICMP_SLT;
261 
262   if (D == Direction::Decreasing)
263     return ICmpInst::ICMP_SGT;
264 
265   // If cannot determine the direction, then unable to find the canonical
266   // predicate
267   return ICmpInst::BAD_ICMP_PREDICATE;
268 }
269 
270 Direction Loop::LoopBounds::getDirection() const {
271   if (const SCEVAddRecExpr *StepAddRecExpr =
272           dyn_cast<SCEVAddRecExpr>(SE.getSCEV(&getStepInst())))
273     if (const SCEV *StepRecur = StepAddRecExpr->getStepRecurrence(SE)) {
274       if (SE.isKnownPositive(StepRecur))
275         return Direction::Increasing;
276       if (SE.isKnownNegative(StepRecur))
277         return Direction::Decreasing;
278     }
279 
280   return Direction::Unknown;
281 }
282 
283 Optional<Loop::LoopBounds> Loop::getBounds(ScalarEvolution &SE) const {
284   if (PHINode *IndVar = getInductionVariable(SE))
285     return LoopBounds::getBounds(*this, *IndVar, SE);
286 
287   return None;
288 }
289 
290 PHINode *Loop::getInductionVariable(ScalarEvolution &SE) const {
291   if (!isLoopSimplifyForm())
292     return nullptr;
293 
294   BasicBlock *Header = getHeader();
295   assert(Header && "Expected a valid loop header");
296   ICmpInst *CmpInst = getLatchCmpInst(*this);
297   if (!CmpInst)
298     return nullptr;
299 
300   Instruction *LatchCmpOp0 = dyn_cast<Instruction>(CmpInst->getOperand(0));
301   Instruction *LatchCmpOp1 = dyn_cast<Instruction>(CmpInst->getOperand(1));
302 
303   for (PHINode &IndVar : Header->phis()) {
304     InductionDescriptor IndDesc;
305     if (!InductionDescriptor::isInductionPHI(&IndVar, this, &SE, IndDesc))
306       continue;
307 
308     Instruction *StepInst = IndDesc.getInductionBinOp();
309 
310     // case 1:
311     // IndVar = phi[{InitialValue, preheader}, {StepInst, latch}]
312     // StepInst = IndVar + step
313     // cmp = StepInst < FinalValue
314     if (StepInst == LatchCmpOp0 || StepInst == LatchCmpOp1)
315       return &IndVar;
316 
317     // case 2:
318     // IndVar = phi[{InitialValue, preheader}, {StepInst, latch}]
319     // StepInst = IndVar + step
320     // cmp = IndVar < FinalValue
321     if (&IndVar == LatchCmpOp0 || &IndVar == LatchCmpOp1)
322       return &IndVar;
323   }
324 
325   return nullptr;
326 }
327 
328 bool Loop::getInductionDescriptor(ScalarEvolution &SE,
329                                   InductionDescriptor &IndDesc) const {
330   if (PHINode *IndVar = getInductionVariable(SE))
331     return InductionDescriptor::isInductionPHI(IndVar, this, &SE, IndDesc);
332 
333   return false;
334 }
335 
336 bool Loop::isAuxiliaryInductionVariable(PHINode &AuxIndVar,
337                                         ScalarEvolution &SE) const {
338   // Located in the loop header
339   BasicBlock *Header = getHeader();
340   if (AuxIndVar.getParent() != Header)
341     return false;
342 
343   // No uses outside of the loop
344   for (User *U : AuxIndVar.users())
345     if (const Instruction *I = dyn_cast<Instruction>(U))
346       if (!contains(I))
347         return false;
348 
349   InductionDescriptor IndDesc;
350   if (!InductionDescriptor::isInductionPHI(&AuxIndVar, this, &SE, IndDesc))
351     return false;
352 
353   // The step instruction opcode should be add or sub.
354   if (IndDesc.getInductionOpcode() != Instruction::Add &&
355       IndDesc.getInductionOpcode() != Instruction::Sub)
356     return false;
357 
358   // Incremented by a loop invariant step for each loop iteration
359   return SE.isLoopInvariant(IndDesc.getStep(), this);
360 }
361 
362 bool Loop::isCanonical(ScalarEvolution &SE) const {
363   InductionDescriptor IndDesc;
364   if (!getInductionDescriptor(SE, IndDesc))
365     return false;
366 
367   ConstantInt *Init = dyn_cast_or_null<ConstantInt>(IndDesc.getStartValue());
368   if (!Init || !Init->isZero())
369     return false;
370 
371   if (IndDesc.getInductionOpcode() != Instruction::Add)
372     return false;
373 
374   ConstantInt *Step = IndDesc.getConstIntStepValue();
375   if (!Step || !Step->isOne())
376     return false;
377 
378   return true;
379 }
380 
381 // Check that 'BB' doesn't have any uses outside of the 'L'
382 static bool isBlockInLCSSAForm(const Loop &L, const BasicBlock &BB,
383                                DominatorTree &DT) {
384   for (const Instruction &I : BB) {
385     // Tokens can't be used in PHI nodes and live-out tokens prevent loop
386     // optimizations, so for the purposes of considered LCSSA form, we
387     // can ignore them.
388     if (I.getType()->isTokenTy())
389       continue;
390 
391     for (const Use &U : I.uses()) {
392       const Instruction *UI = cast<Instruction>(U.getUser());
393       const BasicBlock *UserBB = UI->getParent();
394       if (const PHINode *P = dyn_cast<PHINode>(UI))
395         UserBB = P->getIncomingBlock(U);
396 
397       // Check the current block, as a fast-path, before checking whether
398       // the use is anywhere in the loop.  Most values are used in the same
399       // block they are defined in.  Also, blocks not reachable from the
400       // entry are special; uses in them don't need to go through PHIs.
401       if (UserBB != &BB && !L.contains(UserBB) &&
402           DT.isReachableFromEntry(UserBB))
403         return false;
404     }
405   }
406   return true;
407 }
408 
409 bool Loop::isLCSSAForm(DominatorTree &DT) const {
410   // For each block we check that it doesn't have any uses outside of this loop.
411   return all_of(this->blocks(), [&](const BasicBlock *BB) {
412     return isBlockInLCSSAForm(*this, *BB, DT);
413   });
414 }
415 
416 bool Loop::isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const {
417   // For each block we check that it doesn't have any uses outside of its
418   // innermost loop. This process will transitively guarantee that the current
419   // loop and all of the nested loops are in LCSSA form.
420   return all_of(this->blocks(), [&](const BasicBlock *BB) {
421     return isBlockInLCSSAForm(*LI.getLoopFor(BB), *BB, DT);
422   });
423 }
424 
425 bool Loop::isLoopSimplifyForm() const {
426   // Normal-form loops have a preheader, a single backedge, and all of their
427   // exits have all their predecessors inside the loop.
428   return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
429 }
430 
431 // Routines that reform the loop CFG and split edges often fail on indirectbr.
432 bool Loop::isSafeToClone() const {
433   // Return false if any loop blocks contain indirectbrs, or there are any calls
434   // to noduplicate functions.
435   for (BasicBlock *BB : this->blocks()) {
436     if (isa<IndirectBrInst>(BB->getTerminator()))
437       return false;
438 
439     for (Instruction &I : *BB)
440       if (auto CS = CallSite(&I))
441         if (CS.cannotDuplicate())
442           return false;
443   }
444   return true;
445 }
446 
447 MDNode *Loop::getLoopID() const {
448   MDNode *LoopID = nullptr;
449 
450   // Go through the latch blocks and check the terminator for the metadata.
451   SmallVector<BasicBlock *, 4> LatchesBlocks;
452   getLoopLatches(LatchesBlocks);
453   for (BasicBlock *BB : LatchesBlocks) {
454     Instruction *TI = BB->getTerminator();
455     MDNode *MD = TI->getMetadata(LLVMContext::MD_loop);
456 
457     if (!MD)
458       return nullptr;
459 
460     if (!LoopID)
461       LoopID = MD;
462     else if (MD != LoopID)
463       return nullptr;
464   }
465   if (!LoopID || LoopID->getNumOperands() == 0 ||
466       LoopID->getOperand(0) != LoopID)
467     return nullptr;
468   return LoopID;
469 }
470 
471 void Loop::setLoopID(MDNode *LoopID) const {
472   assert((!LoopID || LoopID->getNumOperands() > 0) &&
473          "Loop ID needs at least one operand");
474   assert((!LoopID || LoopID->getOperand(0) == LoopID) &&
475          "Loop ID should refer to itself");
476 
477   SmallVector<BasicBlock *, 4> LoopLatches;
478   getLoopLatches(LoopLatches);
479   for (BasicBlock *BB : LoopLatches)
480     BB->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID);
481 }
482 
483 void Loop::setLoopAlreadyUnrolled() {
484   LLVMContext &Context = getHeader()->getContext();
485 
486   MDNode *DisableUnrollMD =
487       MDNode::get(Context, MDString::get(Context, "llvm.loop.unroll.disable"));
488   MDNode *LoopID = getLoopID();
489   MDNode *NewLoopID = makePostTransformationMetadata(
490       Context, LoopID, {"llvm.loop.unroll."}, {DisableUnrollMD});
491   setLoopID(NewLoopID);
492 }
493 
494 bool Loop::isAnnotatedParallel() const {
495   MDNode *DesiredLoopIdMetadata = getLoopID();
496 
497   if (!DesiredLoopIdMetadata)
498     return false;
499 
500   MDNode *ParallelAccesses =
501       findOptionMDForLoop(this, "llvm.loop.parallel_accesses");
502   SmallPtrSet<MDNode *, 4>
503       ParallelAccessGroups; // For scalable 'contains' check.
504   if (ParallelAccesses) {
505     for (const MDOperand &MD : drop_begin(ParallelAccesses->operands(), 1)) {
506       MDNode *AccGroup = cast<MDNode>(MD.get());
507       assert(isValidAsAccessGroup(AccGroup) &&
508              "List item must be an access group");
509       ParallelAccessGroups.insert(AccGroup);
510     }
511   }
512 
513   // The loop branch contains the parallel loop metadata. In order to ensure
514   // that any parallel-loop-unaware optimization pass hasn't added loop-carried
515   // dependencies (thus converted the loop back to a sequential loop), check
516   // that all the memory instructions in the loop belong to an access group that
517   // is parallel to this loop.
518   for (BasicBlock *BB : this->blocks()) {
519     for (Instruction &I : *BB) {
520       if (!I.mayReadOrWriteMemory())
521         continue;
522 
523       if (MDNode *AccessGroup = I.getMetadata(LLVMContext::MD_access_group)) {
524         auto ContainsAccessGroup = [&ParallelAccessGroups](MDNode *AG) -> bool {
525           if (AG->getNumOperands() == 0) {
526             assert(isValidAsAccessGroup(AG) && "Item must be an access group");
527             return ParallelAccessGroups.count(AG);
528           }
529 
530           for (const MDOperand &AccessListItem : AG->operands()) {
531             MDNode *AccGroup = cast<MDNode>(AccessListItem.get());
532             assert(isValidAsAccessGroup(AccGroup) &&
533                    "List item must be an access group");
534             if (ParallelAccessGroups.count(AccGroup))
535               return true;
536           }
537           return false;
538         };
539 
540         if (ContainsAccessGroup(AccessGroup))
541           continue;
542       }
543 
544       // The memory instruction can refer to the loop identifier metadata
545       // directly or indirectly through another list metadata (in case of
546       // nested parallel loops). The loop identifier metadata refers to
547       // itself so we can check both cases with the same routine.
548       MDNode *LoopIdMD =
549           I.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
550 
551       if (!LoopIdMD)
552         return false;
553 
554       bool LoopIdMDFound = false;
555       for (const MDOperand &MDOp : LoopIdMD->operands()) {
556         if (MDOp == DesiredLoopIdMetadata) {
557           LoopIdMDFound = true;
558           break;
559         }
560       }
561 
562       if (!LoopIdMDFound)
563         return false;
564     }
565   }
566   return true;
567 }
568 
569 DebugLoc Loop::getStartLoc() const { return getLocRange().getStart(); }
570 
571 Loop::LocRange Loop::getLocRange() const {
572   // If we have a debug location in the loop ID, then use it.
573   if (MDNode *LoopID = getLoopID()) {
574     DebugLoc Start;
575     // We use the first DebugLoc in the header as the start location of the loop
576     // and if there is a second DebugLoc in the header we use it as end location
577     // of the loop.
578     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
579       if (DILocation *L = dyn_cast<DILocation>(LoopID->getOperand(i))) {
580         if (!Start)
581           Start = DebugLoc(L);
582         else
583           return LocRange(Start, DebugLoc(L));
584       }
585     }
586 
587     if (Start)
588       return LocRange(Start);
589   }
590 
591   // Try the pre-header first.
592   if (BasicBlock *PHeadBB = getLoopPreheader())
593     if (DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc())
594       return LocRange(DL);
595 
596   // If we have no pre-header or there are no instructions with debug
597   // info in it, try the header.
598   if (BasicBlock *HeadBB = getHeader())
599     return LocRange(HeadBB->getTerminator()->getDebugLoc());
600 
601   return LocRange();
602 }
603 
604 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
605 LLVM_DUMP_METHOD void Loop::dump() const { print(dbgs()); }
606 
607 LLVM_DUMP_METHOD void Loop::dumpVerbose() const {
608   print(dbgs(), /*Depth=*/0, /*Verbose=*/true);
609 }
610 #endif
611 
612 //===----------------------------------------------------------------------===//
613 // UnloopUpdater implementation
614 //
615 
616 namespace {
617 /// Find the new parent loop for all blocks within the "unloop" whose last
618 /// backedges has just been removed.
619 class UnloopUpdater {
620   Loop &Unloop;
621   LoopInfo *LI;
622 
623   LoopBlocksDFS DFS;
624 
625   // Map unloop's immediate subloops to their nearest reachable parents. Nested
626   // loops within these subloops will not change parents. However, an immediate
627   // subloop's new parent will be the nearest loop reachable from either its own
628   // exits *or* any of its nested loop's exits.
629   DenseMap<Loop *, Loop *> SubloopParents;
630 
631   // Flag the presence of an irreducible backedge whose destination is a block
632   // directly contained by the original unloop.
633   bool FoundIB;
634 
635 public:
636   UnloopUpdater(Loop *UL, LoopInfo *LInfo)
637       : Unloop(*UL), LI(LInfo), DFS(UL), FoundIB(false) {}
638 
639   void updateBlockParents();
640 
641   void removeBlocksFromAncestors();
642 
643   void updateSubloopParents();
644 
645 protected:
646   Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
647 };
648 } // end anonymous namespace
649 
650 /// Update the parent loop for all blocks that are directly contained within the
651 /// original "unloop".
652 void UnloopUpdater::updateBlockParents() {
653   if (Unloop.getNumBlocks()) {
654     // Perform a post order CFG traversal of all blocks within this loop,
655     // propagating the nearest loop from successors to predecessors.
656     LoopBlocksTraversal Traversal(DFS, LI);
657     for (BasicBlock *POI : Traversal) {
658 
659       Loop *L = LI->getLoopFor(POI);
660       Loop *NL = getNearestLoop(POI, L);
661 
662       if (NL != L) {
663         // For reducible loops, NL is now an ancestor of Unloop.
664         assert((NL != &Unloop && (!NL || NL->contains(&Unloop))) &&
665                "uninitialized successor");
666         LI->changeLoopFor(POI, NL);
667       } else {
668         // Or the current block is part of a subloop, in which case its parent
669         // is unchanged.
670         assert((FoundIB || Unloop.contains(L)) && "uninitialized successor");
671       }
672     }
673   }
674   // Each irreducible loop within the unloop induces a round of iteration using
675   // the DFS result cached by Traversal.
676   bool Changed = FoundIB;
677   for (unsigned NIters = 0; Changed; ++NIters) {
678     assert(NIters < Unloop.getNumBlocks() && "runaway iterative algorithm");
679 
680     // Iterate over the postorder list of blocks, propagating the nearest loop
681     // from successors to predecessors as before.
682     Changed = false;
683     for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
684                                    POE = DFS.endPostorder();
685          POI != POE; ++POI) {
686 
687       Loop *L = LI->getLoopFor(*POI);
688       Loop *NL = getNearestLoop(*POI, L);
689       if (NL != L) {
690         assert(NL != &Unloop && (!NL || NL->contains(&Unloop)) &&
691                "uninitialized successor");
692         LI->changeLoopFor(*POI, NL);
693         Changed = true;
694       }
695     }
696   }
697 }
698 
699 /// Remove unloop's blocks from all ancestors below their new parents.
700 void UnloopUpdater::removeBlocksFromAncestors() {
701   // Remove all unloop's blocks (including those in nested subloops) from
702   // ancestors below the new parent loop.
703   for (Loop::block_iterator BI = Unloop.block_begin(), BE = Unloop.block_end();
704        BI != BE; ++BI) {
705     Loop *OuterParent = LI->getLoopFor(*BI);
706     if (Unloop.contains(OuterParent)) {
707       while (OuterParent->getParentLoop() != &Unloop)
708         OuterParent = OuterParent->getParentLoop();
709       OuterParent = SubloopParents[OuterParent];
710     }
711     // Remove blocks from former Ancestors except Unloop itself which will be
712     // deleted.
713     for (Loop *OldParent = Unloop.getParentLoop(); OldParent != OuterParent;
714          OldParent = OldParent->getParentLoop()) {
715       assert(OldParent && "new loop is not an ancestor of the original");
716       OldParent->removeBlockFromLoop(*BI);
717     }
718   }
719 }
720 
721 /// Update the parent loop for all subloops directly nested within unloop.
722 void UnloopUpdater::updateSubloopParents() {
723   while (!Unloop.empty()) {
724     Loop *Subloop = *std::prev(Unloop.end());
725     Unloop.removeChildLoop(std::prev(Unloop.end()));
726 
727     assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
728     if (Loop *Parent = SubloopParents[Subloop])
729       Parent->addChildLoop(Subloop);
730     else
731       LI->addTopLevelLoop(Subloop);
732   }
733 }
734 
735 /// Return the nearest parent loop among this block's successors. If a successor
736 /// is a subloop header, consider its parent to be the nearest parent of the
737 /// subloop's exits.
738 ///
739 /// For subloop blocks, simply update SubloopParents and return NULL.
740 Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
741 
742   // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
743   // is considered uninitialized.
744   Loop *NearLoop = BBLoop;
745 
746   Loop *Subloop = nullptr;
747   if (NearLoop != &Unloop && Unloop.contains(NearLoop)) {
748     Subloop = NearLoop;
749     // Find the subloop ancestor that is directly contained within Unloop.
750     while (Subloop->getParentLoop() != &Unloop) {
751       Subloop = Subloop->getParentLoop();
752       assert(Subloop && "subloop is not an ancestor of the original loop");
753     }
754     // Get the current nearest parent of the Subloop exits, initially Unloop.
755     NearLoop = SubloopParents.insert({Subloop, &Unloop}).first->second;
756   }
757 
758   succ_iterator I = succ_begin(BB), E = succ_end(BB);
759   if (I == E) {
760     assert(!Subloop && "subloop blocks must have a successor");
761     NearLoop = nullptr; // unloop blocks may now exit the function.
762   }
763   for (; I != E; ++I) {
764     if (*I == BB)
765       continue; // self loops are uninteresting
766 
767     Loop *L = LI->getLoopFor(*I);
768     if (L == &Unloop) {
769       // This successor has not been processed. This path must lead to an
770       // irreducible backedge.
771       assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
772       FoundIB = true;
773     }
774     if (L != &Unloop && Unloop.contains(L)) {
775       // Successor is in a subloop.
776       if (Subloop)
777         continue; // Branching within subloops. Ignore it.
778 
779       // BB branches from the original into a subloop header.
780       assert(L->getParentLoop() == &Unloop && "cannot skip into nested loops");
781 
782       // Get the current nearest parent of the Subloop's exits.
783       L = SubloopParents[L];
784       // L could be Unloop if the only exit was an irreducible backedge.
785     }
786     if (L == &Unloop) {
787       continue;
788     }
789     // Handle critical edges from Unloop into a sibling loop.
790     if (L && !L->contains(&Unloop)) {
791       L = L->getParentLoop();
792     }
793     // Remember the nearest parent loop among successors or subloop exits.
794     if (NearLoop == &Unloop || !NearLoop || NearLoop->contains(L))
795       NearLoop = L;
796   }
797   if (Subloop) {
798     SubloopParents[Subloop] = NearLoop;
799     return BBLoop;
800   }
801   return NearLoop;
802 }
803 
804 LoopInfo::LoopInfo(const DomTreeBase<BasicBlock> &DomTree) { analyze(DomTree); }
805 
806 bool LoopInfo::invalidate(Function &F, const PreservedAnalyses &PA,
807                           FunctionAnalysisManager::Invalidator &) {
808   // Check whether the analysis, all analyses on functions, or the function's
809   // CFG have been preserved.
810   auto PAC = PA.getChecker<LoopAnalysis>();
811   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
812            PAC.preservedSet<CFGAnalyses>());
813 }
814 
815 void LoopInfo::erase(Loop *Unloop) {
816   assert(!Unloop->isInvalid() && "Loop has already been erased!");
817 
818   auto InvalidateOnExit = make_scope_exit([&]() { destroy(Unloop); });
819 
820   // First handle the special case of no parent loop to simplify the algorithm.
821   if (!Unloop->getParentLoop()) {
822     // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
823     for (Loop::block_iterator I = Unloop->block_begin(),
824                               E = Unloop->block_end();
825          I != E; ++I) {
826 
827       // Don't reparent blocks in subloops.
828       if (getLoopFor(*I) != Unloop)
829         continue;
830 
831       // Blocks no longer have a parent but are still referenced by Unloop until
832       // the Unloop object is deleted.
833       changeLoopFor(*I, nullptr);
834     }
835 
836     // Remove the loop from the top-level LoopInfo object.
837     for (iterator I = begin();; ++I) {
838       assert(I != end() && "Couldn't find loop");
839       if (*I == Unloop) {
840         removeLoop(I);
841         break;
842       }
843     }
844 
845     // Move all of the subloops to the top-level.
846     while (!Unloop->empty())
847       addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
848 
849     return;
850   }
851 
852   // Update the parent loop for all blocks within the loop. Blocks within
853   // subloops will not change parents.
854   UnloopUpdater Updater(Unloop, this);
855   Updater.updateBlockParents();
856 
857   // Remove blocks from former ancestor loops.
858   Updater.removeBlocksFromAncestors();
859 
860   // Add direct subloops as children in their new parent loop.
861   Updater.updateSubloopParents();
862 
863   // Remove unloop from its parent loop.
864   Loop *ParentLoop = Unloop->getParentLoop();
865   for (Loop::iterator I = ParentLoop->begin();; ++I) {
866     assert(I != ParentLoop->end() && "Couldn't find loop");
867     if (*I == Unloop) {
868       ParentLoop->removeChildLoop(I);
869       break;
870     }
871   }
872 }
873 
874 AnalysisKey LoopAnalysis::Key;
875 
876 LoopInfo LoopAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
877   // FIXME: Currently we create a LoopInfo from scratch for every function.
878   // This may prove to be too wasteful due to deallocating and re-allocating
879   // memory each time for the underlying map and vector datastructures. At some
880   // point it may prove worthwhile to use a freelist and recycle LoopInfo
881   // objects. I don't want to add that kind of complexity until the scope of
882   // the problem is better understood.
883   LoopInfo LI;
884   LI.analyze(AM.getResult<DominatorTreeAnalysis>(F));
885   return LI;
886 }
887 
888 PreservedAnalyses LoopPrinterPass::run(Function &F,
889                                        FunctionAnalysisManager &AM) {
890   AM.getResult<LoopAnalysis>(F).print(OS);
891   return PreservedAnalyses::all();
892 }
893 
894 void llvm::printLoop(Loop &L, raw_ostream &OS, const std::string &Banner) {
895 
896   if (forcePrintModuleIR()) {
897     // handling -print-module-scope
898     OS << Banner << " (loop: ";
899     L.getHeader()->printAsOperand(OS, false);
900     OS << ")\n";
901 
902     // printing whole module
903     OS << *L.getHeader()->getModule();
904     return;
905   }
906 
907   OS << Banner;
908 
909   auto *PreHeader = L.getLoopPreheader();
910   if (PreHeader) {
911     OS << "\n; Preheader:";
912     PreHeader->print(OS);
913     OS << "\n; Loop:";
914   }
915 
916   for (auto *Block : L.blocks())
917     if (Block)
918       Block->print(OS);
919     else
920       OS << "Printing <null> block";
921 
922   SmallVector<BasicBlock *, 8> ExitBlocks;
923   L.getExitBlocks(ExitBlocks);
924   if (!ExitBlocks.empty()) {
925     OS << "\n; Exit blocks";
926     for (auto *Block : ExitBlocks)
927       if (Block)
928         Block->print(OS);
929       else
930         OS << "Printing <null> block";
931   }
932 }
933 
934 MDNode *llvm::findOptionMDForLoopID(MDNode *LoopID, StringRef Name) {
935   // No loop metadata node, no loop properties.
936   if (!LoopID)
937     return nullptr;
938 
939   // First operand should refer to the metadata node itself, for legacy reasons.
940   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
941   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
942 
943   // Iterate over the metdata node operands and look for MDString metadata.
944   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
945     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
946     if (!MD || MD->getNumOperands() < 1)
947       continue;
948     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
949     if (!S)
950       continue;
951     // Return the operand node if MDString holds expected metadata.
952     if (Name.equals(S->getString()))
953       return MD;
954   }
955 
956   // Loop property not found.
957   return nullptr;
958 }
959 
960 MDNode *llvm::findOptionMDForLoop(const Loop *TheLoop, StringRef Name) {
961   return findOptionMDForLoopID(TheLoop->getLoopID(), Name);
962 }
963 
964 bool llvm::isValidAsAccessGroup(MDNode *Node) {
965   return Node->getNumOperands() == 0 && Node->isDistinct();
966 }
967 
968 MDNode *llvm::makePostTransformationMetadata(LLVMContext &Context,
969                                              MDNode *OrigLoopID,
970                                              ArrayRef<StringRef> RemovePrefixes,
971                                              ArrayRef<MDNode *> AddAttrs) {
972   // First remove any existing loop metadata related to this transformation.
973   SmallVector<Metadata *, 4> MDs;
974 
975   // Reserve first location for self reference to the LoopID metadata node.
976   TempMDTuple TempNode = MDNode::getTemporary(Context, None);
977   MDs.push_back(TempNode.get());
978 
979   // Remove metadata for the transformation that has been applied or that became
980   // outdated.
981   if (OrigLoopID) {
982     for (unsigned i = 1, ie = OrigLoopID->getNumOperands(); i < ie; ++i) {
983       bool IsVectorMetadata = false;
984       Metadata *Op = OrigLoopID->getOperand(i);
985       if (MDNode *MD = dyn_cast<MDNode>(Op)) {
986         const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
987         if (S)
988           IsVectorMetadata =
989               llvm::any_of(RemovePrefixes, [S](StringRef Prefix) -> bool {
990                 return S->getString().startswith(Prefix);
991               });
992       }
993       if (!IsVectorMetadata)
994         MDs.push_back(Op);
995     }
996   }
997 
998   // Add metadata to avoid reapplying a transformation, such as
999   // llvm.loop.unroll.disable and llvm.loop.isvectorized.
1000   MDs.append(AddAttrs.begin(), AddAttrs.end());
1001 
1002   MDNode *NewLoopID = MDNode::getDistinct(Context, MDs);
1003   // Replace the temporary node with a self-reference.
1004   NewLoopID->replaceOperandWith(0, NewLoopID);
1005   return NewLoopID;
1006 }
1007 
1008 //===----------------------------------------------------------------------===//
1009 // LoopInfo implementation
1010 //
1011 
1012 char LoopInfoWrapperPass::ID = 0;
1013 INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
1014                       true, true)
1015 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1016 INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
1017                     true, true)
1018 
1019 bool LoopInfoWrapperPass::runOnFunction(Function &) {
1020   releaseMemory();
1021   LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
1022   return false;
1023 }
1024 
1025 void LoopInfoWrapperPass::verifyAnalysis() const {
1026   // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
1027   // function each time verifyAnalysis is called is very expensive. The
1028   // -verify-loop-info option can enable this. In order to perform some
1029   // checking by default, LoopPass has been taught to call verifyLoop manually
1030   // during loop pass sequences.
1031   if (VerifyLoopInfo) {
1032     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1033     LI.verify(DT);
1034   }
1035 }
1036 
1037 void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1038   AU.setPreservesAll();
1039   AU.addRequired<DominatorTreeWrapperPass>();
1040 }
1041 
1042 void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
1043   LI.print(OS);
1044 }
1045 
1046 PreservedAnalyses LoopVerifierPass::run(Function &F,
1047                                         FunctionAnalysisManager &AM) {
1048   LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
1049   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1050   LI.verify(DT);
1051   return PreservedAnalyses::all();
1052 }
1053 
1054 //===----------------------------------------------------------------------===//
1055 // LoopBlocksDFS implementation
1056 //
1057 
1058 /// Traverse the loop blocks and store the DFS result.
1059 /// Useful for clients that just want the final DFS result and don't need to
1060 /// visit blocks during the initial traversal.
1061 void LoopBlocksDFS::perform(LoopInfo *LI) {
1062   LoopBlocksTraversal Traversal(*this, LI);
1063   for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
1064                                         POE = Traversal.end();
1065        POI != POE; ++POI)
1066     ;
1067 }
1068