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<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 CondBrInst *GuardBI = dyn_cast<CondBrInst>(GuardBB->getTerminator());
413 if (!GuardBI)
414 return nullptr;
415
416 BasicBlock *GuardOtherSucc = (GuardBI->getSuccessor(0) == Preheader)
417 ? GuardBI->getSuccessor(1)
418 : GuardBI->getSuccessor(0);
419
420 // Check if ExitFromLatch (or any BasicBlock which is an empty unique
421 // successor of ExitFromLatch) is equal to GuardOtherSucc. If
422 // skipEmptyBlockUntil returns GuardOtherSucc, then the guard branch for the
423 // loop is GuardBI (return GuardBI), otherwise return nullptr.
424 if (&LoopNest::skipEmptyBlockUntil(ExitFromLatch, GuardOtherSucc,
425 /*CheckUniquePred=*/true) ==
426 GuardOtherSucc)
427 return GuardBI;
428 else
429 return nullptr;
430}
431
433 InductionDescriptor IndDesc;
434 if (!getInductionDescriptor(SE, IndDesc))
435 return false;
436
438 if (!Init || !Init->isZero())
439 return false;
440
441 if (IndDesc.getInductionOpcode() != Instruction::Add)
442 return false;
443
444 std::optional<APInt> Step = IndDesc.getConstStepValue();
445 if (!Step || !Step->isOne())
446 return false;
447
448 return true;
449}
450
451// Check whether the use \p U of a value defined in block \p BB (which is part
452// of loop \p L) does not require a live-out phi, i.e. whether it is contained
453// in the loop for LCSSA purposes.
454static bool loopContainsUser(const Loop &L, const BasicBlock &BB, const Use &U,
455 const DominatorTree &DT) {
456 const Instruction *UI = cast<Instruction>(U.getUser());
457 const BasicBlock *UserBB = UI->getParent();
458
459 // For practical purposes, we consider that the use in a PHI
460 // occurs in the respective predecessor block. For more info,
461 // see the `phi` doc in LangRef and the LCSSA doc.
462 if (const PHINode *P = dyn_cast<PHINode>(UI))
463 UserBB = P->getIncomingBlock(U);
464
465 // Check the current block, as a fast-path, before checking whether
466 // the use is anywhere in the loop. Most values are used in the same
467 // block they are defined in. Also, blocks not reachable from the
468 // entry are special; uses in them don't need to go through PHIs.
469 if (UserBB != &BB && !L.contains(UserBB) && DT.isReachableFromEntry(UserBB))
470 return false;
471
472 return true;
473}
474
475// Check that 'BB' doesn't have any uses outside of the 'L'
476static bool isBlockInLCSSAForm(const Loop &L, const BasicBlock &BB,
477 const DominatorTree &DT, bool IgnoreTokens) {
478 for (const Instruction &I : BB) {
479 // Token-like values can't be used in PHI nodes and live-out token-like
480 // values prevent loop optimizations, so for the purposes of considered
481 // LCSSA form, we can ignore them.
482 if (IgnoreTokens && I.getType()->isTokenLikeTy())
483 continue;
484
485 for (const Use &U : I.uses()) {
486 if (!loopContainsUser(L, BB, U, DT))
487 return false;
488 }
489 }
490 return true;
491}
492
493bool Loop::isLCSSAForm(const DominatorTree &DT, bool IgnoreTokens) const {
494 // For each block we check that it doesn't have any uses outside of this loop.
495 return all_of(this->blocks(), [&](const BasicBlock *BB) {
496 return isBlockInLCSSAForm(*this, *BB, DT, IgnoreTokens);
497 });
498}
499
501 bool IgnoreTokens) const {
502 // For each block we check that it doesn't have any uses outside of its
503 // innermost loop. This process will transitively guarantee that the current
504 // loop and all of the nested loops are in LCSSA form.
505 return all_of(this->blocks(), [&](const BasicBlock *BB) {
506 return isBlockInLCSSAForm(*LI.getLoopFor(BB), *BB, DT, IgnoreTokens);
507 });
508}
509
511 // Normal-form loops have a preheader, a single backedge, and all of their
512 // exits have all their predecessors inside the loop.
514}
515
516// Routines that reform the loop CFG and split edges often fail on indirectbr.
518 // Return false if any loop blocks contain indirectbrs, or there are any calls
519 // to noduplicate functions.
520 for (BasicBlock *BB : this->blocks()) {
521 if (isa<IndirectBrInst>(BB->getTerminator()))
522 return false;
523
524 for (Instruction &I : *BB)
525 if (auto *CB = dyn_cast<CallBase>(&I))
526 if (CB->cannotDuplicate())
527 return false;
528 }
529 return true;
530}
531
533 if (!isSafeToClone())
534 return false;
535
536 for (BasicBlock *BB : this->blocks()) {
537 for (Instruction &I : *BB) {
538 // Token-like values cannot be used in PHI nodes, so cloning is only
539 // possible if all their uses are contained in the loop. Uses within
540 // the loop (even across blocks) are fine: cloning only requires
541 // forming phis for values that are live-out of the loop.
542 if (I.getType()->isTokenLikeTy()) {
543 for (const Use &U : I.uses()) {
544 if (!loopContainsUser(*this, *BB, U, DT))
545 return false;
546 }
547 }
548 if (auto *CB = dyn_cast<CallBase>(&I)) {
549 assert(!CB->cannotDuplicate() && "Checked by isSafeToClone().");
550 if (CB->isConvergent())
551 return false;
552 }
553 }
554 }
555 return true;
556}
557
559 MDNode *LoopID = nullptr;
560
561 // Go through the latch blocks and check the terminator for the metadata.
562 SmallVector<BasicBlock *, 4> LatchesBlocks;
563 getLoopLatches(LatchesBlocks);
564 for (BasicBlock *BB : LatchesBlocks) {
565 Instruction *TI = BB->getTerminator();
566 MDNode *MD = TI->getMetadata(LLVMContext::MD_loop);
567
568 if (!MD)
569 return nullptr;
570
571 if (!LoopID)
572 LoopID = MD;
573 else if (MD != LoopID)
574 return nullptr;
575 }
576 if (!LoopID || LoopID->getNumOperands() == 0 ||
577 LoopID->getOperand(0) != LoopID)
578 return nullptr;
579 return LoopID;
580}
581
582void Loop::setLoopID(MDNode *LoopID) const {
583 assert((!LoopID || LoopID->getNumOperands() > 0) &&
584 "Loop ID needs at least one operand");
585 assert((!LoopID || LoopID->getOperand(0) == LoopID) &&
586 "Loop ID should refer to itself");
587
589 getLoopLatches(LoopLatches);
590 for (BasicBlock *BB : LoopLatches)
591 BB->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID);
592}
593
595 addStringLoopAttribute("llvm.loop.unroll.disable", {"llvm.loop.unroll."});
596}
597
599 if (findOptionMDForLoop(this, "llvm.loop.mustprogress"))
600 return;
601 addStringLoopAttribute("llvm.loop.mustprogress");
602}
603
605 ArrayRef<StringRef> RemovePrefixes) const {
606 LLVMContext &Context = getHeader()->getContext();
607 MDNode *AttrMD = MDNode::get(Context, MDString::get(Context, Name));
608 MDNode *LoopID = getLoopID();
609 MDNode *NewLoopID =
610 makePostTransformationMetadata(Context, LoopID, RemovePrefixes, {AttrMD});
611 setLoopID(NewLoopID);
612}
613
615 ArrayRef<StringRef> RemovePrefixes) const {
616 LLVMContext &Context = getHeader()->getContext();
617 MDNode *AttrMD = MDNode::get(
618 Context,
619 {MDString::get(Context, Name),
620 ConstantAsMetadata::get(ConstantInt::get(Context, APInt(32, Value)))});
621 MDNode *LoopID = getLoopID();
622 MDNode *NewLoopID =
623 makePostTransformationMetadata(Context, LoopID, RemovePrefixes, {AttrMD});
624 setLoopID(NewLoopID);
625}
626
628 MDNode *DesiredLoopIdMetadata = getLoopID();
629
630 if (!DesiredLoopIdMetadata)
631 return false;
632
633 MDNode *ParallelAccesses =
634 findOptionMDForLoop(this, "llvm.loop.parallel_accesses");
636 ParallelAccessGroups; // For scalable 'contains' check.
637 if (ParallelAccesses) {
638 for (const MDOperand &MD : drop_begin(ParallelAccesses->operands())) {
639 MDNode *AccGroup = cast<MDNode>(MD.get());
640 assert(isValidAsAccessGroup(AccGroup) &&
641 "List item must be an access group");
642 ParallelAccessGroups.insert(AccGroup);
643 }
644 }
645
646 // The loop branch contains the parallel loop metadata. In order to ensure
647 // that any parallel-loop-unaware optimization pass hasn't added loop-carried
648 // dependencies (thus converted the loop back to a sequential loop), check
649 // that all the memory instructions in the loop belong to an access group that
650 // is parallel to this loop.
651 for (BasicBlock *BB : this->blocks()) {
652 for (Instruction &I : *BB) {
653 if (!I.mayReadOrWriteMemory())
654 continue;
655
656 if (MDNode *AccessGroup = I.getMetadata(LLVMContext::MD_access_group)) {
657 auto ContainsAccessGroup = [&ParallelAccessGroups](MDNode *AG) -> bool {
658 if (AG->getNumOperands() == 0) {
659 assert(isValidAsAccessGroup(AG) && "Item must be an access group");
660 return ParallelAccessGroups.count(AG);
661 }
662
663 for (const MDOperand &AccessListItem : AG->operands()) {
664 MDNode *AccGroup = cast<MDNode>(AccessListItem.get());
665 assert(isValidAsAccessGroup(AccGroup) &&
666 "List item must be an access group");
667 if (ParallelAccessGroups.count(AccGroup))
668 return true;
669 }
670 return false;
671 };
672
673 if (ContainsAccessGroup(AccessGroup))
674 continue;
675 }
676
677 // The memory instruction can refer to the loop identifier metadata
678 // directly or indirectly through another list metadata (in case of
679 // nested parallel loops). The loop identifier metadata refers to
680 // itself so we can check both cases with the same routine.
681 MDNode *LoopIdMD =
682 I.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
683
684 if (!LoopIdMD)
685 return false;
686
687 if (!llvm::is_contained(LoopIdMD->operands(), DesiredLoopIdMetadata))
688 return false;
689 }
690 }
691 return true;
692}
693
695
697 // If we have a debug location in the loop ID, then use it.
698 if (MDNode *LoopID = getLoopID()) {
699 DebugLoc Start;
700 // We use the first DebugLoc in the header as the start location of the loop
701 // and if there is a second DebugLoc in the header we use it as end location
702 // of the loop.
703 for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
704 if (DILocation *L = dyn_cast<DILocation>(MDO)) {
705 if (!Start)
706 Start = DebugLoc(L);
707 else
708 return LocRange(Start, DebugLoc(L));
709 }
710 }
711
712 if (Start)
713 return LocRange(Start);
714 }
715
716 // Try the pre-header first.
717 if (BasicBlock *PHeadBB = getLoopPreheader())
718 if (DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc())
719 return LocRange(DL);
720
721 // If we have no pre-header or there are no instructions with debug
722 // info in it, try the header.
723 if (BasicBlock *HeadBB = getHeader())
724 return LocRange(HeadBB->getTerminator()->getDebugLoc());
725
726 return LocRange();
727}
728
729std::string Loop::getLocStr() const {
730 std::string Result;
731 raw_string_ostream OS(Result);
732 if (const DebugLoc LoopDbgLoc = getStartLoc())
733 LoopDbgLoc.print(OS);
734 else
735 // Just print the module name.
737 return Result;
738}
739
740#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
742
744 print(dbgs(), /*Verbose=*/true);
745}
746#endif
747
748//===----------------------------------------------------------------------===//
749// UnloopUpdater implementation
750//
751
752namespace {
753/// Find the new parent loop for all blocks within the "unloop" whose last
754/// backedges has just been removed.
755class UnloopUpdater {
756 Loop &Unloop;
757 LoopInfo *LI;
758
759 LoopBlocksDFS DFS;
760
761 // Map unloop's immediate subloops to their nearest reachable parents. Nested
762 // loops within these subloops will not change parents. However, an immediate
763 // subloop's new parent will be the nearest loop reachable from either its own
764 // exits *or* any of its nested loop's exits.
765 DenseMap<Loop *, Loop *> SubloopParents;
766
767 // Flag the presence of an irreducible backedge whose destination is a block
768 // directly contained by the original unloop.
769 bool FoundIB = false;
770
771public:
772 UnloopUpdater(Loop *UL, LoopInfo *LInfo) : Unloop(*UL), LI(LInfo), DFS(UL) {}
773
774 void updateBlockParents();
775
776 void removeBlocksFromAncestors();
777
778 void updateSubloopParents();
779
780protected:
781 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
782};
783} // end anonymous namespace
784
785/// Update the parent loop for all blocks that are directly contained within the
786/// original "unloop".
787void UnloopUpdater::updateBlockParents() {
788 if (Unloop.getNumBlocks()) {
789 // Perform a post order CFG traversal of all blocks within this loop,
790 // propagating the nearest loop from successors to predecessors.
791 LoopBlocksTraversal Traversal(DFS, LI);
792 for (BasicBlock *POI : Traversal) {
793
794 Loop *L = LI->getLoopFor(POI);
795 Loop *NL = getNearestLoop(POI, L);
796
797 if (NL != L) {
798 // For reducible loops, NL is now an ancestor of Unloop.
799 assert((NL != &Unloop && (!NL || NL->contains(&Unloop))) &&
800 "uninitialized successor");
801 LI->changeLoopFor(POI, NL);
802 } else {
803 // Or the current block is part of a subloop, in which case its parent
804 // is unchanged.
805 assert((FoundIB || Unloop.contains(L)) && "uninitialized successor");
806 }
807 }
808 }
809 // Each irreducible loop within the unloop induces a round of iteration using
810 // the DFS result cached by Traversal.
811 bool Changed = FoundIB;
812 for (unsigned NIters = 0; Changed; ++NIters) {
813 assert(NIters < Unloop.getNumBlocks() && "runaway iterative algorithm");
814 (void)NIters;
815
816 // Iterate over the postorder list of blocks, propagating the nearest loop
817 // from successors to predecessors as before.
818 Changed = false;
819 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
820 POE = DFS.endPostorder();
821 POI != POE; ++POI) {
822
823 Loop *L = LI->getLoopFor(*POI);
824 Loop *NL = getNearestLoop(*POI, L);
825 if (NL != L) {
826 assert(NL != &Unloop && (!NL || NL->contains(&Unloop)) &&
827 "uninitialized successor");
828 LI->changeLoopFor(*POI, NL);
829 Changed = true;
830 }
831 }
832 }
833}
834
835/// Remove unloop's blocks from all ancestors below their new parents.
836void UnloopUpdater::removeBlocksFromAncestors() {
837 // Remove all unloop's blocks (including those in nested subloops) from
838 // ancestors below the new parent loop.
839 for (BasicBlock *BB : Unloop.blocks()) {
840 Loop *OuterParent = LI->getLoopFor(BB);
841 if (Unloop.contains(OuterParent)) {
842 while (OuterParent->getParentLoop() != &Unloop)
843 OuterParent = OuterParent->getParentLoop();
844 OuterParent = SubloopParents[OuterParent];
845 }
846 // Remove blocks from former Ancestors except Unloop itself which will be
847 // deleted.
848 for (Loop *OldParent = Unloop.getParentLoop(); OldParent != OuterParent;
849 OldParent = OldParent->getParentLoop()) {
850 assert(OldParent && "new loop is not an ancestor of the original");
851 OldParent->removeBlockFromLoop(BB);
852 }
853 }
854}
855
856/// Update the parent loop for all subloops directly nested within unloop.
857void UnloopUpdater::updateSubloopParents() {
858 while (!Unloop.isInnermost()) {
859 Loop *Subloop = *std::prev(Unloop.end());
860 Unloop.removeChildLoop(std::prev(Unloop.end()));
861
862 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
863 if (Loop *Parent = SubloopParents[Subloop])
864 Parent->addChildLoop(Subloop);
865 else
866 LI->addTopLevelLoop(Subloop);
867 }
868}
869
870/// Return the nearest parent loop among this block's successors. If a successor
871/// is a subloop header, consider its parent to be the nearest parent of the
872/// subloop's exits.
873///
874/// For subloop blocks, simply update SubloopParents and return NULL.
875Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
876
877 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
878 // is considered uninitialized.
879 Loop *NearLoop = BBLoop;
880
881 Loop *Subloop = nullptr;
882 if (NearLoop != &Unloop && Unloop.contains(NearLoop)) {
883 Subloop = NearLoop;
884 // Find the subloop ancestor that is directly contained within Unloop.
885 while (Subloop->getParentLoop() != &Unloop) {
886 Subloop = Subloop->getParentLoop();
887 assert(Subloop && "subloop is not an ancestor of the original loop");
888 }
889 // Get the current nearest parent of the Subloop exits, initially Unloop.
890 NearLoop = SubloopParents.insert({Subloop, &Unloop}).first->second;
891 }
892
893 if (succ_empty(BB)) {
894 assert(!Subloop && "subloop blocks must have a successor");
895 NearLoop = nullptr; // unloop blocks may now exit the function.
896 }
897 for (BasicBlock *Succ : successors(BB)) {
898 if (Succ == BB)
899 continue; // self loops are uninteresting
900
901 Loop *L = LI->getLoopFor(Succ);
902 if (L == &Unloop) {
903 // This successor has not been processed. This path must lead to an
904 // irreducible backedge.
905 assert((FoundIB || !DFS.hasPostorder(Succ)) && "should have seen IB");
906 FoundIB = true;
907 }
908 if (L != &Unloop && Unloop.contains(L)) {
909 // Successor is in a subloop.
910 if (Subloop)
911 continue; // Branching within subloops. Ignore it.
912
913 // BB branches from the original into a subloop header.
914 assert(L->getParentLoop() == &Unloop && "cannot skip into nested loops");
915
916 // Get the current nearest parent of the Subloop's exits.
917 L = SubloopParents[L];
918 // L could be Unloop if the only exit was an irreducible backedge.
919 }
920 if (L == &Unloop) {
921 continue;
922 }
923 // Handle critical edges from Unloop into a sibling loop.
924 if (L && !L->contains(&Unloop)) {
925 L = L->getParentLoop();
926 }
927 // Remember the nearest parent loop among successors or subloop exits.
928 if (NearLoop == &Unloop || !NearLoop || NearLoop->contains(L))
929 NearLoop = L;
930 }
931 if (Subloop) {
932 SubloopParents[Subloop] = NearLoop;
933 return BBLoop;
934 }
935 return NearLoop;
936}
937
938LoopInfo::LoopInfo(const DomTreeBase<BasicBlock> &DomTree) { analyze(DomTree); }
939
941 FunctionAnalysisManager::Invalidator &) {
942 // Check whether the analysis, all analyses on functions, or the function's
943 // CFG have been preserved.
944 auto PAC = PA.getChecker<LoopAnalysis>();
945 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
946 PAC.preservedSet<CFGAnalyses>());
947}
948
949void LoopInfo::erase(Loop *Unloop) {
950 assert(!Unloop->isInvalid() && "Loop has already been erased!");
951
952 llvm::scope_exit InvalidateOnExit([&]() { destroy(Unloop); });
953
954 // First handle the special case of no parent loop to simplify the algorithm.
955 if (Unloop->isOutermost()) {
956 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
957 for (BasicBlock *BB : Unloop->blocks()) {
958 // Don't reparent blocks in subloops.
959 if (getLoopFor(BB) != Unloop)
960 continue;
961
962 // Blocks no longer have a parent but are still referenced by Unloop until
963 // the Unloop object is deleted.
964 changeLoopFor(BB, nullptr);
965 }
966
967 // Remove the loop from the top-level LoopInfo object.
968 for (iterator I = begin();; ++I) {
969 assert(I != end() && "Couldn't find loop");
970 if (*I == Unloop) {
971 removeLoop(I);
972 break;
973 }
974 }
975
976 // Move all of the subloops to the top-level.
977 while (!Unloop->isInnermost())
978 addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
979
980 return;
981 }
982
983 // Update the parent loop for all blocks within the loop. Blocks within
984 // subloops will not change parents.
985 UnloopUpdater Updater(Unloop, this);
986 Updater.updateBlockParents();
987
988 // Remove blocks from former ancestor loops.
989 Updater.removeBlocksFromAncestors();
990
991 // Add direct subloops as children in their new parent loop.
992 Updater.updateSubloopParents();
993
994 // Remove unloop from its parent loop.
995 Loop *ParentLoop = Unloop->getParentLoop();
996 for (Loop::iterator I = ParentLoop->begin();; ++I) {
997 assert(I != ParentLoop->end() && "Couldn't find loop");
998 if (*I == Unloop) {
999 ParentLoop->removeChildLoop(I);
1000 break;
1001 }
1002 }
1003}
1004
1006 const Value *V, const BasicBlock *ExitBB) const {
1007 if (V->getType()->isTokenLikeTy())
1008 // We can't form PHIs of token-like type, so the definition of LCSSA
1009 // excludes values of that type.
1010 return false;
1011
1013 if (!I)
1014 return false;
1015 const Loop *L = getLoopFor(I->getParent());
1016 if (!L)
1017 return false;
1018 if (L->contains(ExitBB))
1019 // Could be an exit bb of a subloop and contained in defining loop
1020 return false;
1021
1022 // We found a (new) out-of-loop use location, for a value defined in-loop.
1023 // (Note that because of LCSSA, we don't have to account for values defined
1024 // in sibling loops. Such values will have LCSSA phis of their own in the
1025 // common parent loop.)
1026 return true;
1027}
1028
1029AnalysisKey LoopAnalysis::Key;
1030
1032 // FIXME: Currently we create a LoopInfo from scratch for every function.
1033 // This may prove to be too wasteful due to deallocating and re-allocating
1034 // memory each time for the underlying map and vector datastructures. At some
1035 // point it may prove worthwhile to use a freelist and recycle LoopInfo
1036 // objects. I don't want to add that kind of complexity until the scope of
1037 // the problem is better understood.
1038 LoopInfo LI;
1039 // The dominator tree is needed only for an irreducible CFG.
1040 LI.analyze(&F, [&]() -> const DominatorTree & {
1041 return AM.getResult<DominatorTreeAnalysis>(F);
1042 });
1043 return LI;
1044}
1045
1048 auto &LI = AM.getResult<LoopAnalysis>(F);
1049 OS << "Loop info for function '" << F.getName() << "':\n";
1050 LI.print(OS);
1051 return PreservedAnalyses::all();
1052}
1053
1055 const std::string &Banner) {
1056 if (forcePrintModuleIR()) {
1057 // handling -print-module-scope
1058 OS << Banner << " (loop: ";
1059 L.getHeader()->printAsOperand(OS, false);
1060 OS << ")\n";
1061
1062 // printing whole module
1063 OS << *L.getHeader()->getModule();
1064 return;
1065 }
1066
1067 if (forcePrintFuncIR()) {
1068 // handling -print-loop-func-scope.
1069 // -print-module-scope overrides this.
1070 OS << Banner << " (loop: ";
1071 L.getHeader()->printAsOperand(OS, false);
1072 OS << ")\n";
1073
1074 // printing whole function.
1075 OS << *L.getHeader()->getParent();
1076 return;
1077 }
1078
1079 OS << Banner;
1080
1081 auto *PreHeader = L.getLoopPreheader();
1082 if (PreHeader) {
1083 OS << "\n; Preheader:";
1084 PreHeader->print(OS);
1085 OS << "\n; Loop:";
1086 }
1087
1088 for (auto *Block : L.blocks())
1089 if (Block)
1090 Block->print(OS);
1091 else
1092 OS << "Printing <null> block";
1093
1095 L.getExitBlocks(ExitBlocks);
1096 if (!ExitBlocks.empty()) {
1097 OS << "\n; Exit blocks";
1098 for (auto *Block : ExitBlocks)
1099 if (Block)
1100 Block->print(OS);
1101 else
1102 OS << "Printing <null> block";
1103 }
1104}
1105
1107 // No loop metadata node, no loop properties.
1108 if (!LoopID)
1109 return nullptr;
1110
1111 // First operand should refer to the metadata node itself, for legacy reasons.
1112 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1113 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1114
1115 // Iterate over the metdata node operands and look for MDString metadata.
1116 for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
1117 MDNode *MD = dyn_cast<MDNode>(MDO);
1118 if (!MD || MD->getNumOperands() < 1)
1119 continue;
1121 if (!S)
1122 continue;
1123 // Return the operand node if MDString holds expected metadata.
1124 if (Name == S->getString())
1125 return MD;
1126 }
1127
1128 // Loop property not found.
1129 return nullptr;
1130}
1131
1133 return findOptionMDForLoopID(TheLoop->getLoopID(), Name);
1134}
1135
1136/// Find string metadata for loop
1137///
1138/// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
1139/// operand or null otherwise. If the string metadata is not found return
1140/// Optional's not-a-value.
1141std::optional<const MDOperand *>
1143 MDNode *MD = findOptionMDForLoop(TheLoop, Name);
1144 if (!MD)
1145 return std::nullopt;
1146 switch (MD->getNumOperands()) {
1147 case 1:
1148 return nullptr;
1149 case 2:
1150 return &MD->getOperand(1);
1151 default:
1152 llvm_unreachable("loop metadata has 0 or 1 operand");
1153 }
1154}
1155
1156std::optional<bool> llvm::getOptionalBoolLoopAttribute(const Loop *TheLoop,
1157 StringRef Name) {
1158 MDNode *MD = findOptionMDForLoop(TheLoop, Name);
1159 if (!MD)
1160 return std::nullopt;
1161 switch (MD->getNumOperands()) {
1162 case 1:
1163 // When the value is absent it is interpreted as 'attribute set'.
1164 return true;
1165 case 2:
1166 if (ConstantInt *IntMD =
1168 return IntMD->getZExtValue();
1169 return true;
1170 }
1171 llvm_unreachable("unexpected number of options");
1172}
1173
1175 return getOptionalBoolLoopAttribute(TheLoop, Name).value_or(false);
1176}
1177
1178std::optional<int> llvm::getOptionalIntLoopAttribute(const Loop *TheLoop,
1179 StringRef Name) {
1180 const MDOperand *AttrMD =
1181 findStringMetadataForLoop(TheLoop, Name).value_or(nullptr);
1182 if (!AttrMD)
1183 return std::nullopt;
1184
1185 ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get());
1186 if (!IntMD)
1187 return std::nullopt;
1188
1189 return IntMD->getSExtValue();
1190}
1191
1193 int Default) {
1194 return getOptionalIntLoopAttribute(TheLoop, Name).value_or(Default);
1195}
1196
1198 BasicBlock *H = TheLoop->getHeader();
1199 for (Instruction &II : *H) {
1200 if (auto *CB = dyn_cast<CallBase>(&II)) {
1201 if (!CB->isConvergent())
1202 continue;
1203 // This is the heart if it uses a token defined outside the loop. The
1204 // verifier has already checked that only the loop intrinsic can use such
1205 // a token.
1206 if (auto *Token = CB->getConvergenceControlToken()) {
1207 auto *TokenDef = cast<Instruction>(Token);
1208 if (!TheLoop->contains(TokenDef->getParent()))
1209 return CB;
1210 }
1211 return nullptr;
1212 }
1213 }
1214 return nullptr;
1215}
1216
1217bool llvm::isFinite(const Loop *L) {
1218 return L->getHeader()->getParent()->willReturn();
1219}
1220
1222 // An assumption on L covers every cycle inside it.
1223 if (SE.loopIsFiniteByAssumption(L))
1224 return true;
1225
1226 // An irreducible cycle has no Loop to prove finite.
1227 LoopBlocksRPO RPOT(L);
1228 RPOT.perform(&LI);
1230 return false;
1231
1232 // Likewise, a sub-loop that is finite by assumption covers its own sub-loops.
1234 return false;
1235 SmallVector<Loop *, 8> WorkList(L->begin(), L->end());
1236 while (!WorkList.empty()) {
1237 Loop *Current = WorkList.pop_back_val();
1238 if (SE.loopIsFiniteByAssumption(Current))
1239 continue;
1241 return false;
1242 WorkList.append(Current->begin(), Current->end());
1243 }
1244
1245 return true;
1246}
1247
1248static const char *LLVMLoopMustProgress = "llvm.loop.mustprogress";
1249
1253
1255 return L->getHeader()->getParent()->mustProgress() || hasMustProgress(L);
1256}
1257
1259 return Node->getNumOperands() == 0 && Node->isDistinct();
1260}
1261
1263 MDNode *OrigLoopID,
1264 ArrayRef<StringRef> RemovePrefixes,
1265 ArrayRef<MDNode *> AddAttrs) {
1266 // First remove any existing loop metadata related to this transformation.
1268
1269 // Reserve first location for self reference to the LoopID metadata node.
1270 MDs.push_back(nullptr);
1271
1272 // Remove metadata for the transformation that has been applied or that became
1273 // outdated.
1274 if (OrigLoopID) {
1275 for (const MDOperand &MDO : llvm::drop_begin(OrigLoopID->operands())) {
1276 bool IsVectorMetadata = false;
1277 Metadata *Op = MDO;
1278 if (MDNode *MD = dyn_cast<MDNode>(Op)) {
1279 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1280 if (S)
1281 IsVectorMetadata =
1282 llvm::any_of(RemovePrefixes, [S](StringRef Prefix) -> bool {
1283 return S->getString().starts_with(Prefix);
1284 });
1285 }
1286 if (!IsVectorMetadata)
1287 MDs.push_back(Op);
1288 }
1289 }
1290
1291 // Add metadata to avoid reapplying a transformation, such as
1292 // llvm.loop.unroll.disable and llvm.loop.isvectorized.
1293 MDs.append(AddAttrs.begin(), AddAttrs.end());
1294
1295 MDNode *NewLoopID = MDNode::getDistinct(Context, MDs);
1296 // Replace the temporary node with a self-reference.
1297 NewLoopID->replaceOperandWith(0, NewLoopID);
1298 return NewLoopID;
1299}
1300
1301//===----------------------------------------------------------------------===//
1302// LoopInfo implementation
1303//
1304
1306
1308INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
1309 true, true)
1311INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
1313
1315 releaseMemory();
1317 return false;
1318}
1319
1321 // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
1322 // function each time verifyAnalysis is called is very expensive. The
1323 // -verify-loop-info option can enable this. In order to perform some
1324 // checking by default, LoopPass has been taught to call verifyLoop manually
1325 // during loop pass sequences.
1326 if (VerifyLoopInfo)
1327 LI.verify();
1328}
1329
1334
1336 LI.print(OS);
1337}
1338
1345
1346//===----------------------------------------------------------------------===//
1347// LoopBlocksDFS implementation
1348//
1349
1350/// Traverse the loop blocks and store the DFS result.
1351/// Useful for clients that just want the final DFS result and don't need to
1352/// visit blocks during the initial traversal.
1354 LoopBlocksTraversal Traversal(*this, LI);
1355 for ([[maybe_unused]] BasicBlock *BB : Traversal)
1356 ;
1357}
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:690
#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:476
static bool loopContainsUser(const Loop &L, const BasicBlock &BB, const Use &U, const DominatorTree &DT)
Definition LoopInfo.cpp:454
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
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
LLVM_ABI std::optional< APInt > getConstStepValue() 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
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:940
LLVM_ABI void erase(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
Definition LoopInfo.cpp:949
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:432
bool isLCSSAForm(const DominatorTree &DT, bool IgnoreTokens=true) const
Return true if the Loop is in LCSSA form.
Definition LoopInfo.cpp:493
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:517
std::string getLocStr() const
Return a string containing the debug location of the loop (file name + line number if present,...
Definition LoopInfo.cpp:729
void dumpVerbose() const
Definition LoopInfo.cpp:743
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:627
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
Definition LoopInfo.cpp:694
void dump() const
Definition LoopInfo.cpp:741
LocRange getLocRange() const
Return the source code span of the loop.
Definition LoopInfo.cpp:696
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:532
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:614
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:598
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:510
void addStringLoopAttribute(StringRef Name, ArrayRef< StringRef > RemovePrefixes={}) const
Add a string-only metadata attribute to this loop's loop-ID node.
Definition LoopInfo.cpp:604
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:500
void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
Definition LoopInfo.cpp:582
void setLoopAlreadyUnrolled()
Add llvm.loop.unroll.disable to this loop's loop id metadata.
Definition LoopInfo.cpp:594
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:558
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:714
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.
#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