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"
26#include "llvm/Config/llvm-config.h"
27#include "llvm/IR/CFG.h"
28#include "llvm/IR/Constants.h"
29#include "llvm/IR/DebugLoc.h"
30#include "llvm/IR/Dominators.h"
32#include "llvm/IR/LLVMContext.h"
33#include "llvm/IR/Metadata.h"
34#include "llvm/IR/Module.h"
35#include "llvm/IR/PassManager.h"
36#include "llvm/IR/PrintPasses.h"
43using namespace llvm;
44
45// Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
48
49// Always verify loopinfo if expensive checking is enabled.
50#ifdef EXPENSIVE_CHECKS
51bool llvm::VerifyLoopInfo = true;
52#else
54#endif
57 cl::Hidden, cl::desc("Verify loop info (time consuming)"));
58
59namespace llvm {
61} // end namespace llvm
62
63//===----------------------------------------------------------------------===//
64// Loop implementation
65//
66
67bool Loop::isLoopInvariant(const Value *V) const {
68 if (const Instruction *I = dyn_cast<Instruction>(V))
69 return !contains(I);
70 return true; // All non-instructions are loop invariant
71}
72
74 return all_of(I->operands(), [&](Value *V) { return isLoopInvariant(V); });
75}
76
78 MemorySSAUpdater *MSSAU,
79 ScalarEvolution *SE) const {
81 return makeLoopInvariant(I, Changed, InsertPt, MSSAU, SE);
82 return true; // All non-instructions are loop-invariant.
83}
84
86 Instruction *InsertPt, MemorySSAUpdater *MSSAU,
87 ScalarEvolution *SE) const {
88 BasicBlock *OriginalParent = I->getParent();
89 // Test if the value is already loop-invariant.
90 if (isLoopInvariant(I))
91 return true;
93 return false;
94 if (I->mayReadFromMemory())
95 return false;
96 // EH block instructions are immobile.
97 if (I->isEHPad())
98 return false;
99 // Determine the insertion point, unless one was given.
100 if (!InsertPt) {
101 BasicBlock *Preheader = getLoopPreheader();
102 // Without a preheader, hoisting is not feasible.
103 if (!Preheader)
104 return false;
105 InsertPt = Preheader->getTerminator();
106 }
107 // Don't hoist instructions with loop-variant operands.
108 for (Value *Operand : I->operands())
109 if (!makeLoopInvariant(Operand, Changed, InsertPt, MSSAU, SE))
110 return false;
111
112 // Hoist.
113 I->moveBefore(InsertPt->getIterator());
114 if (MSSAU)
115 if (auto *MUD = MSSAU->getMemorySSA()->getMemoryAccess(I))
116 MSSAU->moveToPlace(MUD, InsertPt->getParent(),
118
119 // We want to preserve profile metadata if possible. However, we need to
120 // ensure that profile metadata would remain the same outside of the loop.
121 // Given at this point we know the conditional is loop-invariant, we just
122 // need to worry about other control flow in the loop conditioned on values
123 // that are potentially not independent of the condition of the instruction
124 // we are interested in hoisting. Given this is not knowable in the general
125 // case, we only hoist from a loop header (which covers a reasonable number
126 // of cases) where we are guaranteed to not run into problems.
127 SmallVector<unsigned, 1> ProfileMetadataToPreserve;
129 if (OriginalParent == getHeader())
130 ProfileMetadataToPreserve.push_back(LLVMContext::MD_prof);
131
132 // There is possibility of hoisting this instruction above some arbitrary
133 // condition. Any metadata defined on it can be control dependent on this
134 // condition. Conservatively strip it here so that we don't give any wrong
135 // information to the optimizer.
136 I->dropUBImplyingAttrsAndUnknownMetadata(ProfileMetadataToPreserve);
137
138 if (ProfileMetadataToPreserve.empty() && isa<SelectInst>(I))
140
141 if (SE)
143
144 Changed = true;
145 return true;
146}
147
149 BasicBlock *&Backedge) const {
151
152 Incoming = nullptr;
153 Backedge = nullptr;
155 assert(PI != pred_end(H) && "Loop must have at least one backedge!");
156 Backedge = *PI++;
157 if (PI == pred_end(H))
158 return false; // dead loop
159 Incoming = *PI++;
160 if (PI != pred_end(H))
161 return false; // multiple backedges?
162
163 if (contains(Incoming)) {
164 if (contains(Backedge))
165 return false;
166 std::swap(Incoming, Backedge);
167 } else if (!contains(Backedge))
168 return false;
169
170 assert(Incoming && Backedge && "expected non-null incoming and backedges");
171 return true;
172}
173
176
177 BasicBlock *Incoming = nullptr, *Backedge = nullptr;
178 if (!getIncomingAndBackEdge(Incoming, Backedge))
179 return nullptr;
180
181 // Loop over all of the PHI nodes, looking for a canonical indvar.
182 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
183 PHINode *PN = cast<PHINode>(I);
184 if (ConstantInt *CI =
186 if (CI->isZero())
187 if (Instruction *Inc =
189 if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
190 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
191 if (CI->isOne())
192 return PN;
193 }
194 return nullptr;
195}
196
197/// Get the latch condition instruction.
199 if (BasicBlock *Latch = getLoopLatch())
200 if (CondBrInst *BI = dyn_cast_or_null<CondBrInst>(Latch->getTerminator()))
201 return dyn_cast<ICmpInst>(BI->getCondition());
202
203 return nullptr;
204}
205
206/// Return the final value of the loop induction variable if found.
207static Value *findFinalIVValue(const Loop &L, const PHINode &IndVar,
208 const Instruction &StepInst) {
209 ICmpInst *LatchCmpInst = L.getLatchCmpInst();
210 if (!LatchCmpInst)
211 return nullptr;
212
213 Value *Op0 = LatchCmpInst->getOperand(0);
214 Value *Op1 = LatchCmpInst->getOperand(1);
215 if (Op0 == &IndVar || Op0 == &StepInst)
216 return Op1;
217
218 if (Op1 == &IndVar || Op1 == &StepInst)
219 return Op0;
220
221 return nullptr;
222}
223
224std::optional<Loop::LoopBounds>
226 ScalarEvolution &SE) {
227 InductionDescriptor IndDesc;
228 if (!InductionDescriptor::isInductionPHI(&IndVar, &L, &SE, IndDesc))
229 return std::nullopt;
230
231 Value *InitialIVValue = IndDesc.getStartValue();
232 Instruction *StepInst = IndDesc.getInductionBinOp();
233 if (!InitialIVValue || !StepInst)
234 return std::nullopt;
235
236 const SCEV *Step = IndDesc.getStep();
237 Value *StepInstOp1 = StepInst->getOperand(1);
238 Value *StepInstOp0 = StepInst->getOperand(0);
239 Value *StepValue = nullptr;
240 if (SE.getSCEV(StepInstOp1) == Step)
241 StepValue = StepInstOp1;
242 else if (SE.getSCEV(StepInstOp0) == Step)
243 StepValue = StepInstOp0;
244
245 Value *FinalIVValue = findFinalIVValue(L, IndVar, *StepInst);
246 if (!FinalIVValue)
247 return std::nullopt;
248
249 return LoopBounds(L, *InitialIVValue, *StepInst, StepValue, *FinalIVValue,
250 SE);
251}
252
254
256 BasicBlock *Latch = L.getLoopLatch();
257 assert(Latch && "Expecting valid latch");
258
260
261 ICmpInst *LatchCmpInst = dyn_cast<ICmpInst>(BI->getCondition());
262 assert(LatchCmpInst &&
263 "Expecting the latch compare instruction to be a CmpInst");
264
265 // Need to inverse the predicate when first successor is not the loop
266 // header
267 ICmpInst::Predicate Pred = (BI->getSuccessor(0) == L.getHeader())
268 ? LatchCmpInst->getPredicate()
269 : LatchCmpInst->getInversePredicate();
270
271 if (LatchCmpInst->getOperand(0) == &getFinalIVValue())
273
274 // Need to flip strictness of the predicate when the latch compare instruction
275 // is not using StepInst
276 if (LatchCmpInst->getOperand(0) == &getStepInst() ||
277 LatchCmpInst->getOperand(1) == &getStepInst())
278 return Pred;
279
280 // Cannot flip strictness of NE and EQ
281 if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
283
285 if (D == Direction::Increasing)
286 return ICmpInst::ICMP_SLT;
287
288 if (D == Direction::Decreasing)
289 return ICmpInst::ICMP_SGT;
290
291 // If cannot determine the direction, then unable to find the canonical
292 // predicate
294}
295
297 if (const SCEVAddRecExpr *StepAddRecExpr =
299 if (const SCEV *StepRecur = StepAddRecExpr->getStepRecurrence(SE)) {
300 if (SE.isKnownPositive(StepRecur))
301 return Direction::Increasing;
302 if (SE.isKnownNegative(StepRecur))
303 return Direction::Decreasing;
304 }
305
306 return Direction::Unknown;
307}
308
309std::optional<Loop::LoopBounds> Loop::getBounds(ScalarEvolution &SE) const {
310 if (PHINode *IndVar = getInductionVariable(SE))
311 return LoopBounds::getBounds(*this, *IndVar, SE);
312
313 return std::nullopt;
314}
315
317 if (!isLoopSimplifyForm())
318 return nullptr;
319
320 BasicBlock *Header = getHeader();
321 assert(Header && "Expected a valid loop header");
323 if (!CmpInst)
324 return nullptr;
325
326 Value *LatchCmpOp0 = CmpInst->getOperand(0);
327 Value *LatchCmpOp1 = CmpInst->getOperand(1);
328
329 for (PHINode &IndVar : Header->phis()) {
330 InductionDescriptor IndDesc;
331 if (!InductionDescriptor::isInductionPHI(&IndVar, this, &SE, IndDesc))
332 continue;
333
334 BasicBlock *Latch = getLoopLatch();
335 Value *StepInst = IndVar.getIncomingValueForBlock(Latch);
336
337 // case 1:
338 // IndVar = phi[{InitialValue, preheader}, {StepInst, latch}]
339 // StepInst = IndVar + step
340 // cmp = StepInst < FinalValue
341 if (StepInst == LatchCmpOp0 || StepInst == LatchCmpOp1)
342 return &IndVar;
343
344 // case 2:
345 // IndVar = phi[{InitialValue, preheader}, {StepInst, latch}]
346 // StepInst = IndVar + step
347 // cmp = IndVar < FinalValue
348 if (&IndVar == LatchCmpOp0 || &IndVar == LatchCmpOp1)
349 return &IndVar;
350 }
351
352 return nullptr;
353}
354
356 InductionDescriptor &IndDesc) const {
357 if (PHINode *IndVar = getInductionVariable(SE))
358 return InductionDescriptor::isInductionPHI(IndVar, this, &SE, IndDesc);
359
360 return false;
361}
362
364 ScalarEvolution &SE) const {
365 // Located in the loop header
366 BasicBlock *Header = getHeader();
367 if (AuxIndVar.getParent() != Header)
368 return false;
369
370 // No uses outside of the loop
371 for (User *U : AuxIndVar.users())
372 if (const Instruction *I = dyn_cast<Instruction>(U))
373 if (!contains(I))
374 return false;
375
376 InductionDescriptor IndDesc;
377 if (!InductionDescriptor::isInductionPHI(&AuxIndVar, this, &SE, IndDesc))
378 return false;
379
380 // The step instruction opcode should be add or sub.
381 if (IndDesc.getInductionOpcode() != Instruction::Add &&
382 IndDesc.getInductionOpcode() != Instruction::Sub)
383 return false;
384
385 // Incremented by a loop invariant step for each loop iteration
386 return SE.isLoopInvariant(IndDesc.getStep(), this);
387}
388
390 if (!isLoopSimplifyForm())
391 return nullptr;
392
393 BasicBlock *Preheader = getLoopPreheader();
394 assert(Preheader && getLoopLatch() &&
395 "Expecting a loop with valid preheader and latch");
396
397 // Loop should be in rotate form.
398 if (!isRotatedForm())
399 return nullptr;
400
401 // Disallow loops with more than one unique exit block, as we do not verify
402 // that GuardOtherSucc post dominates all exit blocks.
403 BasicBlock *ExitFromLatch = getUniqueExitBlock();
404 if (!ExitFromLatch)
405 return nullptr;
406
407 BasicBlock *GuardBB = Preheader->getUniquePredecessor();
408 if (!GuardBB)
409 return nullptr;
410
411 assert(GuardBB->getTerminator() && "Expecting valid guard terminator");
412
413 CondBrInst *GuardBI = dyn_cast<CondBrInst>(GuardBB->getTerminator());
414 if (!GuardBI)
415 return nullptr;
416
417 BasicBlock *GuardOtherSucc = (GuardBI->getSuccessor(0) == Preheader)
418 ? GuardBI->getSuccessor(1)
419 : GuardBI->getSuccessor(0);
420
421 // Check if ExitFromLatch (or any BasicBlock which is an empty unique
422 // successor of ExitFromLatch) is equal to GuardOtherSucc. If
423 // skipEmptyBlockUntil returns GuardOtherSucc, then the guard branch for the
424 // loop is GuardBI (return GuardBI), otherwise return nullptr.
425 if (&LoopNest::skipEmptyBlockUntil(ExitFromLatch, GuardOtherSucc,
426 /*CheckUniquePred=*/true) ==
427 GuardOtherSucc)
428 return GuardBI;
429 else
430 return nullptr;
431}
432
434 InductionDescriptor IndDesc;
435 if (!getInductionDescriptor(SE, IndDesc))
436 return false;
437
439 if (!Init || !Init->isZero())
440 return false;
441
442 if (IndDesc.getInductionOpcode() != Instruction::Add)
443 return false;
444
445 ConstantInt *Step = IndDesc.getConstIntStepValue();
446 if (!Step || !Step->isOne())
447 return false;
448
449 return true;
450}
451
452// Check whether the use \p U of a value defined in block \p BB (which is part
453// of loop \p L) does not require a live-out phi, i.e. whether it is contained
454// in the loop for LCSSA purposes.
455static bool loopContainsUser(const Loop &L, const BasicBlock &BB, const Use &U,
456 const DominatorTree &DT) {
457 const Instruction *UI = cast<Instruction>(U.getUser());
458 const BasicBlock *UserBB = UI->getParent();
459
460 // For practical purposes, we consider that the use in a PHI
461 // occurs in the respective predecessor block. For more info,
462 // see the `phi` doc in LangRef and the LCSSA doc.
463 if (const PHINode *P = dyn_cast<PHINode>(UI))
464 UserBB = P->getIncomingBlock(U);
465
466 // Check the current block, as a fast-path, before checking whether
467 // the use is anywhere in the loop. Most values are used in the same
468 // block they are defined in. Also, blocks not reachable from the
469 // entry are special; uses in them don't need to go through PHIs.
470 if (UserBB != &BB && !L.contains(UserBB) && DT.isReachableFromEntry(UserBB))
471 return false;
472
473 return true;
474}
475
476// Check that 'BB' doesn't have any uses outside of the 'L'
477static bool isBlockInLCSSAForm(const Loop &L, const BasicBlock &BB,
478 const DominatorTree &DT, bool IgnoreTokens) {
479 for (const Instruction &I : BB) {
480 // Token-like values can't be used in PHI nodes and live-out token-like
481 // values prevent loop optimizations, so for the purposes of considered
482 // LCSSA form, we can ignore them.
483 if (IgnoreTokens && I.getType()->isTokenLikeTy())
484 continue;
485
486 for (const Use &U : I.uses()) {
487 if (!loopContainsUser(L, BB, U, DT))
488 return false;
489 }
490 }
491 return true;
492}
493
494bool Loop::isLCSSAForm(const DominatorTree &DT, bool IgnoreTokens) const {
495 // For each block we check that it doesn't have any uses outside of this loop.
496 return all_of(this->blocks(), [&](const BasicBlock *BB) {
497 return isBlockInLCSSAForm(*this, *BB, DT, IgnoreTokens);
498 });
499}
500
502 bool IgnoreTokens) const {
503 // For each block we check that it doesn't have any uses outside of its
504 // innermost loop. This process will transitively guarantee that the current
505 // loop and all of the nested loops are in LCSSA form.
506 return all_of(this->blocks(), [&](const BasicBlock *BB) {
507 return isBlockInLCSSAForm(*LI.getLoopFor(BB), *BB, DT, IgnoreTokens);
508 });
509}
510
512 // Normal-form loops have a preheader, a single backedge, and all of their
513 // exits have all their predecessors inside the loop.
515}
516
517// Routines that reform the loop CFG and split edges often fail on indirectbr.
519 // Return false if any loop blocks contain indirectbrs, or there are any calls
520 // to noduplicate functions.
521 for (BasicBlock *BB : this->blocks()) {
522 if (isa<IndirectBrInst>(BB->getTerminator()))
523 return false;
524
525 for (Instruction &I : *BB)
526 if (auto *CB = dyn_cast<CallBase>(&I))
527 if (CB->cannotDuplicate())
528 return false;
529 }
530 return true;
531}
532
534 if (!isSafeToClone())
535 return false;
536
537 for (BasicBlock *BB : this->blocks()) {
538 for (Instruction &I : *BB) {
539 // Token-like values cannot be used in PHI nodes, so cloning is only
540 // possible if all their uses are contained in the loop. Uses within
541 // the loop (even across blocks) are fine: cloning only requires
542 // forming phis for values that are live-out of the loop.
543 if (I.getType()->isTokenLikeTy()) {
544 for (const Use &U : I.uses()) {
545 if (!loopContainsUser(*this, *BB, U, DT))
546 return false;
547 }
548 }
549 if (auto *CB = dyn_cast<CallBase>(&I)) {
550 assert(!CB->cannotDuplicate() && "Checked by isSafeToClone().");
551 if (CB->isConvergent())
552 return false;
553 }
554 }
555 }
556 return true;
557}
558
560 MDNode *LoopID = nullptr;
561
562 // Go through the latch blocks and check the terminator for the metadata.
563 SmallVector<BasicBlock *, 4> LatchesBlocks;
564 getLoopLatches(LatchesBlocks);
565 for (BasicBlock *BB : LatchesBlocks) {
566 Instruction *TI = BB->getTerminator();
567 MDNode *MD = TI->getMetadata(LLVMContext::MD_loop);
568
569 if (!MD)
570 return nullptr;
571
572 if (!LoopID)
573 LoopID = MD;
574 else if (MD != LoopID)
575 return nullptr;
576 }
577 if (!LoopID || LoopID->getNumOperands() == 0 ||
578 LoopID->getOperand(0) != LoopID)
579 return nullptr;
580 return LoopID;
581}
582
583void Loop::setLoopID(MDNode *LoopID) const {
584 assert((!LoopID || LoopID->getNumOperands() > 0) &&
585 "Loop ID needs at least one operand");
586 assert((!LoopID || LoopID->getOperand(0) == LoopID) &&
587 "Loop ID should refer to itself");
588
590 getLoopLatches(LoopLatches);
591 for (BasicBlock *BB : LoopLatches)
592 BB->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID);
593}
594
596 addStringLoopAttribute("llvm.loop.unroll.disable", {"llvm.loop.unroll."});
597}
598
600 if (findOptionMDForLoop(this, "llvm.loop.mustprogress"))
601 return;
602 addStringLoopAttribute("llvm.loop.mustprogress");
603}
604
606 ArrayRef<StringRef> RemovePrefixes) const {
607 LLVMContext &Context = getHeader()->getContext();
608 MDNode *AttrMD = MDNode::get(Context, MDString::get(Context, Name));
609 MDNode *LoopID = getLoopID();
610 MDNode *NewLoopID =
611 makePostTransformationMetadata(Context, LoopID, RemovePrefixes, {AttrMD});
612 setLoopID(NewLoopID);
613}
614
616 ArrayRef<StringRef> RemovePrefixes) const {
617 LLVMContext &Context = getHeader()->getContext();
618 MDNode *AttrMD = MDNode::get(
619 Context,
620 {MDString::get(Context, Name),
621 ConstantAsMetadata::get(ConstantInt::get(Context, APInt(32, Value)))});
622 MDNode *LoopID = getLoopID();
623 MDNode *NewLoopID =
624 makePostTransformationMetadata(Context, LoopID, RemovePrefixes, {AttrMD});
625 setLoopID(NewLoopID);
626}
627
629 MDNode *DesiredLoopIdMetadata = getLoopID();
630
631 if (!DesiredLoopIdMetadata)
632 return false;
633
634 MDNode *ParallelAccesses =
635 findOptionMDForLoop(this, "llvm.loop.parallel_accesses");
637 ParallelAccessGroups; // For scalable 'contains' check.
638 if (ParallelAccesses) {
639 for (const MDOperand &MD : drop_begin(ParallelAccesses->operands())) {
640 MDNode *AccGroup = cast<MDNode>(MD.get());
641 assert(isValidAsAccessGroup(AccGroup) &&
642 "List item must be an access group");
643 ParallelAccessGroups.insert(AccGroup);
644 }
645 }
646
647 // The loop branch contains the parallel loop metadata. In order to ensure
648 // that any parallel-loop-unaware optimization pass hasn't added loop-carried
649 // dependencies (thus converted the loop back to a sequential loop), check
650 // that all the memory instructions in the loop belong to an access group that
651 // is parallel to this loop.
652 for (BasicBlock *BB : this->blocks()) {
653 for (Instruction &I : *BB) {
654 if (!I.mayReadOrWriteMemory())
655 continue;
656
657 if (MDNode *AccessGroup = I.getMetadata(LLVMContext::MD_access_group)) {
658 auto ContainsAccessGroup = [&ParallelAccessGroups](MDNode *AG) -> bool {
659 if (AG->getNumOperands() == 0) {
660 assert(isValidAsAccessGroup(AG) && "Item must be an access group");
661 return ParallelAccessGroups.count(AG);
662 }
663
664 for (const MDOperand &AccessListItem : AG->operands()) {
665 MDNode *AccGroup = cast<MDNode>(AccessListItem.get());
666 assert(isValidAsAccessGroup(AccGroup) &&
667 "List item must be an access group");
668 if (ParallelAccessGroups.count(AccGroup))
669 return true;
670 }
671 return false;
672 };
673
674 if (ContainsAccessGroup(AccessGroup))
675 continue;
676 }
677
678 // The memory instruction can refer to the loop identifier metadata
679 // directly or indirectly through another list metadata (in case of
680 // nested parallel loops). The loop identifier metadata refers to
681 // itself so we can check both cases with the same routine.
682 MDNode *LoopIdMD =
683 I.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
684
685 if (!LoopIdMD)
686 return false;
687
688 if (!llvm::is_contained(LoopIdMD->operands(), DesiredLoopIdMetadata))
689 return false;
690 }
691 }
692 return true;
693}
694
696
698 // If we have a debug location in the loop ID, then use it.
699 if (MDNode *LoopID = getLoopID()) {
700 DebugLoc Start;
701 // We use the first DebugLoc in the header as the start location of the loop
702 // and if there is a second DebugLoc in the header we use it as end location
703 // of the loop.
704 for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
705 if (DILocation *L = dyn_cast<DILocation>(MDO)) {
706 if (!Start)
707 Start = DebugLoc(L);
708 else
709 return LocRange(Start, DebugLoc(L));
710 }
711 }
712
713 if (Start)
714 return LocRange(Start);
715 }
716
717 // Try the pre-header first.
718 if (BasicBlock *PHeadBB = getLoopPreheader())
719 if (DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc())
720 return LocRange(DL);
721
722 // If we have no pre-header or there are no instructions with debug
723 // info in it, try the header.
724 if (BasicBlock *HeadBB = getHeader())
725 return LocRange(HeadBB->getTerminator()->getDebugLoc());
726
727 return LocRange();
728}
729
730std::string Loop::getLocStr() const {
731 std::string Result;
732 raw_string_ostream OS(Result);
733 if (const DebugLoc LoopDbgLoc = getStartLoc())
734 LoopDbgLoc.print(OS);
735 else
736 // Just print the module name.
738 return Result;
739}
740
741#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
743
745 print(dbgs(), /*Verbose=*/true);
746}
747#endif
748
749//===----------------------------------------------------------------------===//
750// UnloopUpdater implementation
751//
752
753namespace {
754/// Find the new parent loop for all blocks within the "unloop" whose last
755/// backedges has just been removed.
756class UnloopUpdater {
757 Loop &Unloop;
758 LoopInfo *LI;
759
760 LoopBlocksDFS DFS;
761
762 // Map unloop's immediate subloops to their nearest reachable parents. Nested
763 // loops within these subloops will not change parents. However, an immediate
764 // subloop's new parent will be the nearest loop reachable from either its own
765 // exits *or* any of its nested loop's exits.
766 DenseMap<Loop *, Loop *> SubloopParents;
767
768 // Flag the presence of an irreducible backedge whose destination is a block
769 // directly contained by the original unloop.
770 bool FoundIB = false;
771
772public:
773 UnloopUpdater(Loop *UL, LoopInfo *LInfo) : Unloop(*UL), LI(LInfo), DFS(UL) {}
774
775 void updateBlockParents();
776
777 void removeBlocksFromAncestors();
778
779 void updateSubloopParents();
780
781protected:
782 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
783};
784} // end anonymous namespace
785
786/// Update the parent loop for all blocks that are directly contained within the
787/// original "unloop".
788void UnloopUpdater::updateBlockParents() {
789 if (Unloop.getNumBlocks()) {
790 // Perform a post order CFG traversal of all blocks within this loop,
791 // propagating the nearest loop from successors to predecessors.
792 LoopBlocksTraversal Traversal(DFS, LI);
793 for (BasicBlock *POI : Traversal) {
794
795 Loop *L = LI->getLoopFor(POI);
796 Loop *NL = getNearestLoop(POI, L);
797
798 if (NL != L) {
799 // For reducible loops, NL is now an ancestor of Unloop.
800 assert((NL != &Unloop && (!NL || NL->contains(&Unloop))) &&
801 "uninitialized successor");
802 LI->changeLoopFor(POI, NL);
803 } else {
804 // Or the current block is part of a subloop, in which case its parent
805 // is unchanged.
806 assert((FoundIB || Unloop.contains(L)) && "uninitialized successor");
807 }
808 }
809 }
810 // Each irreducible loop within the unloop induces a round of iteration using
811 // the DFS result cached by Traversal.
812 bool Changed = FoundIB;
813 for (unsigned NIters = 0; Changed; ++NIters) {
814 assert(NIters < Unloop.getNumBlocks() && "runaway iterative algorithm");
815 (void)NIters;
816
817 // Iterate over the postorder list of blocks, propagating the nearest loop
818 // from successors to predecessors as before.
819 Changed = false;
820 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
821 POE = DFS.endPostorder();
822 POI != POE; ++POI) {
823
824 Loop *L = LI->getLoopFor(*POI);
825 Loop *NL = getNearestLoop(*POI, L);
826 if (NL != L) {
827 assert(NL != &Unloop && (!NL || NL->contains(&Unloop)) &&
828 "uninitialized successor");
829 LI->changeLoopFor(*POI, NL);
830 Changed = true;
831 }
832 }
833 }
834}
835
836/// Remove unloop's blocks from all ancestors below their new parents.
837void UnloopUpdater::removeBlocksFromAncestors() {
838 // Remove all unloop's blocks (including those in nested subloops) from
839 // ancestors below the new parent loop.
840 for (BasicBlock *BB : Unloop.blocks()) {
841 Loop *OuterParent = LI->getLoopFor(BB);
842 if (Unloop.contains(OuterParent)) {
843 while (OuterParent->getParentLoop() != &Unloop)
844 OuterParent = OuterParent->getParentLoop();
845 OuterParent = SubloopParents[OuterParent];
846 }
847 // Remove blocks from former Ancestors except Unloop itself which will be
848 // deleted.
849 for (Loop *OldParent = Unloop.getParentLoop(); OldParent != OuterParent;
850 OldParent = OldParent->getParentLoop()) {
851 assert(OldParent && "new loop is not an ancestor of the original");
852 OldParent->removeBlockFromLoop(BB);
853 }
854 }
855}
856
857/// Update the parent loop for all subloops directly nested within unloop.
858void UnloopUpdater::updateSubloopParents() {
859 while (!Unloop.isInnermost()) {
860 Loop *Subloop = *std::prev(Unloop.end());
861 Unloop.removeChildLoop(std::prev(Unloop.end()));
862
863 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
864 if (Loop *Parent = SubloopParents[Subloop])
865 Parent->addChildLoop(Subloop);
866 else
867 LI->addTopLevelLoop(Subloop);
868 }
869}
870
871/// Return the nearest parent loop among this block's successors. If a successor
872/// is a subloop header, consider its parent to be the nearest parent of the
873/// subloop's exits.
874///
875/// For subloop blocks, simply update SubloopParents and return NULL.
876Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
877
878 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
879 // is considered uninitialized.
880 Loop *NearLoop = BBLoop;
881
882 Loop *Subloop = nullptr;
883 if (NearLoop != &Unloop && Unloop.contains(NearLoop)) {
884 Subloop = NearLoop;
885 // Find the subloop ancestor that is directly contained within Unloop.
886 while (Subloop->getParentLoop() != &Unloop) {
887 Subloop = Subloop->getParentLoop();
888 assert(Subloop && "subloop is not an ancestor of the original loop");
889 }
890 // Get the current nearest parent of the Subloop exits, initially Unloop.
891 NearLoop = SubloopParents.insert({Subloop, &Unloop}).first->second;
892 }
893
894 if (succ_empty(BB)) {
895 assert(!Subloop && "subloop blocks must have a successor");
896 NearLoop = nullptr; // unloop blocks may now exit the function.
897 }
898 for (BasicBlock *Succ : successors(BB)) {
899 if (Succ == BB)
900 continue; // self loops are uninteresting
901
902 Loop *L = LI->getLoopFor(Succ);
903 if (L == &Unloop) {
904 // This successor has not been processed. This path must lead to an
905 // irreducible backedge.
906 assert((FoundIB || !DFS.hasPostorder(Succ)) && "should have seen IB");
907 FoundIB = true;
908 }
909 if (L != &Unloop && Unloop.contains(L)) {
910 // Successor is in a subloop.
911 if (Subloop)
912 continue; // Branching within subloops. Ignore it.
913
914 // BB branches from the original into a subloop header.
915 assert(L->getParentLoop() == &Unloop && "cannot skip into nested loops");
916
917 // Get the current nearest parent of the Subloop's exits.
918 L = SubloopParents[L];
919 // L could be Unloop if the only exit was an irreducible backedge.
920 }
921 if (L == &Unloop) {
922 continue;
923 }
924 // Handle critical edges from Unloop into a sibling loop.
925 if (L && !L->contains(&Unloop)) {
926 L = L->getParentLoop();
927 }
928 // Remember the nearest parent loop among successors or subloop exits.
929 if (NearLoop == &Unloop || !NearLoop || NearLoop->contains(L))
930 NearLoop = L;
931 }
932 if (Subloop) {
933 SubloopParents[Subloop] = NearLoop;
934 return BBLoop;
935 }
936 return NearLoop;
937}
938
939LoopInfo::LoopInfo(const DomTreeBase<BasicBlock> &DomTree) { analyze(DomTree); }
940
942 FunctionAnalysisManager::Invalidator &) {
943 // Check whether the analysis, all analyses on functions, or the function's
944 // CFG have been preserved.
945 auto PAC = PA.getChecker<LoopAnalysis>();
946 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
947 PAC.preservedSet<CFGAnalyses>());
948}
949
950void LoopInfo::erase(Loop *Unloop) {
951 assert(!Unloop->isInvalid() && "Loop has already been erased!");
952
953 llvm::scope_exit InvalidateOnExit([&]() { destroy(Unloop); });
954
955 // First handle the special case of no parent loop to simplify the algorithm.
956 if (Unloop->isOutermost()) {
957 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
958 for (BasicBlock *BB : Unloop->blocks()) {
959 // Don't reparent blocks in subloops.
960 if (getLoopFor(BB) != Unloop)
961 continue;
962
963 // Blocks no longer have a parent but are still referenced by Unloop until
964 // the Unloop object is deleted.
965 changeLoopFor(BB, nullptr);
966 }
967
968 // Remove the loop from the top-level LoopInfo object.
969 for (iterator I = begin();; ++I) {
970 assert(I != end() && "Couldn't find loop");
971 if (*I == Unloop) {
972 removeLoop(I);
973 break;
974 }
975 }
976
977 // Move all of the subloops to the top-level.
978 while (!Unloop->isInnermost())
979 addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
980
981 return;
982 }
983
984 // Update the parent loop for all blocks within the loop. Blocks within
985 // subloops will not change parents.
986 UnloopUpdater Updater(Unloop, this);
987 Updater.updateBlockParents();
988
989 // Remove blocks from former ancestor loops.
990 Updater.removeBlocksFromAncestors();
991
992 // Add direct subloops as children in their new parent loop.
993 Updater.updateSubloopParents();
994
995 // Remove unloop from its parent loop.
996 Loop *ParentLoop = Unloop->getParentLoop();
997 for (Loop::iterator I = ParentLoop->begin();; ++I) {
998 assert(I != ParentLoop->end() && "Couldn't find loop");
999 if (*I == Unloop) {
1000 ParentLoop->removeChildLoop(I);
1001 break;
1002 }
1003 }
1004}
1005
1007 const Value *V, const BasicBlock *ExitBB) const {
1008 if (V->getType()->isTokenLikeTy())
1009 // We can't form PHIs of token-like type, so the definition of LCSSA
1010 // excludes values of that type.
1011 return false;
1012
1014 if (!I)
1015 return false;
1016 const Loop *L = getLoopFor(I->getParent());
1017 if (!L)
1018 return false;
1019 if (L->contains(ExitBB))
1020 // Could be an exit bb of a subloop and contained in defining loop
1021 return false;
1022
1023 // We found a (new) out-of-loop use location, for a value defined in-loop.
1024 // (Note that because of LCSSA, we don't have to account for values defined
1025 // in sibling loops. Such values will have LCSSA phis of their own in the
1026 // common parent loop.)
1027 return true;
1028}
1029
1030AnalysisKey LoopAnalysis::Key;
1031
1033 // FIXME: Currently we create a LoopInfo from scratch for every function.
1034 // This may prove to be too wasteful due to deallocating and re-allocating
1035 // memory each time for the underlying map and vector datastructures. At some
1036 // point it may prove worthwhile to use a freelist and recycle LoopInfo
1037 // objects. I don't want to add that kind of complexity until the scope of
1038 // the problem is better understood.
1039 LoopInfo LI;
1040 // The dominator tree is needed only for an irreducible CFG.
1041 LI.analyze(&F, [&]() -> const DominatorTree & {
1042 return AM.getResult<DominatorTreeAnalysis>(F);
1043 });
1044 return LI;
1045}
1046
1049 auto &LI = AM.getResult<LoopAnalysis>(F);
1050 OS << "Loop info for function '" << F.getName() << "':\n";
1051 LI.print(OS);
1052 return PreservedAnalyses::all();
1053}
1054
1056 const std::string &Banner) {
1057 if (forcePrintModuleIR()) {
1058 // handling -print-module-scope
1059 OS << Banner << " (loop: ";
1060 L.getHeader()->printAsOperand(OS, false);
1061 OS << ")\n";
1062
1063 // printing whole module
1064 OS << *L.getHeader()->getModule();
1065 return;
1066 }
1067
1068 if (forcePrintFuncIR()) {
1069 // handling -print-loop-func-scope.
1070 // -print-module-scope overrides this.
1071 OS << Banner << " (loop: ";
1072 L.getHeader()->printAsOperand(OS, false);
1073 OS << ")\n";
1074
1075 // printing whole function.
1076 OS << *L.getHeader()->getParent();
1077 return;
1078 }
1079
1080 OS << Banner;
1081
1082 auto *PreHeader = L.getLoopPreheader();
1083 if (PreHeader) {
1084 OS << "\n; Preheader:";
1085 PreHeader->print(OS);
1086 OS << "\n; Loop:";
1087 }
1088
1089 for (auto *Block : L.blocks())
1090 if (Block)
1091 Block->print(OS);
1092 else
1093 OS << "Printing <null> block";
1094
1096 L.getExitBlocks(ExitBlocks);
1097 if (!ExitBlocks.empty()) {
1098 OS << "\n; Exit blocks";
1099 for (auto *Block : ExitBlocks)
1100 if (Block)
1101 Block->print(OS);
1102 else
1103 OS << "Printing <null> block";
1104 }
1105}
1106
1108 // No loop metadata node, no loop properties.
1109 if (!LoopID)
1110 return nullptr;
1111
1112 // First operand should refer to the metadata node itself, for legacy reasons.
1113 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1114 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1115
1116 // Iterate over the metdata node operands and look for MDString metadata.
1117 for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
1118 MDNode *MD = dyn_cast<MDNode>(MDO);
1119 if (!MD || MD->getNumOperands() < 1)
1120 continue;
1122 if (!S)
1123 continue;
1124 // Return the operand node if MDString holds expected metadata.
1125 if (Name == S->getString())
1126 return MD;
1127 }
1128
1129 // Loop property not found.
1130 return nullptr;
1131}
1132
1134 return findOptionMDForLoopID(TheLoop->getLoopID(), Name);
1135}
1136
1137/// Find string metadata for loop
1138///
1139/// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
1140/// operand or null otherwise. If the string metadata is not found return
1141/// Optional's not-a-value.
1142std::optional<const MDOperand *>
1144 MDNode *MD = findOptionMDForLoop(TheLoop, Name);
1145 if (!MD)
1146 return std::nullopt;
1147 switch (MD->getNumOperands()) {
1148 case 1:
1149 return nullptr;
1150 case 2:
1151 return &MD->getOperand(1);
1152 default:
1153 llvm_unreachable("loop metadata has 0 or 1 operand");
1154 }
1155}
1156
1157std::optional<bool> llvm::getOptionalBoolLoopAttribute(const Loop *TheLoop,
1158 StringRef Name) {
1159 MDNode *MD = findOptionMDForLoop(TheLoop, Name);
1160 if (!MD)
1161 return std::nullopt;
1162 switch (MD->getNumOperands()) {
1163 case 1:
1164 // When the value is absent it is interpreted as 'attribute set'.
1165 return true;
1166 case 2:
1167 if (ConstantInt *IntMD =
1169 return IntMD->getZExtValue();
1170 return true;
1171 }
1172 llvm_unreachable("unexpected number of options");
1173}
1174
1176 return getOptionalBoolLoopAttribute(TheLoop, Name).value_or(false);
1177}
1178
1179std::optional<int> llvm::getOptionalIntLoopAttribute(const Loop *TheLoop,
1180 StringRef Name) {
1181 const MDOperand *AttrMD =
1182 findStringMetadataForLoop(TheLoop, Name).value_or(nullptr);
1183 if (!AttrMD)
1184 return std::nullopt;
1185
1186 ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get());
1187 if (!IntMD)
1188 return std::nullopt;
1189
1190 return IntMD->getSExtValue();
1191}
1192
1194 int Default) {
1195 return getOptionalIntLoopAttribute(TheLoop, Name).value_or(Default);
1196}
1197
1199 BasicBlock *H = TheLoop->getHeader();
1200 for (Instruction &II : *H) {
1201 if (auto *CB = dyn_cast<CallBase>(&II)) {
1202 if (!CB->isConvergent())
1203 continue;
1204 // This is the heart if it uses a token defined outside the loop. The
1205 // verifier has already checked that only the loop intrinsic can use such
1206 // a token.
1207 if (auto *Token = CB->getConvergenceControlToken()) {
1208 auto *TokenDef = cast<Instruction>(Token);
1209 if (!TheLoop->contains(TokenDef->getParent()))
1210 return CB;
1211 }
1212 return nullptr;
1213 }
1214 }
1215 return nullptr;
1216}
1217
1218bool llvm::isFinite(const Loop *L) {
1219 return L->getHeader()->getParent()->willReturn();
1220}
1221
1222static const char *LLVMLoopMustProgress = "llvm.loop.mustprogress";
1223
1227
1229 return L->getHeader()->getParent()->mustProgress() || hasMustProgress(L);
1230}
1231
1233 return Node->getNumOperands() == 0 && Node->isDistinct();
1234}
1235
1237 MDNode *OrigLoopID,
1238 ArrayRef<StringRef> RemovePrefixes,
1239 ArrayRef<MDNode *> AddAttrs) {
1240 // First remove any existing loop metadata related to this transformation.
1242
1243 // Reserve first location for self reference to the LoopID metadata node.
1244 MDs.push_back(nullptr);
1245
1246 // Remove metadata for the transformation that has been applied or that became
1247 // outdated.
1248 if (OrigLoopID) {
1249 for (const MDOperand &MDO : llvm::drop_begin(OrigLoopID->operands())) {
1250 bool IsVectorMetadata = false;
1251 Metadata *Op = MDO;
1252 if (MDNode *MD = dyn_cast<MDNode>(Op)) {
1253 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1254 if (S)
1255 IsVectorMetadata =
1256 llvm::any_of(RemovePrefixes, [S](StringRef Prefix) -> bool {
1257 return S->getString().starts_with(Prefix);
1258 });
1259 }
1260 if (!IsVectorMetadata)
1261 MDs.push_back(Op);
1262 }
1263 }
1264
1265 // Add metadata to avoid reapplying a transformation, such as
1266 // llvm.loop.unroll.disable and llvm.loop.isvectorized.
1267 MDs.append(AddAttrs.begin(), AddAttrs.end());
1268
1269 MDNode *NewLoopID = MDNode::getDistinct(Context, MDs);
1270 // Replace the temporary node with a self-reference.
1271 NewLoopID->replaceOperandWith(0, NewLoopID);
1272 return NewLoopID;
1273}
1274
1275//===----------------------------------------------------------------------===//
1276// LoopInfo implementation
1277//
1278
1280
1282INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
1283 true, true)
1285INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
1287
1289 releaseMemory();
1291 return false;
1292}
1293
1295 // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
1296 // function each time verifyAnalysis is called is very expensive. The
1297 // -verify-loop-info option can enable this. In order to perform some
1298 // checking by default, LoopPass has been taught to call verifyLoop manually
1299 // during loop pass sequences.
1300 if (VerifyLoopInfo)
1301 LI.verify();
1302}
1303
1308
1310 LI.print(OS);
1311}
1312
1319
1320//===----------------------------------------------------------------------===//
1321// LoopBlocksDFS implementation
1322//
1323
1324/// Traverse the loop blocks and store the DFS result.
1325/// Useful for clients that just want the final DFS result and don't need to
1326/// visit blocks during the initial traversal.
1328 LoopBlocksTraversal Traversal(*this, LI);
1329 for ([[maybe_unused]] BasicBlock *BB : Traversal)
1330 ;
1331}
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:678
#define LLVM_EXPORT_TEMPLATE
Definition Compiler.h:217
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:477
static bool loopContainsUser(const Loop &L, const BasicBlock &BB, const Use &U, const DominatorTree &DT)
Definition LoopInfo.cpp:455
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:207
Loop::LoopBounds::Direction Direction
Definition LoopInfo.cpp:253
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:537
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:316
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.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
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.
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:941
LLVM_ABI void erase(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
Definition LoopInfo.cpp:950
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:433
bool isLCSSAForm(const DominatorTree &DT, bool IgnoreTokens=true) const
Return true if the Loop is in LCSSA form.
Definition LoopInfo.cpp:494
std::optional< LoopBounds > getBounds(ScalarEvolution &SE) const
Return the struct LoopBounds collected if all struct members are found, else std::nullopt.
Definition LoopInfo.cpp:309
bool isSafeToClone() const
Return true if the loop body is safe to clone in practice.
Definition LoopInfo.cpp:518
std::string getLocStr() const
Return a string containing the debug location of the loop (file name + line number if present,...
Definition LoopInfo.cpp:730
void dumpVerbose() const
Definition LoopInfo.cpp:744
bool hasLoopInvariantOperands(const Instruction *I) const
Return true if all the operands of the specified instruction are loop invariant.
Definition LoopInfo.cpp:73
bool isAnnotatedParallel() const
Returns true if the loop is annotated parallel.
Definition LoopInfo.cpp:628
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
Definition LoopInfo.cpp:695
void dump() const
Definition LoopInfo.cpp:742
LocRange getLocRange() const
Return the source code span of the loop.
Definition LoopInfo.cpp:697
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:67
ICmpInst * getLatchCmpInst() const
Get the latch condition instruction.
Definition LoopInfo.cpp:198
bool isSafeToCloneConditionally(const DominatorTree &DT) const
Like isSafeToClone, but for transformations where the cloned loop bodies may run conditionally.
Definition LoopInfo.cpp:533
bool getInductionDescriptor(ScalarEvolution &SE, InductionDescriptor &IndDesc) const
Get the loop induction descriptor for the loop induction variable.
Definition LoopInfo.cpp:355
CondBrInst * getLoopGuardBranch() const
Return the loop guard branch, if it exists.
Definition LoopInfo.cpp:389
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:615
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:599
PHINode * getInductionVariable(ScalarEvolution &SE) const
Return the loop induction variable if found, else return nullptr.
Definition LoopInfo.cpp:316
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to,...
Definition LoopInfo.cpp:511
void addStringLoopAttribute(StringRef Name, ArrayRef< StringRef > RemovePrefixes={}) const
Add a string-only metadata attribute to this loop's loop-ID node.
Definition LoopInfo.cpp:605
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:501
void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
Definition LoopInfo.cpp:583
void setLoopAlreadyUnrolled()
Add llvm.loop.unroll.disable to this loop's loop id metadata.
Definition LoopInfo.cpp:595
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:77
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:174
bool getIncomingAndBackEdge(BasicBlock *&Incoming, BasicBlock *&Backedge) const
Obtain the unique incoming and back edge.
Definition LoopInfo.cpp:148
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
Definition LoopInfo.cpp:559
bool isAuxiliaryInductionVariable(PHINode &AuxIndVar, ScalarEvolution &SE) const
Return true if the given PHINode AuxIndVar is.
Definition LoopInfo.cpp:363
Metadata node.
Definition Metadata.h:1069
LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1575
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1426
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1424
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1567
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1432
Tracking metadata reference owned by Metadata.
Definition Metadata.h:891
Metadata * get() const
Definition Metadata.h:920
A single uniqued string.
Definition Metadata.h:722
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:633
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:615
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:67
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition Module.h:294
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.
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.
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
iterator_range< user_iterator > users()
Definition Value.h:426
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:683
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:315
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
Definition LoopInfo.cpp:60
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:1739
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:1746
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:53
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 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:1947
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
@ Default
The result value is uniform if and only if all operands are uniform.
Definition Uniformity.h:20
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:225
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:255
LLVM_ABI Direction getDirection() const
Get the direction of the loop.
Definition LoopInfo.cpp:296