LLVM 24.0.0git
LoopInfo.cpp
Go to the documentation of this file.
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
17#include "llvm/ADT/ScopeExit.h"
19#include "llvm/Analysis/CFG.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"
33#include "llvm/IR/LLVMContext.h"
34#include "llvm/IR/Metadata.h"
35#include "llvm/IR/Module.h"
36#include "llvm/IR/PassManager.h"
37#include "llvm/IR/PrintPasses.h"
44using namespace llvm;
45
46// Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
49
50// Always verify loopinfo if expensive checking is enabled.
51#ifdef EXPENSIVE_CHECKS
52bool llvm::VerifyLoopInfo = true;
53#else
55#endif
58 cl::Hidden, cl::desc("Verify loop info (time consuming)"));
59
60namespace llvm {
62} // end namespace llvm
63
64//===----------------------------------------------------------------------===//
65// Loop implementation
66//
67
68bool Loop::isLoopInvariant(const Value *V) const {
69 if (const Instruction *I = dyn_cast<Instruction>(V))
70 return !contains(I);
71 return true; // All non-instructions are loop invariant
72}
73
75 return all_of(I->operands(), [&](Value *V) { return isLoopInvariant(V); });
76}
77
79 MemorySSAUpdater *MSSAU,
80 ScalarEvolution *SE) const {
82 return makeLoopInvariant(I, Changed, InsertPt, MSSAU, SE);
83 return true; // All non-instructions are loop-invariant.
84}
85
87 Instruction *InsertPt, MemorySSAUpdater *MSSAU,
88 ScalarEvolution *SE) const {
89 BasicBlock *OriginalParent = I->getParent();
90 // Test if the value is already loop-invariant.
91 if (isLoopInvariant(I))
92 return true;
94 return false;
95 if (I->mayReadFromMemory())
96 return false;
97 // EH block instructions are immobile.
98 if (I->isEHPad())
99 return false;
100 // Determine the insertion point, unless one was given.
101 if (!InsertPt) {
102 BasicBlock *Preheader = getLoopPreheader();
103 // Without a preheader, hoisting is not feasible.
104 if (!Preheader)
105 return false;
106 InsertPt = Preheader->getTerminator();
107 }
108 // Don't hoist instructions with loop-variant operands.
109 for (Value *Operand : I->operands())
110 if (!makeLoopInvariant(Operand, Changed, InsertPt, MSSAU, SE))
111 return false;
112
113 // Hoist.
114 I->moveBefore(InsertPt->getIterator());
115 if (MSSAU)
116 if (auto *MUD = MSSAU->getMemorySSA()->getMemoryAccess(I))
117 MSSAU->moveToPlace(MUD, InsertPt->getParent(),
119
120 // We want to preserve profile metadata if possible. However, we need to
121 // ensure that profile metadata would remain the same outside of the loop.
122 // Given at this point we know the conditional is loop-invariant, we just
123 // need to worry about other control flow in the loop conditioned on values
124 // that are potentially not independent of the condition of the instruction
125 // we are interested in hoisting. Given this is not knowable in the general
126 // case, we only hoist from a loop header (which covers a reasonable number
127 // of cases) where we are guaranteed to not run into problems.
128 SmallVector<unsigned, 1> ProfileMetadataToPreserve;
130 if (OriginalParent == getHeader())
131 ProfileMetadataToPreserve.push_back(LLVMContext::MD_prof);
132
133 // There is possibility of hoisting this instruction above some arbitrary
134 // condition. Any metadata defined on it can be control dependent on this
135 // condition. Conservatively strip it here so that we don't give any wrong
136 // information to the optimizer.
137 I->dropUBImplyingAttrsAndUnknownMetadata(ProfileMetadataToPreserve);
138
139 if (ProfileMetadataToPreserve.empty() && isa<SelectInst>(I))
141
142 if (SE)
144
145 Changed = true;
146 return true;
147}
148
150 BasicBlock *&Backedge) const {
152
153 Incoming = nullptr;
154 Backedge = nullptr;
156 assert(PI != pred_end(H) && "Loop must have at least one backedge!");
157 Backedge = *PI++;
158 if (PI == pred_end(H))
159 return false; // dead loop
160 Incoming = *PI++;
161 if (PI != pred_end(H))
162 return false; // multiple backedges?
163
164 if (contains(Incoming)) {
165 if (contains(Backedge))
166 return false;
167 std::swap(Incoming, Backedge);
168 } else if (!contains(Backedge))
169 return false;
170
171 assert(Incoming && Backedge && "expected non-null incoming and backedges");
172 return true;
173}
174
177
178 BasicBlock *Incoming = nullptr, *Backedge = nullptr;
179 if (!getIncomingAndBackEdge(Incoming, Backedge))
180 return nullptr;
181
182 // Loop over all of the PHI nodes, looking for a canonical indvar.
183 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
184 PHINode *PN = cast<PHINode>(I);
185 if (ConstantInt *CI =
187 if (CI->isZero())
188 if (Instruction *Inc =
190 if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
191 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
192 if (CI->isOne())
193 return PN;
194 }
195 return nullptr;
196}
197
198/// Get the latch condition instruction.
200 if (BasicBlock *Latch = getLoopLatch())
201 if (CondBrInst *BI = dyn_cast_or_null<CondBrInst>(Latch->getTerminator()))
202 return dyn_cast<ICmpInst>(BI->getCondition());
203
204 return nullptr;
205}
206
207/// Return the final value of the loop induction variable if found.
208static Value *findFinalIVValue(const Loop &L, const PHINode &IndVar,
209 const Instruction &StepInst) {
210 ICmpInst *LatchCmpInst = L.getLatchCmpInst();
211 if (!LatchCmpInst)
212 return nullptr;
213
214 Value *Op0 = LatchCmpInst->getOperand(0);
215 Value *Op1 = LatchCmpInst->getOperand(1);
216 if (Op0 == &IndVar || Op0 == &StepInst)
217 return Op1;
218
219 if (Op1 == &IndVar || Op1 == &StepInst)
220 return Op0;
221
222 return nullptr;
223}
224
225std::optional<Loop::LoopBounds>
227 ScalarEvolution &SE) {
228 InductionDescriptor IndDesc;
229 if (!InductionDescriptor::isInductionPHI(&IndVar, &L, &SE, IndDesc))
230 return std::nullopt;
231
232 Value *InitialIVValue = IndDesc.getStartValue();
233 Instruction *StepInst = IndDesc.getInductionBinOp();
234 if (!InitialIVValue || !StepInst)
235 return std::nullopt;
236
237 const SCEV *Step = IndDesc.getStep();
238 Value *StepInstOp1 = StepInst->getOperand(1);
239 Value *StepInstOp0 = StepInst->getOperand(0);
240 Value *StepValue = nullptr;
241 if (SE.getSCEV(StepInstOp1) == Step)
242 StepValue = StepInstOp1;
243 else if (SE.getSCEV(StepInstOp0) == Step)
244 StepValue = StepInstOp0;
245
246 Value *FinalIVValue = findFinalIVValue(L, IndVar, *StepInst);
247 if (!FinalIVValue)
248 return std::nullopt;
249
250 return LoopBounds(L, *InitialIVValue, *StepInst, StepValue, *FinalIVValue,
251 SE);
252}
253
255
257 BasicBlock *Latch = L.getLoopLatch();
258 assert(Latch && "Expecting valid latch");
259
261
262 ICmpInst *LatchCmpInst = dyn_cast<ICmpInst>(BI->getCondition());
263 assert(LatchCmpInst &&
264 "Expecting the latch compare instruction to be a CmpInst");
265
266 // Need to inverse the predicate when first successor is not the loop
267 // header
268 ICmpInst::Predicate Pred = (BI->getSuccessor(0) == L.getHeader())
269 ? LatchCmpInst->getPredicate()
270 : LatchCmpInst->getInversePredicate();
271
272 if (LatchCmpInst->getOperand(0) == &getFinalIVValue())
274
275 // Need to flip strictness of the predicate when the latch compare instruction
276 // is not using StepInst
277 if (LatchCmpInst->getOperand(0) == &getStepInst() ||
278 LatchCmpInst->getOperand(1) == &getStepInst())
279 return Pred;
280
281 // Cannot flip strictness of NE and EQ
282 if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
284
286 if (D == Direction::Increasing)
287 return ICmpInst::ICMP_SLT;
288
289 if (D == Direction::Decreasing)
290 return ICmpInst::ICMP_SGT;
291
292 // If cannot determine the direction, then unable to find the canonical
293 // predicate
295}
296
298 if (const SCEVAddRecExpr *StepAddRecExpr =
300 if (const SCEV *StepRecur = StepAddRecExpr->getStepRecurrence(SE)) {
301 if (SE.isKnownPositive(StepRecur))
302 return Direction::Increasing;
303 if (SE.isKnownNegative(StepRecur))
304 return Direction::Decreasing;
305 }
306
307 return Direction::Unknown;
308}
309
310std::optional<Loop::LoopBounds> Loop::getBounds(ScalarEvolution &SE) const {
311 if (PHINode *IndVar = getInductionVariable(SE))
312 return LoopBounds::getBounds(*this, *IndVar, SE);
313
314 return std::nullopt;
315}
316
318 if (!isLoopSimplifyForm())
319 return nullptr;
320
321 BasicBlock *Header = getHeader();
322 assert(Header && "Expected a valid loop header");
324 if (!CmpInst)
325 return nullptr;
326
327 Value *LatchCmpOp0 = CmpInst->getOperand(0);
328 Value *LatchCmpOp1 = CmpInst->getOperand(1);
329
330 for (PHINode &IndVar : Header->phis()) {
331 InductionDescriptor IndDesc;
332 if (!InductionDescriptor::isInductionPHI(&IndVar, this, &SE, IndDesc))
333 continue;
334
335 BasicBlock *Latch = getLoopLatch();
336 Value *StepInst = IndVar.getIncomingValueForBlock(Latch);
337
338 // case 1:
339 // IndVar = phi[{InitialValue, preheader}, {StepInst, latch}]
340 // StepInst = IndVar + step
341 // cmp = StepInst < FinalValue
342 if (StepInst == LatchCmpOp0 || StepInst == LatchCmpOp1)
343 return &IndVar;
344
345 // case 2:
346 // IndVar = phi[{InitialValue, preheader}, {StepInst, latch}]
347 // StepInst = IndVar + step
348 // cmp = IndVar < FinalValue
349 if (&IndVar == LatchCmpOp0 || &IndVar == LatchCmpOp1)
350 return &IndVar;
351 }
352
353 return nullptr;
354}
355
357 InductionDescriptor &IndDesc) const {
358 if (PHINode *IndVar = getInductionVariable(SE))
359 return InductionDescriptor::isInductionPHI(IndVar, this, &SE, IndDesc);
360
361 return false;
362}
363
365 ScalarEvolution &SE) const {
366 // Located in the loop header
367 BasicBlock *Header = getHeader();
368 if (AuxIndVar.getParent() != Header)
369 return false;
370
371 // No uses outside of the loop
372 for (User *U : AuxIndVar.users())
373 if (const Instruction *I = dyn_cast<Instruction>(U))
374 if (!contains(I))
375 return false;
376
377 InductionDescriptor IndDesc;
378 if (!InductionDescriptor::isInductionPHI(&AuxIndVar, this, &SE, IndDesc))
379 return false;
380
381 // The step instruction opcode should be add or sub.
382 if (IndDesc.getInductionOpcode() != Instruction::Add &&
383 IndDesc.getInductionOpcode() != Instruction::Sub)
384 return false;
385
386 // Incremented by a loop invariant step for each loop iteration
387 return SE.isLoopInvariant(IndDesc.getStep(), this);
388}
389
391 if (!isLoopSimplifyForm())
392 return nullptr;
393
394 BasicBlock *Preheader = getLoopPreheader();
395 assert(Preheader && getLoopLatch() &&
396 "Expecting a loop with valid preheader and latch");
397
398 // Loop should be in rotate form.
399 if (!isRotatedForm())
400 return nullptr;
401
402 // Disallow loops with more than one unique exit block, as we do not verify
403 // that GuardOtherSucc post dominates all exit blocks.
404 BasicBlock *ExitFromLatch = getUniqueExitBlock();
405 if (!ExitFromLatch)
406 return nullptr;
407
408 BasicBlock *GuardBB = Preheader->getUniquePredecessor();
409 if (!GuardBB)
410 return nullptr;
411
412 assert(GuardBB->getTerminator() && "Expecting valid guard terminator");
413
414 CondBrInst *GuardBI = dyn_cast<CondBrInst>(GuardBB->getTerminator());
415 if (!GuardBI)
416 return nullptr;
417
418 BasicBlock *GuardOtherSucc = (GuardBI->getSuccessor(0) == Preheader)
419 ? GuardBI->getSuccessor(1)
420 : GuardBI->getSuccessor(0);
421
422 // Check if ExitFromLatch (or any BasicBlock which is an empty unique
423 // successor of ExitFromLatch) is equal to GuardOtherSucc. If
424 // skipEmptyBlockUntil returns GuardOtherSucc, then the guard branch for the
425 // loop is GuardBI (return GuardBI), otherwise return nullptr.
426 if (&LoopNest::skipEmptyBlockUntil(ExitFromLatch, GuardOtherSucc,
427 /*CheckUniquePred=*/true) ==
428 GuardOtherSucc)
429 return GuardBI;
430 else
431 return nullptr;
432}
433
435 InductionDescriptor IndDesc;
436 if (!getInductionDescriptor(SE, IndDesc))
437 return false;
438
440 if (!Init || !Init->isZero())
441 return false;
442
443 if (IndDesc.getInductionOpcode() != Instruction::Add)
444 return false;
445
446 ConstantInt *Step = IndDesc.getConstIntStepValue();
447 if (!Step || !Step->isOne())
448 return false;
449
450 return true;
451}
452
453// Check whether the use \p U of a value defined in block \p BB (which is part
454// of loop \p L) does not require a live-out phi, i.e. whether it is contained
455// in the loop for LCSSA purposes.
456static bool loopContainsUser(const Loop &L, const BasicBlock &BB, const Use &U,
457 const DominatorTree &DT) {
458 const Instruction *UI = cast<Instruction>(U.getUser());
459 const BasicBlock *UserBB = UI->getParent();
460
461 // For practical purposes, we consider that the use in a PHI
462 // occurs in the respective predecessor block. For more info,
463 // see the `phi` doc in LangRef and the LCSSA doc.
464 if (const PHINode *P = dyn_cast<PHINode>(UI))
465 UserBB = P->getIncomingBlock(U);
466
467 // Check the current block, as a fast-path, before checking whether
468 // the use is anywhere in the loop. Most values are used in the same
469 // block they are defined in. Also, blocks not reachable from the
470 // entry are special; uses in them don't need to go through PHIs.
471 if (UserBB != &BB && !L.contains(UserBB) && DT.isReachableFromEntry(UserBB))
472 return false;
473
474 return true;
475}
476
477// Check that 'BB' doesn't have any uses outside of the 'L'
478static bool isBlockInLCSSAForm(const Loop &L, const BasicBlock &BB,
479 const DominatorTree &DT, bool IgnoreTokens) {
480 for (const Instruction &I : BB) {
481 // Token-like values can't be used in PHI nodes and live-out token-like
482 // values prevent loop optimizations, so for the purposes of considered
483 // LCSSA form, we can ignore them.
484 if (IgnoreTokens && I.getType()->isTokenLikeTy())
485 continue;
486
487 for (const Use &U : I.uses()) {
488 if (!loopContainsUser(L, BB, U, DT))
489 return false;
490 }
491 }
492 return true;
493}
494
495bool Loop::isLCSSAForm(const DominatorTree &DT, bool IgnoreTokens) const {
496 // For each block we check that it doesn't have any uses outside of this loop.
497 return all_of(this->blocks(), [&](const BasicBlock *BB) {
498 return isBlockInLCSSAForm(*this, *BB, DT, IgnoreTokens);
499 });
500}
501
503 bool IgnoreTokens) const {
504 // For each block we check that it doesn't have any uses outside of its
505 // innermost loop. This process will transitively guarantee that the current
506 // loop and all of the nested loops are in LCSSA form.
507 return all_of(this->blocks(), [&](const BasicBlock *BB) {
508 return isBlockInLCSSAForm(*LI.getLoopFor(BB), *BB, DT, IgnoreTokens);
509 });
510}
511
513 // Normal-form loops have a preheader, a single backedge, and all of their
514 // exits have all their predecessors inside the loop.
516}
517
518// Routines that reform the loop CFG and split edges often fail on indirectbr.
520 // Return false if any loop blocks contain indirectbrs, or there are any calls
521 // to noduplicate functions.
522 for (BasicBlock *BB : this->blocks()) {
523 if (isa<IndirectBrInst>(BB->getTerminator()))
524 return false;
525
526 for (Instruction &I : *BB)
527 if (auto *CB = dyn_cast<CallBase>(&I))
528 if (CB->cannotDuplicate())
529 return false;
530 }
531 return true;
532}
533
535 if (!isSafeToClone())
536 return false;
537
538 for (BasicBlock *BB : this->blocks()) {
539 for (Instruction &I : *BB) {
540 // Token-like values cannot be used in PHI nodes, so cloning is only
541 // possible if all their uses are contained in the loop. Uses within
542 // the loop (even across blocks) are fine: cloning only requires
543 // forming phis for values that are live-out of the loop.
544 if (I.getType()->isTokenLikeTy()) {
545 for (const Use &U : I.uses()) {
546 if (!loopContainsUser(*this, *BB, U, DT))
547 return false;
548 }
549 }
550 if (auto *CB = dyn_cast<CallBase>(&I)) {
551 assert(!CB->cannotDuplicate() && "Checked by isSafeToClone().");
552 if (CB->isConvergent())
553 return false;
554 }
555 }
556 }
557 return true;
558}
559
561 MDNode *LoopID = nullptr;
562
563 // Go through the latch blocks and check the terminator for the metadata.
564 SmallVector<BasicBlock *, 4> LatchesBlocks;
565 getLoopLatches(LatchesBlocks);
566 for (BasicBlock *BB : LatchesBlocks) {
567 Instruction *TI = BB->getTerminator();
568 MDNode *MD = TI->getMetadata(LLVMContext::MD_loop);
569
570 if (!MD)
571 return nullptr;
572
573 if (!LoopID)
574 LoopID = MD;
575 else if (MD != LoopID)
576 return nullptr;
577 }
578 if (!LoopID || LoopID->getNumOperands() == 0 ||
579 LoopID->getOperand(0) != LoopID)
580 return nullptr;
581 return LoopID;
582}
583
584void Loop::setLoopID(MDNode *LoopID) const {
585 assert((!LoopID || LoopID->getNumOperands() > 0) &&
586 "Loop ID needs at least one operand");
587 assert((!LoopID || LoopID->getOperand(0) == LoopID) &&
588 "Loop ID should refer to itself");
589
591 getLoopLatches(LoopLatches);
592 for (BasicBlock *BB : LoopLatches)
593 BB->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID);
594}
595
597 addStringLoopAttribute("llvm.loop.unroll.disable", {"llvm.loop.unroll."});
598}
599
601 if (findOptionMDForLoop(this, "llvm.loop.mustprogress"))
602 return;
603 addStringLoopAttribute("llvm.loop.mustprogress");
604}
605
607 ArrayRef<StringRef> RemovePrefixes) const {
608 LLVMContext &Context = getHeader()->getContext();
609 MDNode *AttrMD = MDNode::get(Context, MDString::get(Context, Name));
610 MDNode *LoopID = getLoopID();
611 MDNode *NewLoopID =
612 makePostTransformationMetadata(Context, LoopID, RemovePrefixes, {AttrMD});
613 setLoopID(NewLoopID);
614}
615
617 ArrayRef<StringRef> RemovePrefixes) const {
618 LLVMContext &Context = getHeader()->getContext();
619 MDNode *AttrMD = MDNode::get(
620 Context,
621 {MDString::get(Context, Name),
622 ConstantAsMetadata::get(ConstantInt::get(Context, APInt(32, Value)))});
623 MDNode *LoopID = getLoopID();
624 MDNode *NewLoopID =
625 makePostTransformationMetadata(Context, LoopID, RemovePrefixes, {AttrMD});
626 setLoopID(NewLoopID);
627}
628
630 MDNode *DesiredLoopIdMetadata = getLoopID();
631
632 if (!DesiredLoopIdMetadata)
633 return false;
634
635 MDNode *ParallelAccesses =
636 findOptionMDForLoop(this, "llvm.loop.parallel_accesses");
638 ParallelAccessGroups; // For scalable 'contains' check.
639 if (ParallelAccesses) {
640 for (const MDOperand &MD : drop_begin(ParallelAccesses->operands())) {
641 MDNode *AccGroup = cast<MDNode>(MD.get());
642 assert(isValidAsAccessGroup(AccGroup) &&
643 "List item must be an access group");
644 ParallelAccessGroups.insert(AccGroup);
645 }
646 }
647
648 // The loop branch contains the parallel loop metadata. In order to ensure
649 // that any parallel-loop-unaware optimization pass hasn't added loop-carried
650 // dependencies (thus converted the loop back to a sequential loop), check
651 // that all the memory instructions in the loop belong to an access group that
652 // is parallel to this loop.
653 for (BasicBlock *BB : this->blocks()) {
654 for (Instruction &I : *BB) {
655 if (!I.mayReadOrWriteMemory())
656 continue;
657
658 if (MDNode *AccessGroup = I.getMetadata(LLVMContext::MD_access_group)) {
659 auto ContainsAccessGroup = [&ParallelAccessGroups](MDNode *AG) -> bool {
660 if (AG->getNumOperands() == 0) {
661 assert(isValidAsAccessGroup(AG) && "Item must be an access group");
662 return ParallelAccessGroups.count(AG);
663 }
664
665 for (const MDOperand &AccessListItem : AG->operands()) {
666 MDNode *AccGroup = cast<MDNode>(AccessListItem.get());
667 assert(isValidAsAccessGroup(AccGroup) &&
668 "List item must be an access group");
669 if (ParallelAccessGroups.count(AccGroup))
670 return true;
671 }
672 return false;
673 };
674
675 if (ContainsAccessGroup(AccessGroup))
676 continue;
677 }
678
679 // The memory instruction can refer to the loop identifier metadata
680 // directly or indirectly through another list metadata (in case of
681 // nested parallel loops). The loop identifier metadata refers to
682 // itself so we can check both cases with the same routine.
683 MDNode *LoopIdMD =
684 I.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
685
686 if (!LoopIdMD)
687 return false;
688
689 if (!llvm::is_contained(LoopIdMD->operands(), DesiredLoopIdMetadata))
690 return false;
691 }
692 }
693 return true;
694}
695
697
699 // If we have a debug location in the loop ID, then use it.
700 if (MDNode *LoopID = getLoopID()) {
701 DebugLoc Start;
702 // We use the first DebugLoc in the header as the start location of the loop
703 // and if there is a second DebugLoc in the header we use it as end location
704 // of the loop.
705 for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
706 if (DILocation *L = dyn_cast<DILocation>(MDO)) {
707 if (!Start)
708 Start = DebugLoc(L);
709 else
710 return LocRange(Start, DebugLoc(L));
711 }
712 }
713
714 if (Start)
715 return LocRange(Start);
716 }
717
718 // Try the pre-header first.
719 if (BasicBlock *PHeadBB = getLoopPreheader())
720 if (DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc())
721 return LocRange(DL);
722
723 // If we have no pre-header or there are no instructions with debug
724 // info in it, try the header.
725 if (BasicBlock *HeadBB = getHeader())
726 return LocRange(HeadBB->getTerminator()->getDebugLoc());
727
728 return LocRange();
729}
730
731std::string Loop::getLocStr() const {
732 std::string Result;
733 raw_string_ostream OS(Result);
734 if (const DebugLoc LoopDbgLoc = getStartLoc())
735 LoopDbgLoc.print(OS);
736 else
737 // Just print the module name.
739 return Result;
740}
741
742#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
744
746 print(dbgs(), /*Verbose=*/true);
747}
748#endif
749
750//===----------------------------------------------------------------------===//
751// UnloopUpdater implementation
752//
753
754namespace {
755/// Find the new parent loop for all blocks within the "unloop" whose last
756/// backedges has just been removed.
757class UnloopUpdater {
758 Loop &Unloop;
759 LoopInfo *LI;
760
761 LoopBlocksDFS DFS;
762
763 // Map unloop's immediate subloops to their nearest reachable parents. Nested
764 // loops within these subloops will not change parents. However, an immediate
765 // subloop's new parent will be the nearest loop reachable from either its own
766 // exits *or* any of its nested loop's exits.
767 DenseMap<Loop *, Loop *> SubloopParents;
768
769 // Flag the presence of an irreducible backedge whose destination is a block
770 // directly contained by the original unloop.
771 bool FoundIB = false;
772
773public:
774 UnloopUpdater(Loop *UL, LoopInfo *LInfo) : Unloop(*UL), LI(LInfo), DFS(UL) {}
775
776 void updateBlockParents();
777
778 void removeBlocksFromAncestors();
779
780 void updateSubloopParents();
781
782protected:
783 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
784};
785} // end anonymous namespace
786
787/// Update the parent loop for all blocks that are directly contained within the
788/// original "unloop".
789void UnloopUpdater::updateBlockParents() {
790 if (Unloop.getNumBlocks()) {
791 // Perform a post order CFG traversal of all blocks within this loop,
792 // propagating the nearest loop from successors to predecessors.
793 LoopBlocksTraversal Traversal(DFS, LI);
794 for (BasicBlock *POI : Traversal) {
795
796 Loop *L = LI->getLoopFor(POI);
797 Loop *NL = getNearestLoop(POI, L);
798
799 if (NL != L) {
800 // For reducible loops, NL is now an ancestor of Unloop.
801 assert((NL != &Unloop && (!NL || NL->contains(&Unloop))) &&
802 "uninitialized successor");
803 LI->changeLoopFor(POI, NL);
804 } else {
805 // Or the current block is part of a subloop, in which case its parent
806 // is unchanged.
807 assert((FoundIB || Unloop.contains(L)) && "uninitialized successor");
808 }
809 }
810 }
811 // Each irreducible loop within the unloop induces a round of iteration using
812 // the DFS result cached by Traversal.
813 bool Changed = FoundIB;
814 for (unsigned NIters = 0; Changed; ++NIters) {
815 assert(NIters < Unloop.getNumBlocks() && "runaway iterative algorithm");
816 (void)NIters;
817
818 // Iterate over the postorder list of blocks, propagating the nearest loop
819 // from successors to predecessors as before.
820 Changed = false;
821 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
822 POE = DFS.endPostorder();
823 POI != POE; ++POI) {
824
825 Loop *L = LI->getLoopFor(*POI);
826 Loop *NL = getNearestLoop(*POI, L);
827 if (NL != L) {
828 assert(NL != &Unloop && (!NL || NL->contains(&Unloop)) &&
829 "uninitialized successor");
830 LI->changeLoopFor(*POI, NL);
831 Changed = true;
832 }
833 }
834 }
835}
836
837/// Remove unloop's blocks from all ancestors below their new parents.
838void UnloopUpdater::removeBlocksFromAncestors() {
839 // Remove all unloop's blocks (including those in nested subloops) from
840 // ancestors below the new parent loop.
841 for (BasicBlock *BB : Unloop.blocks()) {
842 Loop *OuterParent = LI->getLoopFor(BB);
843 if (Unloop.contains(OuterParent)) {
844 while (OuterParent->getParentLoop() != &Unloop)
845 OuterParent = OuterParent->getParentLoop();
846 OuterParent = SubloopParents[OuterParent];
847 }
848 // Remove blocks from former Ancestors except Unloop itself which will be
849 // deleted.
850 for (Loop *OldParent = Unloop.getParentLoop(); OldParent != OuterParent;
851 OldParent = OldParent->getParentLoop()) {
852 assert(OldParent && "new loop is not an ancestor of the original");
853 OldParent->removeBlockFromLoop(BB);
854 }
855 }
856}
857
858/// Update the parent loop for all subloops directly nested within unloop.
859void UnloopUpdater::updateSubloopParents() {
860 while (!Unloop.isInnermost()) {
861 Loop *Subloop = *std::prev(Unloop.end());
862 Unloop.removeChildLoop(std::prev(Unloop.end()));
863
864 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
865 if (Loop *Parent = SubloopParents[Subloop])
866 Parent->addChildLoop(Subloop);
867 else
868 LI->addTopLevelLoop(Subloop);
869 }
870}
871
872/// Return the nearest parent loop among this block's successors. If a successor
873/// is a subloop header, consider its parent to be the nearest parent of the
874/// subloop's exits.
875///
876/// For subloop blocks, simply update SubloopParents and return NULL.
877Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
878
879 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
880 // is considered uninitialized.
881 Loop *NearLoop = BBLoop;
882
883 Loop *Subloop = nullptr;
884 if (NearLoop != &Unloop && Unloop.contains(NearLoop)) {
885 Subloop = NearLoop;
886 // Find the subloop ancestor that is directly contained within Unloop.
887 while (Subloop->getParentLoop() != &Unloop) {
888 Subloop = Subloop->getParentLoop();
889 assert(Subloop && "subloop is not an ancestor of the original loop");
890 }
891 // Get the current nearest parent of the Subloop exits, initially Unloop.
892 NearLoop = SubloopParents.insert({Subloop, &Unloop}).first->second;
893 }
894
895 if (succ_empty(BB)) {
896 assert(!Subloop && "subloop blocks must have a successor");
897 NearLoop = nullptr; // unloop blocks may now exit the function.
898 }
899 for (BasicBlock *Succ : successors(BB)) {
900 if (Succ == BB)
901 continue; // self loops are uninteresting
902
903 Loop *L = LI->getLoopFor(Succ);
904 if (L == &Unloop) {
905 // This successor has not been processed. This path must lead to an
906 // irreducible backedge.
907 assert((FoundIB || !DFS.hasPostorder(Succ)) && "should have seen IB");
908 FoundIB = true;
909 }
910 if (L != &Unloop && Unloop.contains(L)) {
911 // Successor is in a subloop.
912 if (Subloop)
913 continue; // Branching within subloops. Ignore it.
914
915 // BB branches from the original into a subloop header.
916 assert(L->getParentLoop() == &Unloop && "cannot skip into nested loops");
917
918 // Get the current nearest parent of the Subloop's exits.
919 L = SubloopParents[L];
920 // L could be Unloop if the only exit was an irreducible backedge.
921 }
922 if (L == &Unloop) {
923 continue;
924 }
925 // Handle critical edges from Unloop into a sibling loop.
926 if (L && !L->contains(&Unloop)) {
927 L = L->getParentLoop();
928 }
929 // Remember the nearest parent loop among successors or subloop exits.
930 if (NearLoop == &Unloop || !NearLoop || NearLoop->contains(L))
931 NearLoop = L;
932 }
933 if (Subloop) {
934 SubloopParents[Subloop] = NearLoop;
935 return BBLoop;
936 }
937 return NearLoop;
938}
939
940LoopInfo::LoopInfo(const DomTreeBase<BasicBlock> &DomTree) { analyze(DomTree); }
941
943 FunctionAnalysisManager::Invalidator &) {
944 // Check whether the analysis, all analyses on functions, or the function's
945 // CFG have been preserved.
946 auto PAC = PA.getChecker<LoopAnalysis>();
947 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
948 PAC.preservedSet<CFGAnalyses>());
949}
950
951void LoopInfo::erase(Loop *Unloop) {
952 assert(!Unloop->isInvalid() && "Loop has already been erased!");
953
954 llvm::scope_exit InvalidateOnExit([&]() { destroy(Unloop); });
955
956 // First handle the special case of no parent loop to simplify the algorithm.
957 if (Unloop->isOutermost()) {
958 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
959 for (BasicBlock *BB : Unloop->blocks()) {
960 // Don't reparent blocks in subloops.
961 if (getLoopFor(BB) != Unloop)
962 continue;
963
964 // Blocks no longer have a parent but are still referenced by Unloop until
965 // the Unloop object is deleted.
966 changeLoopFor(BB, nullptr);
967 }
968
969 // Remove the loop from the top-level LoopInfo object.
970 for (iterator I = begin();; ++I) {
971 assert(I != end() && "Couldn't find loop");
972 if (*I == Unloop) {
973 removeLoop(I);
974 break;
975 }
976 }
977
978 // Move all of the subloops to the top-level.
979 while (!Unloop->isInnermost())
980 addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
981
982 return;
983 }
984
985 // Update the parent loop for all blocks within the loop. Blocks within
986 // subloops will not change parents.
987 UnloopUpdater Updater(Unloop, this);
988 Updater.updateBlockParents();
989
990 // Remove blocks from former ancestor loops.
991 Updater.removeBlocksFromAncestors();
992
993 // Add direct subloops as children in their new parent loop.
994 Updater.updateSubloopParents();
995
996 // Remove unloop from its parent loop.
997 Loop *ParentLoop = Unloop->getParentLoop();
998 for (Loop::iterator I = ParentLoop->begin();; ++I) {
999 assert(I != ParentLoop->end() && "Couldn't find loop");
1000 if (*I == Unloop) {
1001 ParentLoop->removeChildLoop(I);
1002 break;
1003 }
1004 }
1005}
1006
1008 const Value *V, const BasicBlock *ExitBB) const {
1009 if (V->getType()->isTokenLikeTy())
1010 // We can't form PHIs of token-like type, so the definition of LCSSA
1011 // excludes values of that type.
1012 return false;
1013
1015 if (!I)
1016 return false;
1017 const Loop *L = getLoopFor(I->getParent());
1018 if (!L)
1019 return false;
1020 if (L->contains(ExitBB))
1021 // Could be an exit bb of a subloop and contained in defining loop
1022 return false;
1023
1024 // We found a (new) out-of-loop use location, for a value defined in-loop.
1025 // (Note that because of LCSSA, we don't have to account for values defined
1026 // in sibling loops. Such values will have LCSSA phis of their own in the
1027 // common parent loop.)
1028 return true;
1029}
1030
1031AnalysisKey LoopAnalysis::Key;
1032
1034 // FIXME: Currently we create a LoopInfo from scratch for every function.
1035 // This may prove to be too wasteful due to deallocating and re-allocating
1036 // memory each time for the underlying map and vector datastructures. At some
1037 // point it may prove worthwhile to use a freelist and recycle LoopInfo
1038 // objects. I don't want to add that kind of complexity until the scope of
1039 // the problem is better understood.
1040 LoopInfo LI;
1041 // The dominator tree is needed only for an irreducible CFG.
1042 LI.analyze(&F, [&]() -> const DominatorTree & {
1043 return AM.getResult<DominatorTreeAnalysis>(F);
1044 });
1045 return LI;
1046}
1047
1050 auto &LI = AM.getResult<LoopAnalysis>(F);
1051 OS << "Loop info for function '" << F.getName() << "':\n";
1052 LI.print(OS);
1053 return PreservedAnalyses::all();
1054}
1055
1057 const std::string &Banner) {
1058 if (forcePrintModuleIR()) {
1059 // handling -print-module-scope
1060 OS << Banner << " (loop: ";
1061 L.getHeader()->printAsOperand(OS, false);
1062 OS << ")\n";
1063
1064 // printing whole module
1065 OS << *L.getHeader()->getModule();
1066 return;
1067 }
1068
1069 if (forcePrintFuncIR()) {
1070 // handling -print-loop-func-scope.
1071 // -print-module-scope overrides this.
1072 OS << Banner << " (loop: ";
1073 L.getHeader()->printAsOperand(OS, false);
1074 OS << ")\n";
1075
1076 // printing whole function.
1077 OS << *L.getHeader()->getParent();
1078 return;
1079 }
1080
1081 OS << Banner;
1082
1083 auto *PreHeader = L.getLoopPreheader();
1084 if (PreHeader) {
1085 OS << "\n; Preheader:";
1086 PreHeader->print(OS);
1087 OS << "\n; Loop:";
1088 }
1089
1090 for (auto *Block : L.blocks())
1091 if (Block)
1092 Block->print(OS);
1093 else
1094 OS << "Printing <null> block";
1095
1097 L.getExitBlocks(ExitBlocks);
1098 if (!ExitBlocks.empty()) {
1099 OS << "\n; Exit blocks";
1100 for (auto *Block : ExitBlocks)
1101 if (Block)
1102 Block->print(OS);
1103 else
1104 OS << "Printing <null> block";
1105 }
1106}
1107
1109 // No loop metadata node, no loop properties.
1110 if (!LoopID)
1111 return nullptr;
1112
1113 // First operand should refer to the metadata node itself, for legacy reasons.
1114 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1115 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1116
1117 // Iterate over the metdata node operands and look for MDString metadata.
1118 for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
1119 MDNode *MD = dyn_cast<MDNode>(MDO);
1120 if (!MD || MD->getNumOperands() < 1)
1121 continue;
1123 if (!S)
1124 continue;
1125 // Return the operand node if MDString holds expected metadata.
1126 if (Name == S->getString())
1127 return MD;
1128 }
1129
1130 // Loop property not found.
1131 return nullptr;
1132}
1133
1135 return findOptionMDForLoopID(TheLoop->getLoopID(), Name);
1136}
1137
1138/// Find string metadata for loop
1139///
1140/// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
1141/// operand or null otherwise. If the string metadata is not found return
1142/// Optional's not-a-value.
1143std::optional<const MDOperand *>
1145 MDNode *MD = findOptionMDForLoop(TheLoop, Name);
1146 if (!MD)
1147 return std::nullopt;
1148 switch (MD->getNumOperands()) {
1149 case 1:
1150 return nullptr;
1151 case 2:
1152 return &MD->getOperand(1);
1153 default:
1154 llvm_unreachable("loop metadata has 0 or 1 operand");
1155 }
1156}
1157
1158std::optional<bool> llvm::getOptionalBoolLoopAttribute(const Loop *TheLoop,
1159 StringRef Name) {
1160 MDNode *MD = findOptionMDForLoop(TheLoop, Name);
1161 if (!MD)
1162 return std::nullopt;
1163 switch (MD->getNumOperands()) {
1164 case 1:
1165 // When the value is absent it is interpreted as 'attribute set'.
1166 return true;
1167 case 2:
1168 if (ConstantInt *IntMD =
1170 return IntMD->getZExtValue();
1171 return true;
1172 }
1173 llvm_unreachable("unexpected number of options");
1174}
1175
1177 return getOptionalBoolLoopAttribute(TheLoop, Name).value_or(false);
1178}
1179
1180std::optional<int> llvm::getOptionalIntLoopAttribute(const Loop *TheLoop,
1181 StringRef Name) {
1182 const MDOperand *AttrMD =
1183 findStringMetadataForLoop(TheLoop, Name).value_or(nullptr);
1184 if (!AttrMD)
1185 return std::nullopt;
1186
1187 ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get());
1188 if (!IntMD)
1189 return std::nullopt;
1190
1191 return IntMD->getSExtValue();
1192}
1193
1195 int Default) {
1196 return getOptionalIntLoopAttribute(TheLoop, Name).value_or(Default);
1197}
1198
1200 BasicBlock *H = TheLoop->getHeader();
1201 for (Instruction &II : *H) {
1202 if (auto *CB = dyn_cast<CallBase>(&II)) {
1203 if (!CB->isConvergent())
1204 continue;
1205 // This is the heart if it uses a token defined outside the loop. The
1206 // verifier has already checked that only the loop intrinsic can use such
1207 // a token.
1208 if (auto *Token = CB->getConvergenceControlToken()) {
1209 auto *TokenDef = cast<Instruction>(Token);
1210 if (!TheLoop->contains(TokenDef->getParent()))
1211 return CB;
1212 }
1213 return nullptr;
1214 }
1215 }
1216 return nullptr;
1217}
1218
1219bool llvm::isFinite(const Loop *L) {
1220 return L->getHeader()->getParent()->willReturn();
1221}
1222
1224 // An assumption on L covers every cycle inside it.
1225 if (SE.loopIsFiniteByAssumption(L))
1226 return true;
1227
1228 // An irreducible cycle has no Loop to prove finite.
1229 LoopBlocksRPO RPOT(L);
1230 RPOT.perform(&LI);
1232 return false;
1233
1234 // Likewise, a sub-loop that is finite by assumption covers its own sub-loops.
1236 return false;
1237 SmallVector<Loop *, 8> WorkList(L->begin(), L->end());
1238 while (!WorkList.empty()) {
1239 Loop *Current = WorkList.pop_back_val();
1240 if (SE.loopIsFiniteByAssumption(Current))
1241 continue;
1243 return false;
1244 WorkList.append(Current->begin(), Current->end());
1245 }
1246
1247 return true;
1248}
1249
1250static const char *LLVMLoopMustProgress = "llvm.loop.mustprogress";
1251
1255
1257 return L->getHeader()->getParent()->mustProgress() || hasMustProgress(L);
1258}
1259
1261 return Node->getNumOperands() == 0 && Node->isDistinct();
1262}
1263
1265 MDNode *OrigLoopID,
1266 ArrayRef<StringRef> RemovePrefixes,
1267 ArrayRef<MDNode *> AddAttrs) {
1268 // First remove any existing loop metadata related to this transformation.
1270
1271 // Reserve first location for self reference to the LoopID metadata node.
1272 MDs.push_back(nullptr);
1273
1274 // Remove metadata for the transformation that has been applied or that became
1275 // outdated.
1276 if (OrigLoopID) {
1277 for (const MDOperand &MDO : llvm::drop_begin(OrigLoopID->operands())) {
1278 bool IsVectorMetadata = false;
1279 Metadata *Op = MDO;
1280 if (MDNode *MD = dyn_cast<MDNode>(Op)) {
1281 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1282 if (S)
1283 IsVectorMetadata =
1284 llvm::any_of(RemovePrefixes, [S](StringRef Prefix) -> bool {
1285 return S->getString().starts_with(Prefix);
1286 });
1287 }
1288 if (!IsVectorMetadata)
1289 MDs.push_back(Op);
1290 }
1291 }
1292
1293 // Add metadata to avoid reapplying a transformation, such as
1294 // llvm.loop.unroll.disable and llvm.loop.isvectorized.
1295 MDs.append(AddAttrs.begin(), AddAttrs.end());
1296
1297 MDNode *NewLoopID = MDNode::getDistinct(Context, MDs);
1298 // Replace the temporary node with a self-reference.
1299 NewLoopID->replaceOperandWith(0, NewLoopID);
1300 return NewLoopID;
1301}
1302
1303//===----------------------------------------------------------------------===//
1304// LoopInfo implementation
1305//
1306
1308
1310INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
1311 true, true)
1313INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
1315
1317 releaseMemory();
1319 return false;
1320}
1321
1323 // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
1324 // function each time verifyAnalysis is called is very expensive. The
1325 // -verify-loop-info option can enable this. In order to perform some
1326 // checking by default, LoopPass has been taught to call verifyLoop manually
1327 // during loop pass sequences.
1328 if (VerifyLoopInfo)
1329 LI.verify();
1330}
1331
1336
1338 LI.print(OS);
1339}
1340
1347
1348//===----------------------------------------------------------------------===//
1349// LoopBlocksDFS implementation
1350//
1351
1352/// Traverse the loop blocks and store the DFS result.
1353/// Useful for clients that just want the final DFS result and don't need to
1354/// visit blocks during the initial traversal.
1356 LoopBlocksTraversal Traversal(*this, LI);
1357 for ([[maybe_unused]] BasicBlock *BB : Traversal)
1358 ;
1359}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:682
#define LLVM_EXPORT_TEMPLATE
Definition Compiler.h:213
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
static bool isBlockInLCSSAForm(const Loop &L, const BasicBlock &BB, const DominatorTree &DT, bool IgnoreTokens)
Definition LoopInfo.cpp:478
static bool loopContainsUser(const Loop &L, const BasicBlock &BB, const Use &U, const DominatorTree &DT)
Definition LoopInfo.cpp:456
static const char * LLVMLoopMustProgress
static Value * findFinalIVValue(const Loop &L, const PHINode &IndVar, const Instruction &StepInst)
Return the final value of the loop induction variable if found.
Definition LoopInfo.cpp:208
Loop::LoopBounds::Direction Direction
Definition LoopInfo.cpp:254
static cl::opt< bool, true > VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo), cl::Hidden, cl::desc("Verify loop info (time consuming)"))
This file defines the interface for the loop nest analysis.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define H(x, y, z)
Definition MD5.cpp:56
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
This file contains the declarations for metadata subclasses.
uint64_t IntrinsicInst * II
#define P(N)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file contains the declarations for profiling metadata utility functions.
static DominatorTree getDomTree(Function &F)
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallPtrSet class.
Class for arbitrary precision integers.
Definition APInt.h:78
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
AnalysisUsage & addRequiredTransitive()
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
iterator begin() const
Definition ArrayRef.h:129
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_NE
not equal
Definition InstrTypes.h:762
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
Predicate getFlippedStrictnessPredicate() const
For predicate of kind "is X or equal to 0" returns the predicate "is X".
Definition InstrTypes.h:956
Conditional Branch instruction.
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:548
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition Constants.h:225
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition Constants.h:174
A debug info location.
Definition DebugLoc.h:126
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
void print(raw_ostream &OS, const Module *M=nullptr) const override
print - Print out the internal state of the pass.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
FunctionPass(char &pid)
Definition Pass.h:314
Module * getParent()
Get the module that this global value is contained inside of...
This instruction compares its operands according to the predicate given to the constructor.
A struct for saving information about induction variables.
BinaryOperator * getInductionBinOp() const
const SCEV * getStep() const
static LLVM_ABI bool isInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, InductionDescriptor &D, ArrayRef< const SCEVPredicate * > NoWrapPreds={}, const SCEV *Expr=nullptr, SmallVectorImpl< Instruction * > *CastsToIgnore=nullptr)
Returns true if Phi is an induction in the loop L.
Instruction::BinaryOps getInductionOpcode() const
Returns binary opcode of the induction operator.
Value * getStartValue() const
LLVM_ABI ConstantInt * getConstIntStepValue() const
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
iterator_range< user_iterator > users()
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
LLVM_ABI LoopInfo run(Function &F, FunctionAnalysisManager &AM)
Instances of this class are used to represent loops that are detected in the flow graph.
bool contains(const Loop *L) const
typename std::vector< Loop * >::const_iterator iterator
bool isOutermost() const
Return true if the loop does not have a parent (natural) loop.
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
void getLoopLatches(SmallVectorImpl< BasicBlock * > &LoopLatches) const
void print(raw_ostream &OS, bool Verbose=false, bool PrintNested=true, unsigned Depth=0) const
iterator_range< block_iterator > blocks() const
bool isInvalid() const
Return true if this loop is no longer valid.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
Store the result of a depth first search within basic blocks contained by a single loop.
friend class LoopBlocksTraversal
std::vector< BasicBlock * >::const_iterator POIterator
Postorder list iterators.
LLVM_ABI void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
Wrapper class to LoopBlocksDFS that provides a standard begin()/end() interface for the DFS reverse p...
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
This class builds and contains all of the top-level loop structures in the specified function.
typename std::vector< Loop * >::const_iterator iterator
void analyze(ParentT F)
Create the loop forest for a function.
Loop * getLoopFor(const BasicBlock *BB) const
void changeLoopFor(const BasicBlock *BB, Loop *L)
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:619
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
Definition LoopInfo.h:635
bool runOnFunction(Function &F) override
Calculate the natural loop information for a given function.
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
void print(raw_ostream &O, const Module *M=nullptr) const override
print - Print out the internal state of the pass.
LoopInfo()=default
LLVM_ABI bool wouldBeOutOfLoopUseRequiringLCSSA(const Value *V, const BasicBlock *ExitBB) const
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &)
Handle invalidation explicitly.
Definition LoopInfo.cpp:942
LLVM_ABI void erase(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
Definition LoopInfo.cpp:951
static const BasicBlock & skipEmptyBlockUntil(const BasicBlock *From, const BasicBlock *End, bool CheckUniquePred=false)
Recursivelly traverse all empty 'single successor' basic blocks of From (if there are any).
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
A range representing the start and end location of a loop.
Definition LoopInfo.h:43
const DebugLoc & getStart() const
Definition LoopInfo.h:53
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
bool isCanonical(ScalarEvolution &SE) const
Return true if the loop induction variable starts at zero and increments by one each time through the...
Definition LoopInfo.cpp:434
bool isLCSSAForm(const DominatorTree &DT, bool IgnoreTokens=true) const
Return true if the Loop is in LCSSA form.
Definition LoopInfo.cpp:495
std::optional< LoopBounds > getBounds(ScalarEvolution &SE) const
Return the struct LoopBounds collected if all struct members are found, else std::nullopt.
Definition LoopInfo.cpp:310
bool isSafeToClone() const
Return true if the loop body is safe to clone in practice.
Definition LoopInfo.cpp:519
std::string getLocStr() const
Return a string containing the debug location of the loop (file name + line number if present,...
Definition LoopInfo.cpp:731
void dumpVerbose() const
Definition LoopInfo.cpp:745
bool hasLoopInvariantOperands(const Instruction *I) const
Return true if all the operands of the specified instruction are loop invariant.
Definition LoopInfo.cpp:74
bool isAnnotatedParallel() const
Returns true if the loop is annotated parallel.
Definition LoopInfo.cpp:629
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
Definition LoopInfo.cpp:696
void dump() const
Definition LoopInfo.cpp:743
LocRange getLocRange() const
Return the source code span of the loop.
Definition LoopInfo.cpp:698
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:68
ICmpInst * getLatchCmpInst() const
Get the latch condition instruction.
Definition LoopInfo.cpp:199
bool isSafeToCloneConditionally(const DominatorTree &DT) const
Like isSafeToClone, but for transformations where the cloned loop bodies may run conditionally.
Definition LoopInfo.cpp:534
bool getInductionDescriptor(ScalarEvolution &SE, InductionDescriptor &IndDesc) const
Get the loop induction descriptor for the loop induction variable.
Definition LoopInfo.cpp:356
CondBrInst * getLoopGuardBranch() const
Return the loop guard branch, if it exists.
Definition LoopInfo.cpp:390
void addIntLoopAttribute(StringRef Name, unsigned Value, ArrayRef< StringRef > RemovePrefixes={}) const
Add an integer metadata attribute to this loop's loop-ID node.
Definition LoopInfo.cpp:616
bool isRotatedForm() const
Return true if the loop is in rotated form.
Definition LoopInfo.h:303
void setLoopMustProgress()
Add llvm.loop.mustprogress to this loop's loop id metadata.
Definition LoopInfo.cpp:600
PHINode * getInductionVariable(ScalarEvolution &SE) const
Return the loop induction variable if found, else return nullptr.
Definition LoopInfo.cpp:317
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to,...
Definition LoopInfo.cpp:512
void addStringLoopAttribute(StringRef Name, ArrayRef< StringRef > RemovePrefixes={}) const
Add a string-only metadata attribute to this loop's loop-ID node.
Definition LoopInfo.cpp:606
bool isRecursivelyLCSSAForm(const DominatorTree &DT, const LoopInfo &LI, bool IgnoreTokens=true) const
Return true if this Loop and all inner subloops are in LCSSA form.
Definition LoopInfo.cpp:502
void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
Definition LoopInfo.cpp:584
void setLoopAlreadyUnrolled()
Add llvm.loop.unroll.disable to this loop's loop id metadata.
Definition LoopInfo.cpp:596
bool makeLoopInvariant(Value *V, bool &Changed, Instruction *InsertPt=nullptr, MemorySSAUpdater *MSSAU=nullptr, ScalarEvolution *SE=nullptr) const
If the given value is an instruction inside of the loop and it can be hoisted, do so to make it trivi...
Definition LoopInfo.cpp:78
PHINode * getCanonicalInductionVariable() const
Check to see if the loop has a canonical induction variable: an integer recurrence that starts at 0 a...
Definition LoopInfo.cpp:175
bool getIncomingAndBackEdge(BasicBlock *&Incoming, BasicBlock *&Backedge) const
Obtain the unique incoming and back edge.
Definition LoopInfo.cpp:149
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
Definition LoopInfo.cpp:560
bool isAuxiliaryInductionVariable(PHINode &AuxIndVar, ScalarEvolution &SE) const
Return true if the given PHINode AuxIndVar is.
Definition LoopInfo.cpp:364
Metadata node.
Definition Metadata.h:1081
LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1587
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1435
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1443
Tracking metadata reference owned by Metadata.
Definition Metadata.h:902
Metadata * get() const
Definition Metadata.h:931
A single uniqued string.
Definition Metadata.h:733
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:615
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:597
MemorySSA * getMemorySSA() const
Get handle on MemorySSA.
LLVM_ABI void moveToPlace(MemoryUseOrDef *What, BasicBlock *BB, MemorySSA::InsertionPlace Where)
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
Definition MemorySSA.h:720
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition Module.h:299
Value * getIncomingValueForBlock(const BasicBlock *BB) const
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
This node represents a polynomial recurrence on the trip count of the specified loop.
This class represents an analyzed expression in the program.
The main scalar evolution driver.
const SCEV * getConstantMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
LLVM_ABI bool loopIsFiniteByAssumption(const Loop *L)
Return true if this loop is finite by assumption.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LocationClass< Ty > location(Ty &L)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
Definition Metadata.h:694
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
Definition LoopInfo.cpp:61
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name)
Returns true if Name is applied to TheLoop and enabled.
bool succ_empty(const Instruction *I)
Definition CFG.h:141
LLVM_ABI bool forcePrintModuleIR()
LLVM_ABI std::optional< bool > getOptionalBoolLoopAttribute(const Loop *TheLoop, StringRef Name)
LLVM_ABI int getIntLoopAttribute(const Loop *TheLoop, StringRef Name, int Default=0)
Find named metadata for a loop with an integer value.
auto pred_end(const MachineBasicBlock *BB)
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI std::optional< const MDOperand * > findStringMetadataForLoop(const Loop *TheLoop, StringRef Name)
Find string metadata for loop.
auto successors(const MachineBasicBlock *BB)
LLVM_ABI MDNode * findOptionMDForLoop(const Loop *TheLoop, StringRef Name)
Find string metadata for a loop.
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM_ABI bool hasMustProgress(const Loop *L)
Look for the loop attribute that requires progress within the loop.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
bool containsIrreducibleCFG(RPOTraversalT &RPOTraversal, const LoopInfoT &LI)
Return true if the control flow in RPOTraversal is irreducible.
Definition CFG.h:154
LLVM_ABI bool isMustProgress(const Loop *L)
Return true if this loop can be assumed to make progress.
LLVM_ABI CallBase * getLoopConvergenceHeart(const Loop *TheLoop)
Find the convergence heart of the loop.
LLVM_ABI bool isFinite(const Loop *L)
Return true if this loop can be assumed to run for a finite number of iterations.
DominatorTreeBase< T, false > DomTreeBase
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI bool VerifyLoopInfo
Enable verification of loop info.
Definition LoopInfo.cpp:54
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool isLoopNestFinite(Loop *L, ScalarEvolution &SE, const LoopInfo &LI)
Return true if every cycle in the loop nest rooted at L is finite.
LLVM_ABI std::optional< int > getOptionalIntLoopAttribute(const Loop *TheLoop, StringRef Name)
Find named metadata for a loop with an integer value.
LLVM_ABI bool isValidAsAccessGroup(MDNode *AccGroup)
Return whether an MDNode might represent an access group.
LLVM_ABI void printLoop(const Loop &L, raw_ostream &OS, const std::string &Banner="")
Function to print a loop's contents as LLVM's text IR assembly.
DWARFExpression::Operation Op
PredIterator< BasicBlock, Value::user_iterator > pred_iterator
Definition CFG.h:93
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI llvm::MDNode * makePostTransformationMetadata(llvm::LLVMContext &Context, MDNode *OrigLoopID, llvm::ArrayRef< llvm::StringRef > RemovePrefixes, llvm::ArrayRef< llvm::MDNode * > AddAttrs)
Create a new LoopID after the loop has been transformed.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI MDNode * findOptionMDForLoopID(MDNode *LoopID, StringRef Name)
Find and return the loop attribute node for the attribute Name in LoopID.
LLVM_ABI bool forcePrintFuncIR()
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
static LLVM_ABI std::optional< Loop::LoopBounds > getBounds(const Loop &L, PHINode &IndVar, ScalarEvolution &SE)
Return the LoopBounds object if.
Definition LoopInfo.cpp:226
Direction
An enum for the direction of the loop.
Definition LoopInfo.h:216
Value & getFinalIVValue() const
Get the final value of the loop induction variable.
Definition LoopInfo.h:175
Instruction & getStepInst() const
Get the instruction that updates the loop induction variable.
Definition LoopInfo.h:168
LLVM_ABI ICmpInst::Predicate getCanonicalPredicate() const
Return the canonical predicate for the latch compare instruction, if able to be calcuated.
Definition LoopInfo.cpp:256
LLVM_ABI Direction getDirection() const
Get the direction of the loop.
Definition LoopInfo.cpp:297