LLVM 24.0.0git
IndVarSimplify.cpp
Go to the documentation of this file.
1//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
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 transformation analyzes and transforms the induction variables (and
10// computations derived from them) into simpler forms suitable for subsequent
11// analysis and transformation.
12//
13// If the trip count of a loop is computable, this pass also makes the following
14// changes:
15// 1. The exit condition for the loop is canonicalized to compare the
16// induction value against the exit value. This turns loops like:
17// 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
18// 2. Any use outside of the loop of an expression derived from the indvar
19// is changed to compute the derived value outside of the loop, eliminating
20// the dependence on the exit value of the induction variable. If the only
21// purpose of the loop is to compute the exit value of some derived
22// expression, this transformation will make the loop dead.
23//
24//===----------------------------------------------------------------------===//
25
27#include "ScalarOptions.h"
28#include "llvm/ADT/APFloat.h"
29#include "llvm/ADT/ArrayRef.h"
30#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/Statistic.h"
45#include "llvm/IR/BasicBlock.h"
46#include "llvm/IR/Constant.h"
48#include "llvm/IR/Constants.h"
49#include "llvm/IR/DataLayout.h"
51#include "llvm/IR/Dominators.h"
52#include "llvm/IR/Function.h"
53#include "llvm/IR/IRBuilder.h"
54#include "llvm/IR/InstrTypes.h"
55#include "llvm/IR/Instruction.h"
57#include "llvm/IR/Intrinsics.h"
58#include "llvm/IR/PassManager.h"
60#include "llvm/IR/Type.h"
61#include "llvm/IR/Use.h"
62#include "llvm/IR/User.h"
63#include "llvm/IR/Value.h"
64#include "llvm/IR/ValueHandle.h"
66#include "llvm/Support/Debug.h"
75#include <cassert>
76#include <cstdint>
77#include <utility>
78
79using namespace llvm;
80using namespace PatternMatch;
81using namespace SCEVPatternMatch;
82
83#define DEBUG_TYPE "indvars"
84
85STATISTIC(NumWidened , "Number of indvars widened");
86STATISTIC(NumReplaced , "Number of exit values replaced");
87STATISTIC(NumLFTR , "Number of loop exit tests replaced");
88STATISTIC(NumElimExt , "Number of IV sign/zero extends eliminated");
89STATISTIC(NumElimIV , "Number of congruent IVs eliminated");
90
91namespace {
92
93class IndVarSimplify {
94 const ScalarOptions &Opts;
95 LoopInfo *LI;
97 DominatorTree *DT;
98 const DataLayout &DL;
101 std::unique_ptr<MemorySSAUpdater> MSSAU;
102
104 bool WidenIndVars;
105
106 bool RunUnswitching = false;
107
108 bool handleFloatingPointIV(Loop *L, PHINode *PH);
109 bool rewriteNonIntegerIVs(Loop *L);
110
111 bool simplifyAndExtend(Loop *L, SCEVExpander &Rewriter, LoopInfo *LI);
112 /// Try to improve our exit conditions by converting condition from signed
113 /// to unsigned or rotating computation out of the loop.
114 /// (See inline comment about why this is duplicated from simplifyAndExtend)
115 bool canonicalizeExitCondition(Loop *L);
116 /// Try to eliminate loop exits based on analyzeable exit counts
117 bool optimizeLoopExits(Loop *L, SCEVExpander &Rewriter);
118 /// Try to form loop invariant tests for loop exits by changing how many
119 /// iterations of the loop run when that is unobservable.
120 bool predicateLoopExits(Loop *L, SCEVExpander &Rewriter);
121
122 bool rewriteFirstIterationLoopExitValues(Loop *L);
123
124 bool linearFunctionTestReplace(Loop *L, BasicBlock *ExitingBB,
125 const SCEV *ExitCount,
126 PHINode *IndVar, SCEVExpander &Rewriter);
127
128 bool sinkUnusedInvariants(Loop *L);
129
130public:
131 IndVarSimplify(const ScalarOptions &Opts, LoopInfo *LI, ScalarEvolution *SE,
132 DominatorTree *DT, const DataLayout &DL,
134 MemorySSA *MSSA, bool WidenIndVars)
135 : Opts(Opts), LI(LI), SE(SE), DT(DT), DL(DL), TLI(TLI), TTI(TTI),
136 WidenIndVars(WidenIndVars) {
137 if (MSSA)
138 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
139 }
140
141 bool run(Loop *L);
142
143 bool runUnswitching() const { return RunUnswitching; }
144};
145
146} // end anonymous namespace
147
148//===----------------------------------------------------------------------===//
149// rewriteNonIntegerIVs and helpers. Prefer integer IVs.
150//===----------------------------------------------------------------------===//
151
152/// Convert APF to an integer, if possible.
153static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
154 bool isExact = false;
155 // See if we can convert this to an int64_t
156 uint64_t UIntVal;
157 if (APF.convertToInteger(MutableArrayRef(UIntVal), 64, true,
158 APFloat::rmTowardZero, &isExact) != APFloat::opOK ||
159 !isExact)
160 return false;
161 IntVal = UIntVal;
162 return true;
163}
164
165/// Ensure we stay within the bounds of fp values that can be represented as
166/// integers without gaps, which are 2^24 and 2^53 for IEEE-754 single and
167/// double precision respectively (both on negative and positive side).
168static bool isRepresentableAsExactInteger(const APFloat &FPVal,
169 int64_t IntVal) {
170 const auto &FltSema = FPVal.getSemantics();
171 if (!APFloat::isIEEELikeFP(FltSema))
172 return false;
173 return isUIntN(APFloat::semanticsPrecision(FltSema), AbsoluteValue(IntVal));
174}
175
176/// Represents a floating-point induction variable pattern that may be
177/// convertible to integer form.
191
192/// Represents the integer values for a converted IV.
199
201 switch (FPPred) {
204 return CmpInst::ICMP_EQ;
207 return CmpInst::ICMP_NE;
210 return CmpInst::ICMP_SGT;
213 return CmpInst::ICMP_SGE;
216 return CmpInst::ICMP_SLT;
219 return CmpInst::ICMP_SLE;
220 default:
222 }
223}
224
225/// Analyze a PN to determine whether it represents a simple floating-point
226/// induction variable, with constant fp init, increment, and exit values,
227/// whose exit condition is to be evaluated on every iteration of the loop.
228///
229/// Returns a FloatingPointIV struct if matched, std::nullopt otherwise.
230static std::optional<FloatingPointIV>
232 assert(L->getLoopLatch() && "Must be in simplified form.");
233
234 // Identify incoming and backedge for the PN.
235 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
236 unsigned BackEdge = IncomingEdge ^ 1;
237
238 // Check incoming value.
239 auto *InitValueVal = dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
240 if (!InitValueVal)
241 return std::nullopt;
242
243 // Check IV increment. Reject this PN if increment operation is not
244 // an add or increment value can not be represented by an integer.
245 auto *Incr = dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
246 if (!Incr || Incr->getOpcode() != Instruction::FAdd)
247 return std::nullopt;
248
249 // If this is not an add of the PHI with a constantfp, or if the constant fp
250 // is not an integer, bail out.
251 auto *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
252 if (!IncValueVal || Incr->getOperand(0) != PN)
253 return std::nullopt;
254
255 // Check Incr uses. One user is PN and the other user is an exit condition
256 // used by the conditional terminator.
257 // TODO: Should relax this, so as to allow any `fpext` that may occur.
258 if (!Incr->hasNUses(2))
259 return std::nullopt;
260
261 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
262 // only used by a branch, we can't transform it.
263 auto It = llvm::find_if(Incr->users(),
264 [](const User *U) { return isa<FCmpInst>(U); });
265 if (It == Incr->users().end())
266 return std::nullopt;
267
268 FCmpInst *Compare = cast<FCmpInst>(*It);
269 if (!Compare->hasOneUse())
270 return std::nullopt;
271
272 // We need to verify that the branch actually controls the iteration count
273 // of the loop. If not, the new IV can overflow and no one will notice.
274 // The branch block must be in the loop and one of the successors must be out
275 // of the loop.
276 auto *BI = dyn_cast<CondBrInst>(Compare->user_back());
277 if (!BI)
278 return std::nullopt;
279
280 BasicBlock *ExitingBB = BI->getParent();
281 if (!L->contains(ExitingBB) ||
282 (L->contains(BI->getSuccessor(0)) && L->contains(BI->getSuccessor(1))))
283 return std::nullopt;
284
285 // Ensure that the fcmp exit comparison runs on every iteration of the loop,
286 // otherwise the IV may be incremented past the exit value, thus overflowing.
287 if (!DT.dominates(ExitingBB, L->getLoopLatch()))
288 return std::nullopt;
289
290 bool ExitsOnTrue = !L->contains(BI->getSuccessor(0));
291 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
292 // transform it.
293 auto *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
294 if (!ExitValueVal)
295 return std::nullopt;
296
297 return FloatingPointIV(InitValueVal->getValueAPF(),
298 IncValueVal->getValueAPF(),
299 ExitValueVal->getValueAPF(), Compare, ExitsOnTrue);
300}
301
302/// Ensure that the floating-point IV can be converted to a semantics-preserving
303/// signed 32-bit integer IV.
304///
305/// Returns a IntegerIV struct if possible, std::nullopt otherwise.
306static std::optional<IntegerIV>
308 // Convert floating-point predicate to integer.
309 auto NewPred = getIntegerPredicate(FPIV.Compare->getPredicate());
310 if (NewPred == CmpInst::BAD_ICMP_PREDICATE)
311 return std::nullopt;
312
313 // Convert APFloat values to signed integers.
314 int64_t InitValue, IncrValue, ExitValue;
315 if (!ConvertToSInt(FPIV.InitValue, InitValue) ||
316 !ConvertToSInt(FPIV.IncrValue, IncrValue) ||
317 !ConvertToSInt(FPIV.ExitValue, ExitValue))
318 return std::nullopt;
319
320 // Bail out if integers cannot be represented exactly.
321 if (!isRepresentableAsExactInteger(FPIV.InitValue, InitValue) ||
323 return std::nullopt;
324
325 // We convert the floating point induction variable to a signed i32 value if
326 // we can. This is only safe if the comparison will not overflow in a way that
327 // won't be trapped by the integer equivalent operations. Check for this now.
328 // TODO: We could use i64 if it is native and the range requires it.
329
330 // The start/stride/exit values must all fit in signed i32.
331 if (!isInt<32>(InitValue) || !isInt<32>(IncrValue) || !isInt<32>(ExitValue))
332 return std::nullopt;
333
334 // If not actually striding (add x, 0.0), avoid touching the code.
335 if (IncrValue == 0)
336 return std::nullopt;
337
338 // Compute the predicate under which the loop keeps iterating.
339 CmpInst::Predicate ContinuePred =
340 FPIV.ExitsOnTrue ? CmpInst::getInversePredicate(NewPred) : NewPred;
341
342 // Normalize to positive stride.
343 int64_t Start = InitValue, Step = IncrValue, Bound = ExitValue;
344 if (Step < 0) {
345 Start = -Start;
346 Step = -Step;
347 Bound = -Bound;
348 ContinuePred = CmpInst::getSwappedPredicate(ContinuePred);
349 }
350
351 // Start of IV is below the exit value.
352 if (Start >= Bound)
353 return std::nullopt;
354
355 // Compute the last value of the incremented IV.
356 uint64_t Dist = Bound - Start;
357 int64_t Last;
358 switch (ContinuePred) {
360 Last = Start + alignTo(Dist, Step);
361 break;
363 Last = Start + alignTo(Dist + 1, Step);
364 break;
365 case CmpInst::ICMP_NE:
366 // The strided value must exactly land on the exit value.
367 if (Dist % Step != 0)
368 return std::nullopt;
369 Last = Bound;
370 break;
371 case CmpInst::ICMP_EQ:
372 Last = Start + Step == Bound ? Bound + Step : Start + Step;
373 break;
374 default:
375 return std::nullopt;
376 }
377
378 // The integer IV must not overflow before the loop exits.
379 if (!isInt<32>(Last))
380 return std::nullopt;
381
382 return IntegerIV{InitValue, IncrValue, ExitValue, NewPred};
383}
384
385/// Rewrite the floating-point IV as an integer IV.
387 const FloatingPointIV &FPIV,
388 const IntegerIV &IIV,
389 const TargetLibraryInfo *TLI,
390 std::unique_ptr<MemorySSAUpdater> &MSSAU) {
391 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
392 unsigned BackEdge = IncomingEdge ^ 1;
393
394 IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
395 auto *Incr = cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
396 auto *BI = cast<CondBrInst>(FPIV.Compare->user_back());
397
398 LLVM_DEBUG(dbgs() << "INDVARS: Rewriting floating-point IV to integer IV:\n"
399 << " Init: " << IIV.InitValue << "\n"
400 << " Incr: " << IIV.IncrValue << "\n"
401 << " Exit: " << IIV.ExitValue << "\n"
402 << " Pred: " << CmpInst::getPredicateName(IIV.NewPred)
403 << "\n"
404 << " Original PN: " << *PN << "\n");
405
406 // Insert new integer induction variable.
407 PHINode *NewPHI =
408 PHINode::Create(Int32Ty, 2, PN->getName() + ".int", PN->getIterator());
409 NewPHI->addIncoming(ConstantInt::getSigned(Int32Ty, IIV.InitValue),
410 PN->getIncomingBlock(IncomingEdge));
411 NewPHI->setDebugLoc(PN->getDebugLoc());
412
413 Instruction *NewAdd = BinaryOperator::CreateAdd(
414 NewPHI, ConstantInt::getSigned(Int32Ty, IIV.IncrValue),
415 Incr->getName() + ".int", Incr->getIterator());
416 NewAdd->setDebugLoc(Incr->getDebugLoc());
417 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
418
419 ICmpInst *NewCompare = new ICmpInst(
420 BI->getIterator(), IIV.NewPred, NewAdd,
421 ConstantInt::getSigned(Int32Ty, IIV.ExitValue), FPIV.Compare->getName());
422 NewCompare->setDebugLoc(FPIV.Compare->getDebugLoc());
423
424 // In the following deletions, PN may become dead and may be deleted.
425 // Use a WeakTrackingVH to observe whether this happens.
426 WeakTrackingVH WeakPH = PN;
427
428 // Delete the old floating point exit comparison. The branch starts using the
429 // new comparison.
430 NewCompare->takeName(FPIV.Compare);
431 FPIV.Compare->replaceAllUsesWith(NewCompare);
433
434 // Delete the old floating point increment.
435 Incr->replaceAllUsesWith(PoisonValue::get(Incr->getType()));
437
438 // If the FP induction variable still has uses, this is because something else
439 // in the loop uses its value. In order to canonicalize the induction
440 // variable, we chose to eliminate the IV and rewrite it in terms of an
441 // int->fp cast.
442 //
443 // We give preference to sitofp over uitofp because it is faster on most
444 // platforms.
445 if (WeakPH) {
446 Instruction *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
447 PN->getParent()->getFirstInsertionPt());
448 Conv->setDebugLoc(PN->getDebugLoc());
449 PN->replaceAllUsesWith(Conv);
451 }
452}
453
454/// If the loop has a floating induction variable, then insert corresponding
455/// integer induction variable if possible. For example, the following:
456/// for(double i = 0; i < 10000; ++i)
457/// bar(i)
458/// is converted into
459/// for(int i = 0; i < 10000; ++i)
460/// bar((double)i);
461bool IndVarSimplify::handleFloatingPointIV(Loop *L, PHINode *PN) {
462 // See if the PN matches a floating-point IV pattern.
463 auto FPIV = maybeFloatingPointRecurrence(L, PN, *DT);
464 if (!FPIV)
465 return false;
466
467 // Can we safely convert the floating-point values to integer ones?
468 auto IIV = tryConvertToIntegerIV(*FPIV);
469 if (!IIV)
470 return false;
471
472 // Perform the rewriting.
473 canonicalizeToIntegerIV(L, PN, *FPIV, *IIV, TLI, MSSAU);
474 return true;
475}
476
477bool IndVarSimplify::rewriteNonIntegerIVs(Loop *L) {
478 // First step. Check to see if there are any floating-point recurrences.
479 // If there are, change them into integer recurrences, permitting analysis by
480 // the SCEV routines.
481 BasicBlock *Header = L->getHeader();
482
484
485 bool Changed = false;
486 for (WeakTrackingVH &PHI : PHIs)
487 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHI))
488 Changed |= handleFloatingPointIV(L, PN);
489
490 // If the loop previously had floating-point IV, ScalarEvolution
491 // may not have been able to compute a trip count. Now that we've done some
492 // re-writing, the trip count may be computable.
493 if (Changed)
494 SE->forgetLoop(L);
495 return Changed;
496}
497
498//===---------------------------------------------------------------------===//
499// rewriteFirstIterationLoopExitValues: Rewrite loop exit values if we know
500// they will exit at the first iteration.
501//===---------------------------------------------------------------------===//
502
503/// Check to see if this loop has loop invariant conditions which lead to loop
504/// exits. If so, we know that if the exit path is taken, it is at the first
505/// loop iteration. This lets us predict exit values of PHI nodes that live in
506/// loop header.
507bool IndVarSimplify::rewriteFirstIterationLoopExitValues(Loop *L) {
508 // Verify the input to the pass is already in LCSSA form.
509 assert(L->isLCSSAForm(*DT));
510
511 SmallVector<BasicBlock *, 8> ExitBlocks;
512 L->getUniqueExitBlocks(ExitBlocks);
513
514 bool MadeAnyChanges = false;
515 for (auto *ExitBB : ExitBlocks) {
516 // If there are no more PHI nodes in this exit block, then no more
517 // values defined inside the loop are used on this path.
518 for (PHINode &PN : ExitBB->phis()) {
519 for (unsigned IncomingValIdx = 0, E = PN.getNumIncomingValues();
520 IncomingValIdx != E; ++IncomingValIdx) {
521 auto *IncomingBB = PN.getIncomingBlock(IncomingValIdx);
522
523 // Can we prove that the exit must run on the first iteration if it
524 // runs at all? (i.e. early exits are fine for our purposes, but
525 // traces which lead to this exit being taken on the 2nd iteration
526 // aren't.) Note that this is about whether the exit branch is
527 // executed, not about whether it is taken.
528 if (!L->getLoopLatch() ||
529 !DT->dominates(IncomingBB, L->getLoopLatch()))
530 continue;
531
532 // Get condition that leads to the exit path.
533 auto *TermInst = IncomingBB->getTerminator();
534
535 Value *Cond = nullptr;
536 if (auto *BI = dyn_cast<CondBrInst>(TermInst)) {
537 // Must be a conditional branch, otherwise the block
538 // should not be in the loop.
539 Cond = BI->getCondition();
540 } else if (auto *SI = dyn_cast<SwitchInst>(TermInst))
541 Cond = SI->getCondition();
542 else
543 continue;
544
545 if (!L->isLoopInvariant(Cond))
546 continue;
547
548 auto *ExitVal = dyn_cast<PHINode>(PN.getIncomingValue(IncomingValIdx));
549
550 // Only deal with PHIs in the loop header.
551 if (!ExitVal || ExitVal->getParent() != L->getHeader())
552 continue;
553
554 // If ExitVal is a PHI on the loop header, then we know its
555 // value along this exit because the exit can only be taken
556 // on the first iteration.
557 auto *LoopPreheader = L->getLoopPreheader();
558 assert(LoopPreheader && "Invalid loop");
559 int PreheaderIdx = ExitVal->getBasicBlockIndex(LoopPreheader);
560 if (PreheaderIdx != -1) {
561 assert(ExitVal->getParent() == L->getHeader() &&
562 "ExitVal must be in loop header");
563 MadeAnyChanges = true;
564 PN.setIncomingValue(IncomingValIdx,
565 ExitVal->getIncomingValue(PreheaderIdx));
566 SE->forgetValue(&PN);
567 }
568 }
569 }
570 }
571 return MadeAnyChanges;
572}
573
574//===----------------------------------------------------------------------===//
575// IV Widening - Extend the width of an IV to cover its widest uses.
576//===----------------------------------------------------------------------===//
577
578/// Update information about the induction variable that is extended by this
579/// sign or zero extend operation. This is used to determine the final width of
580/// the IV before actually widening it.
581static void visitIVCast(CastInst *Cast, WideIVInfo &WI,
582 ScalarEvolution *SE,
583 const TargetTransformInfo *TTI) {
584 bool IsSigned = Cast->getOpcode() == Instruction::SExt;
585 if (!IsSigned && Cast->getOpcode() != Instruction::ZExt)
586 return;
587
588 Type *Ty = Cast->getType();
589 uint64_t Width = SE->getTypeSizeInBits(Ty);
590 if (!Cast->getDataLayout().isLegalInteger(Width))
591 return;
592
593 // Check that `Cast` actually extends the induction variable (we rely on this
594 // later). This takes care of cases where `Cast` is extending a truncation of
595 // the narrow induction variable, and thus can end up being narrower than the
596 // "narrow" induction variable.
597 uint64_t NarrowIVWidth = SE->getTypeSizeInBits(WI.NarrowIV->getType());
598 if (NarrowIVWidth >= Width)
599 return;
600
601 // Cast is either an sext or zext up to this point.
602 // We should not widen an indvar if arithmetics on the wider indvar are more
603 // expensive than those on the narrower indvar. We check only the cost of ADD
604 // because at least an ADD is required to increment the induction variable. We
605 // could compute more comprehensively the cost of all instructions on the
606 // induction variable when necessary.
608 if (TTI && TTI->getArithmeticInstrCost(Instruction::Add, Ty, CostKind) >
609 TTI->getArithmeticInstrCost(Instruction::Add,
610 Cast->getOperand(0)->getType(),
611 CostKind)) {
612 return;
613 }
614
615 if (!WI.WidestNativeType ||
616 Width > SE->getTypeSizeInBits(WI.WidestNativeType)) {
618 WI.IsSigned = IsSigned;
619 return;
620 }
621
622 // We extend the IV to satisfy the sign of its user(s), or 'signed'
623 // if there are multiple users with both sign- and zero extensions,
624 // in order not to introduce nondeterministic behaviour based on the
625 // unspecified order of a PHI nodes' users-iterator.
626 WI.IsSigned |= IsSigned;
627}
628
629//===----------------------------------------------------------------------===//
630// Live IV Reduction - Minimize IVs live across the loop.
631//===----------------------------------------------------------------------===//
632
633//===----------------------------------------------------------------------===//
634// Simplification of IV users based on SCEV evaluation.
635//===----------------------------------------------------------------------===//
636
637namespace {
638
639class IndVarSimplifyVisitor : public IVVisitor {
640 ScalarEvolution *SE;
641 const TargetTransformInfo *TTI;
642 PHINode *IVPhi;
643
644public:
645 WideIVInfo WI;
646
647 IndVarSimplifyVisitor(PHINode *IV, ScalarEvolution *SCEV,
648 const TargetTransformInfo *TTI,
649 const DominatorTree *DTree)
650 : SE(SCEV), TTI(TTI), IVPhi(IV) {
651 DT = DTree;
652 WI.NarrowIV = IVPhi;
653 }
654
655 // Implement the interface used by simplifyUsersOfIV.
656 void visitCast(CastInst *Cast) override { visitIVCast(Cast, WI, SE, TTI); }
657};
658
659} // end anonymous namespace
660
661/// Iteratively perform simplification on a worklist of IV users. Each
662/// successive simplification may push more users which may themselves be
663/// candidates for simplification.
664///
665/// Sign/Zero extend elimination is interleaved with IV simplification.
666bool IndVarSimplify::simplifyAndExtend(Loop *L,
667 SCEVExpander &Rewriter,
668 LoopInfo *LI) {
670
671 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
672 L->getBlocks()[0]->getModule(), Intrinsic::experimental_guard);
673 bool HasGuards = GuardDecl && !GuardDecl->use_empty();
674
676 llvm::make_pointer_range(L->getHeader()->phis()));
677
678 // Each round of simplification iterates through the SimplifyIVUsers worklist
679 // for all current phis, then determines whether any IVs can be
680 // widened. Widening adds new phis to LoopPhis, inducing another round of
681 // simplification on the wide IVs.
682 bool Changed = false;
683 while (!LoopPhis.empty()) {
684 // Evaluate as many IV expressions as possible before widening any IVs. This
685 // forces SCEV to set no-wrap flags before evaluating sign/zero
686 // extension. The first time SCEV attempts to normalize sign/zero extension,
687 // the result becomes final. So for the most predictable results, we delay
688 // evaluation of sign/zero extend evaluation until needed, and avoid running
689 // other SCEV based analysis prior to simplifyAndExtend.
690 do {
691 PHINode *CurrIV = LoopPhis.pop_back_val();
692
693 // Information about sign/zero extensions of CurrIV.
694 IndVarSimplifyVisitor Visitor(CurrIV, SE, TTI, DT);
695
696 const auto &[C, U] = simplifyUsersOfIV(CurrIV, SE, DT, LI, TTI, DeadInsts,
697 Rewriter, &Visitor);
698
699 Changed |= C;
700 RunUnswitching |= U;
701 if (Visitor.WI.WidestNativeType) {
702 WideIVs.push_back(Visitor.WI);
703 }
704 } while(!LoopPhis.empty());
705
706 // Continue if we disallowed widening.
707 if (!WidenIndVars)
708 continue;
709
710 for (; !WideIVs.empty(); WideIVs.pop_back()) {
711 unsigned ElimExt;
712 unsigned Widened;
713 if (PHINode *WidePhi = createWideIV(
714 WideIVs.back(), LI, SE, Rewriter, DT, DeadInsts, ElimExt, Widened,
715 HasGuards, Opts.indvars_post_increment_ranges)) {
716 NumElimExt += ElimExt;
717 NumWidened += Widened;
718 Changed = true;
719 LoopPhis.push_back(WidePhi);
720 }
721 }
722 }
723 return Changed;
724}
725
726//===----------------------------------------------------------------------===//
727// linearFunctionTestReplace and its kin. Rewrite the loop exit condition.
728//===----------------------------------------------------------------------===//
729
730/// Given an Value which is hoped to be part of an add recurance in the given
731/// loop, return the associated Phi node if so. Otherwise, return null. Note
732/// that this is less general than SCEVs AddRec checking.
735 if (!IncI)
736 return nullptr;
737
738 switch (IncI->getOpcode()) {
739 case Instruction::Add:
740 case Instruction::Sub:
741 break;
742 case Instruction::GetElementPtr:
743 // An IV counter must preserve its type.
744 if (IncI->getNumOperands() == 2)
745 break;
746 [[fallthrough]];
747 default:
748 return nullptr;
749 }
750
751 PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0));
752 if (Phi && Phi->getParent() == L->getHeader()) {
753 if (L->isLoopInvariant(IncI->getOperand(1)))
754 return Phi;
755 return nullptr;
756 }
757 if (IncI->getOpcode() == Instruction::GetElementPtr)
758 return nullptr;
759
760 // Allow add/sub to be commuted.
761 Phi = dyn_cast<PHINode>(IncI->getOperand(1));
762 if (Phi && Phi->getParent() == L->getHeader()) {
763 if (L->isLoopInvariant(IncI->getOperand(0)))
764 return Phi;
765 }
766 return nullptr;
767}
768
769/// Whether the current loop exit test is based on this value. Currently this
770/// is limited to a direct use in the loop condition.
771static bool isLoopExitTestBasedOn(Value *V, BasicBlock *ExitingBB) {
772 CondBrInst *BI = cast<CondBrInst>(ExitingBB->getTerminator());
774 // TODO: Allow non-icmp loop test.
775 if (!ICmp)
776 return false;
777
778 // TODO: Allow indirect use.
779 return ICmp->getOperand(0) == V || ICmp->getOperand(1) == V;
780}
781
782/// linearFunctionTestReplace policy. Return true unless we can show that the
783/// current exit test is already sufficiently canonical.
784static bool needsLFTR(Loop *L, BasicBlock *ExitingBB) {
785 assert(L->getLoopLatch() && "Must be in simplified form");
786
787 // Avoid converting a constant or loop invariant test back to a runtime
788 // test. This is critical for when SCEV's cached ExitCount is less precise
789 // than the current IR (such as after we've proven a particular exit is
790 // actually dead and thus the BE count never reaches our ExitCount.)
791 CondBrInst *BI = cast<CondBrInst>(ExitingBB->getTerminator());
792 if (L->isLoopInvariant(BI->getCondition()))
793 return false;
794
795 // Do LFTR to simplify the exit condition to an ICMP.
797 if (!Cond)
798 return true;
799
800 // Do LFTR to simplify the exit ICMP to EQ/NE
801 ICmpInst::Predicate Pred = Cond->getPredicate();
803 return true;
804
805 // Look for a loop invariant RHS
806 Value *LHS = Cond->getOperand(0);
807 Value *RHS = Cond->getOperand(1);
808 if (!L->isLoopInvariant(RHS)) {
809 if (!L->isLoopInvariant(LHS))
810 return true;
811 std::swap(LHS, RHS);
812 }
813 // Look for a simple IV counter LHS
815 if (!Phi)
816 Phi = getLoopPhiForCounter(LHS, L);
817
818 if (!Phi)
819 return true;
820
821 // Do LFTR if PHI node is defined in the loop, but is *not* a counter.
822 int Idx = Phi->getBasicBlockIndex(L->getLoopLatch());
823 if (Idx < 0)
824 return true;
825
826 // Do LFTR if the exit condition's IV is *not* a simple counter.
827 Value *IncV = Phi->getIncomingValue(Idx);
828 return Phi != getLoopPhiForCounter(IncV, L);
829}
830
831/// Recursive helper for hasConcreteDef(). Unfortunately, this currently boils
832/// down to checking that all operands are constant and listing instructions
833/// that may hide undef.
835 unsigned Depth) {
836 if (isa<Constant>(V))
837 return !isa<UndefValue>(V);
838
839 if (Depth >= 6)
840 return false;
841
842 // Conservatively handle non-constant non-instructions. For example, Arguments
843 // may be undef.
845 if (!I)
846 return false;
847
848 // Load and return values may be undef.
849 if(I->mayReadFromMemory() || isa<CallInst>(I) || isa<InvokeInst>(I))
850 return false;
851
852 // Optimistically handle other instructions.
853 for (Value *Op : I->operands()) {
854 if (!Visited.insert(Op).second)
855 continue;
856 if (!hasConcreteDefImpl(Op, Visited, Depth+1))
857 return false;
858 }
859 return true;
860}
861
862/// Return true if the given value is concrete. We must prove that undef can
863/// never reach it.
864///
865/// TODO: If we decide that this is a good approach to checking for undef, we
866/// may factor it into a common location.
867static bool hasConcreteDef(Value *V) {
869 Visited.insert(V);
870 return hasConcreteDefImpl(V, Visited, 0);
871}
872
873/// Return true if the given phi is a "counter" in L. A counter is an
874/// add recurance (of integer or pointer type) with an arbitrary start, and a
875/// step of 1. Note that L must have exactly one latch.
876static bool isLoopCounter(PHINode* Phi, Loop *L,
877 ScalarEvolution *SE) {
878 assert(Phi->getParent() == L->getHeader());
879 assert(L->getLoopLatch());
880
881 if (!SE->isSCEVable(Phi->getType()))
882 return false;
883
884 const SCEV *S = SE->getSCEV(Phi);
886 return false;
887
888 int LatchIdx = Phi->getBasicBlockIndex(L->getLoopLatch());
889 Value *IncV = Phi->getIncomingValue(LatchIdx);
890 return (getLoopPhiForCounter(IncV, L) == Phi &&
891 isa<SCEVAddRecExpr>(SE->getSCEV(IncV)));
892}
893
894/// Search the loop header for a loop counter (anadd rec w/step of one)
895/// suitable for use by LFTR. If multiple counters are available, select the
896/// "best" one based profitable heuristics.
897///
898/// BECount may be an i8* pointer type. The pointer difference is already
899/// valid count without scaling the address stride, so it remains a pointer
900/// expression as far as SCEV is concerned.
901static PHINode *FindLoopCounter(Loop *L, BasicBlock *ExitingBB,
902 const SCEV *BECount,
904 uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType());
905
906 Value *Cond = cast<CondBrInst>(ExitingBB->getTerminator())->getCondition();
907
908 // Loop over all of the PHI nodes, looking for a simple counter.
909 PHINode *BestPhi = nullptr;
910 const SCEV *BestInit = nullptr;
911 BasicBlock *LatchBlock = L->getLoopLatch();
912 assert(LatchBlock && "Must be in simplified form");
913 const DataLayout &DL = L->getHeader()->getDataLayout();
914
915 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
916 PHINode *Phi = cast<PHINode>(I);
917 if (!isLoopCounter(Phi, L, SE))
918 continue;
919
920 const auto *AR = cast<SCEVAddRecExpr>(SE->getSCEV(Phi));
921
922 // AR may be a pointer type, while BECount is an integer type.
923 // AR may be wider than BECount. With eq/ne tests overflow is immaterial.
924 // AR may not be a narrower type, or we may never exit.
925 uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType());
926 if (PhiWidth < BCWidth || !DL.isLegalInteger(PhiWidth))
927 continue;
928
929 // Avoid reusing a potentially undef value to compute other values that may
930 // have originally had a concrete definition.
931 if (!hasConcreteDef(Phi)) {
932 // We explicitly allow unknown phis as long as they are already used by
933 // the loop exit test. This is legal since performing LFTR could not
934 // increase the number of undef users.
935 Value *IncPhi = Phi->getIncomingValueForBlock(LatchBlock);
936 if (!isLoopExitTestBasedOn(Phi, ExitingBB) &&
937 !isLoopExitTestBasedOn(IncPhi, ExitingBB))
938 continue;
939 }
940
941 // Avoid introducing undefined behavior due to poison which didn't exist in
942 // the original program. (Annoyingly, the rules for poison and undef
943 // propagation are distinct, so this does NOT cover the undef case above.)
944 // We have to ensure that we don't introduce UB by introducing a use on an
945 // iteration where said IV produces poison. Our strategy here differs for
946 // pointers and integer IVs. For integers, we strip and reinfer as needed,
947 // see code in linearFunctionTestReplace. For pointers, we restrict
948 // transforms as there is no good way to reinfer inbounds once lost.
949 if (!Phi->getType()->isIntegerTy() &&
950 !mustExecuteUBIfPoisonOnPathTo(Phi, ExitingBB->getTerminator(), DT))
951 continue;
952
953 const SCEV *Init = AR->getStart();
954
955 if (BestPhi && !isAlmostDeadIV(BestPhi, LatchBlock, Cond)) {
956 // Don't force a live loop counter if another IV can be used.
957 if (isAlmostDeadIV(Phi, LatchBlock, Cond))
958 continue;
959
960 // Prefer to count-from-zero. This is a more "canonical" counter form. It
961 // also prefers integer to pointer IVs.
962 if (BestInit->isZero() != Init->isZero()) {
963 if (BestInit->isZero())
964 continue;
965 }
966 // If two IVs both count from zero or both count from nonzero then the
967 // narrower is likely a dead phi that has been widened. Use the wider phi
968 // to allow the other to be eliminated.
969 else if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType()))
970 continue;
971 }
972 BestPhi = Phi;
973 BestInit = Init;
974 }
975 return BestPhi;
976}
977
978/// Insert an IR expression which computes the value held by the IV IndVar
979/// (which must be an loop counter w/unit stride) after the backedge of loop L
980/// is taken ExitCount times.
981static Value *genLoopLimit(PHINode *IndVar, BasicBlock *ExitingBB,
982 const SCEV *ExitCount, bool UsePostInc, Loop *L,
983 SCEVExpander &Rewriter, ScalarEvolution *SE) {
984 assert(isLoopCounter(IndVar, L, SE));
985 assert(ExitCount->getType()->isIntegerTy() && "exit count must be integer");
986 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
987 assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride");
988
989 // For integer IVs, truncate the IV before computing the limit unless we
990 // know apriori that the limit must be a constant when evaluated in the
991 // bitwidth of the IV. We prefer (potentially) keeping a truncate of the
992 // IV in the loop over a (potentially) expensive expansion of the widened
993 // exit count add(zext(add)) expression.
994 if (IndVar->getType()->isIntegerTy() &&
995 SE->getTypeSizeInBits(AR->getType()) >
996 SE->getTypeSizeInBits(ExitCount->getType())) {
997 const SCEV *IVInit = AR->getStart();
998 if (!isa<SCEVConstant>(IVInit) || !isa<SCEVConstant>(ExitCount)) {
999 const SCEV *TruncExpr = SE->getTruncateExpr(AR, ExitCount->getType());
1000
1001 // The following bailout is necessary due to the interaction with
1002 // the depth limit in SCEV analysis.
1003 if (!isa<SCEVAddRecExpr>(TruncExpr))
1004 return nullptr;
1005 AR = cast<SCEVAddRecExpr>(TruncExpr);
1006 }
1007 }
1008
1009 const SCEVAddRecExpr *ARBase = UsePostInc ? AR->getPostIncExpr(*SE) : AR;
1010 const SCEV *IVLimit = ARBase->evaluateAtIteration(ExitCount, *SE);
1011 assert(SE->isLoopInvariant(IVLimit, L) &&
1012 "Computed iteration count is not loop invariant!");
1013 return Rewriter.expandCodeFor(IVLimit, ARBase->getType(),
1014 ExitingBB->getTerminator());
1015}
1016
1017/// This method rewrites the exit condition of the loop to be a canonical !=
1018/// comparison against the incremented loop induction variable. This pass is
1019/// able to rewrite the exit tests of any loop where the SCEV analysis can
1020/// determine a loop-invariant trip count of the loop, which is actually a much
1021/// broader range than just linear tests.
1022bool IndVarSimplify::
1023linearFunctionTestReplace(Loop *L, BasicBlock *ExitingBB,
1024 const SCEV *ExitCount,
1025 PHINode *IndVar, SCEVExpander &Rewriter) {
1026 assert(L->getLoopLatch() && "Loop no longer in simplified form?");
1027 assert(isLoopCounter(IndVar, L, SE));
1028 Instruction * const IncVar =
1029 cast<Instruction>(IndVar->getIncomingValueForBlock(L->getLoopLatch()));
1030
1031 // Initialize CmpIndVar to the preincremented IV.
1032 Value *CmpIndVar = IndVar;
1033 bool UsePostInc = false;
1034
1035 // If the exiting block is the same as the backedge block, we prefer to
1036 // compare against the post-incremented value, otherwise we must compare
1037 // against the preincremented value.
1038 if (ExitingBB == L->getLoopLatch()) {
1039 // For pointer IVs, we chose to not strip inbounds which requires us not
1040 // to add a potentially UB introducing use. We need to either a) show
1041 // the loop test we're modifying is already in post-inc form, or b) show
1042 // that adding a use must not introduce UB.
1043 bool SafeToPostInc =
1044 IndVar->getType()->isIntegerTy() ||
1045 isLoopExitTestBasedOn(IncVar, ExitingBB) ||
1046 mustExecuteUBIfPoisonOnPathTo(IncVar, ExitingBB->getTerminator(), DT);
1047 if (SafeToPostInc) {
1048 UsePostInc = true;
1049 CmpIndVar = IncVar;
1050 }
1051 }
1052
1053 Value *ExitCnt =
1054 genLoopLimit(IndVar, ExitingBB, ExitCount, UsePostInc, L, Rewriter, SE);
1055 if (!ExitCnt)
1056 return false;
1057
1058 assert(ExitCnt->getType()->isPointerTy() ==
1059 IndVar->getType()->isPointerTy() &&
1060 "genLoopLimit missed a cast");
1061
1062 // It may be necessary to drop nowrap flags on the incrementing instruction
1063 // if either LFTR moves from a pre-inc check to a post-inc check (in which
1064 // case the increment might have previously been poison on the last iteration
1065 // only) or if LFTR switches to a different IV that was previously dynamically
1066 // dead (and as such may be arbitrarily poison). We remove any nowrap flags
1067 // that SCEV didn't infer for the post-inc addrec (even if we use a pre-inc
1068 // check), because the pre-inc addrec flags may be adopted from the original
1069 // instruction, while SCEV has to explicitly prove the post-inc nowrap flags.
1070 // TODO: This handling is inaccurate for one case: If we switch to a
1071 // dynamically dead IV that wraps on the first loop iteration only, which is
1072 // not covered by the post-inc addrec. (If the new IV was not dynamically
1073 // dead, it could not be poison on the first iteration in the first place.)
1074 if (auto *BO = dyn_cast<BinaryOperator>(IncVar)) {
1075 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IncVar));
1076 if (BO->hasNoUnsignedWrap())
1077 BO->setHasNoUnsignedWrap(AR->hasNoUnsignedWrap());
1078 if (BO->hasNoSignedWrap())
1079 BO->setHasNoSignedWrap(AR->hasNoSignedWrap());
1080 }
1081
1082 // Insert a new icmp_ne or icmp_eq instruction before the branch.
1083 CondBrInst *BI = cast<CondBrInst>(ExitingBB->getTerminator());
1084 ICmpInst::Predicate P;
1085 if (L->contains(BI->getSuccessor(0)))
1086 P = ICmpInst::ICMP_NE;
1087 else
1088 P = ICmpInst::ICMP_EQ;
1089
1090 IRBuilder<> Builder(BI);
1091
1092 // The new loop exit condition should reuse the debug location of the
1093 // original loop exit condition.
1094 if (auto *Cond = dyn_cast<Instruction>(BI->getCondition()))
1095 Builder.SetCurrentDebugLocation(Cond->getDebugLoc());
1096
1097 // For integer IVs, if we evaluated the limit in the narrower bitwidth to
1098 // avoid the expensive expansion of the limit expression in the wider type,
1099 // emit a truncate to narrow the IV to the ExitCount type. This is safe
1100 // since we know (from the exit count bitwidth), that we can't self-wrap in
1101 // the narrower type.
1102 unsigned CmpIndVarSize = SE->getTypeSizeInBits(CmpIndVar->getType());
1103 unsigned ExitCntSize = SE->getTypeSizeInBits(ExitCnt->getType());
1104 if (CmpIndVarSize > ExitCntSize) {
1105 assert(!CmpIndVar->getType()->isPointerTy() &&
1106 !ExitCnt->getType()->isPointerTy());
1107
1108 // Before resorting to actually inserting the truncate, use the same
1109 // reasoning as from SimplifyIndvar::eliminateTrunc to see if we can extend
1110 // the other side of the comparison instead. We still evaluate the limit
1111 // in the narrower bitwidth, we just prefer a zext/sext outside the loop to
1112 // a truncate within in.
1113 bool Extended = false;
1114 const SCEV *IV = SE->getSCEV(CmpIndVar);
1115 const SCEV *TruncatedIV = SE->getTruncateExpr(IV, ExitCnt->getType());
1116 const SCEV *ZExtTrunc =
1117 SE->getZeroExtendExpr(TruncatedIV, CmpIndVar->getType());
1118
1119 if (ZExtTrunc == IV) {
1120 Extended = true;
1121 ExitCnt = Builder.CreateZExt(ExitCnt, IndVar->getType(),
1122 "wide.trip.count");
1123 } else {
1124 const SCEV *SExtTrunc =
1125 SE->getSignExtendExpr(TruncatedIV, CmpIndVar->getType());
1126 if (SExtTrunc == IV) {
1127 Extended = true;
1128 ExitCnt = Builder.CreateSExt(ExitCnt, IndVar->getType(),
1129 "wide.trip.count");
1130 }
1131 }
1132
1133 if (Extended) {
1134 bool Discard;
1135 L->makeLoopInvariant(ExitCnt, Discard);
1136 } else
1137 CmpIndVar = Builder.CreateTrunc(CmpIndVar, ExitCnt->getType(),
1138 "lftr.wideiv");
1139 }
1140 LLVM_DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
1141 << " LHS:" << *CmpIndVar << '\n'
1142 << " op:\t" << (P == ICmpInst::ICMP_NE ? "!=" : "==")
1143 << "\n"
1144 << " RHS:\t" << *ExitCnt << "\n"
1145 << "ExitCount:\t" << *ExitCount << "\n"
1146 << " was: " << *BI->getCondition() << "\n");
1147
1148 Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond");
1149 Value *OrigCond = BI->getCondition();
1150 // It's tempting to use replaceAllUsesWith here to fully replace the old
1151 // comparison, but that's not immediately safe, since users of the old
1152 // comparison may not be dominated by the new comparison. Instead, just
1153 // update the branch to use the new comparison; in the common case this
1154 // will make old comparison dead.
1155 BI->setCondition(Cond);
1156 DeadInsts.emplace_back(OrigCond);
1157
1158 ++NumLFTR;
1159 return true;
1160}
1161
1162//===----------------------------------------------------------------------===//
1163// sinkUnusedInvariants. A late subpass to cleanup loop preheaders.
1164//===----------------------------------------------------------------------===//
1165
1166/// If there's a single exit block, sink any loop-invariant values that
1167/// were defined in the preheader but not used inside the loop into the
1168/// exit block to reduce register pressure in the loop.
1169bool IndVarSimplify::sinkUnusedInvariants(Loop *L) {
1170 BasicBlock *ExitBlock = L->getExitBlock();
1171 if (!ExitBlock) return false;
1172
1173 BasicBlock *Preheader = L->getLoopPreheader();
1174 if (!Preheader) return false;
1175
1176 bool MadeAnyChanges = false;
1177 SmallVector<Value *, 16> SunkInsts;
1178 for (Instruction &I : llvm::make_early_inc_range(llvm::reverse(*Preheader))) {
1179
1180 // Skip BB Terminator.
1181 if (Preheader->getTerminator() == &I)
1182 continue;
1183
1184 // New instructions were inserted at the end of the preheader.
1185 if (isa<PHINode>(I))
1186 break;
1187
1188 // Don't move instructions which might have side effects, since the side
1189 // effects need to complete before instructions inside the loop. Also don't
1190 // move instructions which might read memory, since the loop may modify
1191 // memory. Note that it's okay if the instruction might have undefined
1192 // behavior: LoopSimplify guarantees that the preheader dominates the exit
1193 // block.
1194 if (I.mayHaveSideEffects() || I.mayReadFromMemory())
1195 continue;
1196
1197 // Don't sink convergent calls. Not every thread that executes the
1198 // preheader necessarily reaches the exit block (e.g. a thread may be
1199 // terminated inside the loop), so sinking could change the set of threads
1200 // that execute the call together.
1201 if (auto *CI = dyn_cast<CallInst>(&I); CI && CI->isConvergent())
1202 continue;
1203
1204 // Skip eh pad instructions.
1205 if (I.isEHPad())
1206 continue;
1207
1208 // Don't sink alloca: we never want to sink static alloca's out of the
1209 // entry block, and correctly sinking dynamic alloca's requires
1210 // checks for stacksave/stackrestore intrinsics.
1211 // FIXME: Refactor this check somehow?
1212 if (isa<AllocaInst>(&I))
1213 continue;
1214
1215 // Determine if there is a use in or before the loop (direct or
1216 // otherwise).
1217 bool UsedInLoop = false;
1218 for (Use &U : I.uses()) {
1219 Instruction *User = cast<Instruction>(U.getUser());
1220 BasicBlock *UseBB = User->getParent();
1221 if (PHINode *P = dyn_cast<PHINode>(User)) {
1222 unsigned i =
1224 UseBB = P->getIncomingBlock(i);
1225 }
1226 if (UseBB == Preheader || L->contains(UseBB)) {
1227 UsedInLoop = true;
1228 break;
1229 }
1230 }
1231
1232 // If there is, the def must remain in the preheader.
1233 if (UsedInLoop)
1234 continue;
1235
1236 // Otherwise, sink it to the exit block.
1237 I.moveBefore(ExitBlock->getFirstInsertionPt());
1238 SunkInsts.push_back(&I);
1239 MadeAnyChanges = true;
1240 }
1241
1242 if (!SunkInsts.empty())
1243 SE->forgetValues(SunkInsts);
1244
1245 return MadeAnyChanges;
1246}
1247
1248static void replaceExitCond(CondBrInst *BI, Value *NewCond,
1250 auto *OldCond = BI->getCondition();
1251 LLVM_DEBUG(dbgs() << "Replacing condition of loop-exiting branch " << *BI
1252 << " with " << *NewCond << "\n");
1253 BI->setCondition(NewCond);
1254 if (OldCond->use_empty())
1255 DeadInsts.emplace_back(OldCond);
1256}
1257
1258static Constant *createFoldedExitCond(const Loop *L, BasicBlock *ExitingBB,
1259 bool IsTaken) {
1260 CondBrInst *BI = cast<CondBrInst>(ExitingBB->getTerminator());
1261 bool ExitIfTrue = !L->contains(*succ_begin(ExitingBB));
1262 auto *OldCond = BI->getCondition();
1263 return ConstantInt::get(OldCond->getType(),
1264 IsTaken ? ExitIfTrue : !ExitIfTrue);
1265}
1266
1267static void foldExit(const Loop *L, BasicBlock *ExitingBB, bool IsTaken,
1269 CondBrInst *BI = cast<CondBrInst>(ExitingBB->getTerminator());
1270 auto *NewCond = createFoldedExitCond(L, ExitingBB, IsTaken);
1271 replaceExitCond(BI, NewCond, DeadInsts);
1272}
1273
1275 LoopInfo *LI, Loop *L, SmallVectorImpl<WeakTrackingVH> &DeadInsts,
1276 ScalarEvolution &SE) {
1277 assert(L->isLoopSimplifyForm() && "Should only do it in simplify form!");
1278 auto *LoopPreheader = L->getLoopPreheader();
1279 auto *LoopHeader = L->getHeader();
1281 for (auto &PN : LoopHeader->phis()) {
1282 auto *PreheaderIncoming = PN.getIncomingValueForBlock(LoopPreheader);
1283 for (Instruction *U : PN.users())
1284 Worklist.push_back(U);
1285 SE.forgetValue(&PN);
1286 PN.replaceAllUsesWith(PreheaderIncoming);
1287 DeadInsts.emplace_back(&PN);
1288 }
1289
1290 // Replacing with the preheader value will often allow IV users to simplify
1291 // (especially if the preheader value is a constant).
1293 while (!Worklist.empty()) {
1294 auto *I = cast<Instruction>(Worklist.pop_back_val());
1295 if (!Visited.insert(I).second)
1296 continue;
1297
1298 // Don't simplify instructions outside the loop.
1299 if (!L->contains(I))
1300 continue;
1301
1302 Value *Res = simplifyInstruction(I, I->getDataLayout());
1303 if (Res && LI->replacementPreservesLCSSAForm(I, Res)) {
1304 for (Instruction *U : I->users())
1305 Worklist.push_back(U);
1306 I->replaceAllUsesWith(Res);
1307 DeadInsts.emplace_back(I);
1308 }
1309 }
1310}
1311
1312static Value *
1315 SCEVExpander &Rewriter) {
1316 ICmpInst::Predicate InvariantPred = LIP.Pred;
1317 BasicBlock *Preheader = L->getLoopPreheader();
1318 assert(Preheader && "Preheader doesn't exist");
1319 Rewriter.setInsertPoint(Preheader->getTerminator());
1320 auto *LHSV = Rewriter.expandCodeFor(LIP.LHS);
1321 auto *RHSV = Rewriter.expandCodeFor(LIP.RHS);
1322 bool ExitIfTrue = !L->contains(*succ_begin(ExitingBB));
1323 if (ExitIfTrue)
1324 InvariantPred = ICmpInst::getInversePredicate(InvariantPred);
1325 IRBuilder<> Builder(Preheader->getTerminator());
1326 CondBrInst *BI = cast<CondBrInst>(ExitingBB->getTerminator());
1327 return Builder.CreateICmp(InvariantPred, LHSV, RHSV,
1328 BI->getCondition()->getName());
1329}
1330
1331static std::optional<Value *>
1332createReplacement(ICmpInst *ICmp, const Loop *L, BasicBlock *ExitingBB,
1333 const SCEV *MaxIter, bool Inverted, bool SkipLastIter,
1334 ScalarEvolution *SE, SCEVExpander &Rewriter) {
1336 Value *LHS = ICmp->getOperand(0);
1337 Value *RHS = ICmp->getOperand(1);
1338
1339 // 'LHS pred RHS' should now mean that we stay in loop.
1340 auto *BI = cast<CondBrInst>(ExitingBB->getTerminator());
1341 if (Inverted)
1343
1344 const SCEV *LHSS = SE->getSCEVAtScope(LHS, L);
1345 const SCEV *RHSS = SE->getSCEVAtScope(RHS, L);
1346 // Can we prove it to be trivially true or false?
1347 if (auto EV = SE->evaluatePredicateAt(Pred, LHSS, RHSS, BI))
1348 return createFoldedExitCond(L, ExitingBB, /*IsTaken*/ !*EV);
1349
1350 auto *ARTy = LHSS->getType();
1351 auto *MaxIterTy = MaxIter->getType();
1352 // If possible, adjust types.
1353 if (SE->getTypeSizeInBits(ARTy) > SE->getTypeSizeInBits(MaxIterTy))
1354 MaxIter = SE->getZeroExtendExpr(MaxIter, ARTy);
1355 else if (SE->getTypeSizeInBits(ARTy) < SE->getTypeSizeInBits(MaxIterTy)) {
1356 const SCEV *MinusOne = SE->getMinusOne(ARTy);
1357 const SCEV *MaxAllowedIter = SE->getZeroExtendExpr(MinusOne, MaxIterTy);
1358 if (SE->isKnownPredicateAt(ICmpInst::ICMP_ULE, MaxIter, MaxAllowedIter, BI))
1359 MaxIter = SE->getTruncateExpr(MaxIter, ARTy);
1360 }
1361
1362 if (SkipLastIter) {
1363 // Semantically skip last iter is "subtract 1, do not bother about unsigned
1364 // wrap". getLoopInvariantExitCondDuringFirstIterations knows how to deal
1365 // with umin in a smart way, but umin(a, b) - 1 will likely not simplify.
1366 // So we manually construct umin(a - 1, b - 1).
1367 SmallVector<SCEVUse, 4> Elements;
1368 if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter)) {
1369 for (SCEVUse Op : UMin->operands())
1370 Elements.push_back(SE->getMinusSCEV(Op, SE->getOne(Op->getType())));
1371 MaxIter = SE->getUMinFromMismatchedTypes(Elements);
1372 } else
1373 MaxIter = SE->getMinusSCEV(MaxIter, SE->getOne(MaxIter->getType()));
1374 }
1375
1376 // Check if there is a loop-invariant predicate equivalent to our check.
1377 auto LIP = SE->getLoopInvariantExitCondDuringFirstIterations(Pred, LHSS, RHSS,
1378 L, BI, MaxIter);
1379 if (!LIP)
1380 return std::nullopt;
1381
1382 // Can we prove it to be trivially true?
1383 if (SE->isKnownPredicateAt(LIP->Pred, LIP->LHS, LIP->RHS, BI))
1384 return createFoldedExitCond(L, ExitingBB, /*IsTaken*/ false);
1385 else
1386 return createInvariantCond(L, ExitingBB, *LIP, Rewriter);
1387}
1388
1390 const Loop *L, CondBrInst *BI, BasicBlock *ExitingBB, const SCEV *MaxIter,
1391 bool SkipLastIter, ScalarEvolution *SE, SCEVExpander &Rewriter,
1393 assert(
1394 (L->contains(BI->getSuccessor(0)) != L->contains(BI->getSuccessor(1))) &&
1395 "Not a loop exit!");
1396
1397 // For branch that stays in loop by TRUE condition, go through AND. For branch
1398 // that stays in loop by FALSE condition, go through OR. Both gives the
1399 // similar logic: "stay in loop iff all conditions are true(false)".
1400 bool Inverted = L->contains(BI->getSuccessor(1));
1401 SmallVector<ICmpInst *, 4> LeafConditions;
1402 SmallVector<Value *, 4> Worklist;
1404 Value *OldCond = BI->getCondition();
1405 Visited.insert(OldCond);
1406 Worklist.push_back(OldCond);
1407
1408 auto GoThrough = [&](Value *V) {
1409 Value *LHS = nullptr, *RHS = nullptr;
1410 if (Inverted) {
1412 return false;
1413 } else {
1415 return false;
1416 }
1417 if (Visited.insert(LHS).second)
1418 Worklist.push_back(LHS);
1419 if (Visited.insert(RHS).second)
1420 Worklist.push_back(RHS);
1421 return true;
1422 };
1423
1424 do {
1425 Value *Curr = Worklist.pop_back_val();
1426 // Go through AND/OR conditions. Collect leaf ICMPs. We only care about
1427 // those with one use, to avoid instruction duplication.
1428 if (Curr->hasOneUse())
1429 if (!GoThrough(Curr))
1430 if (auto *ICmp = dyn_cast<ICmpInst>(Curr))
1431 LeafConditions.push_back(ICmp);
1432 } while (!Worklist.empty());
1433
1434 // If the current basic block has the same exit count as the whole loop, and
1435 // it consists of multiple icmp's, try to collect all icmp's that give exact
1436 // same exit count. For all other icmp's, we could use one less iteration,
1437 // because their value on the last iteration doesn't really matter.
1438 SmallPtrSet<ICmpInst *, 4> ICmpsFailingOnLastIter;
1439 if (!SkipLastIter && LeafConditions.size() > 1 &&
1440 SE->getExitCount(L, ExitingBB,
1442 MaxIter)
1443 for (auto *ICmp : LeafConditions) {
1444 auto EL = SE->computeExitLimitFromCond(L, ICmp, Inverted,
1445 /*ControlsExit*/ false);
1446 const SCEV *ExitMax = EL.SymbolicMaxNotTaken;
1447 if (isa<SCEVCouldNotCompute>(ExitMax))
1448 continue;
1449 // They could be of different types (specifically this happens after
1450 // IV widening).
1451 auto *WiderType =
1452 SE->getWiderType(ExitMax->getType(), MaxIter->getType());
1453 const SCEV *WideExitMax = SE->getNoopOrZeroExtend(ExitMax, WiderType);
1454 const SCEV *WideMaxIter = SE->getNoopOrZeroExtend(MaxIter, WiderType);
1455 if (WideExitMax == WideMaxIter)
1456 ICmpsFailingOnLastIter.insert(ICmp);
1457 }
1458
1459 bool Changed = false;
1460 for (auto *OldCond : LeafConditions) {
1461 // Skip last iteration for this icmp under one of two conditions:
1462 // - We do it for all conditions;
1463 // - There is another ICmp that would fail on last iter, so this one doesn't
1464 // really matter.
1465 bool OptimisticSkipLastIter = SkipLastIter;
1466 if (!OptimisticSkipLastIter) {
1467 if (ICmpsFailingOnLastIter.size() > 1)
1468 OptimisticSkipLastIter = true;
1469 else if (ICmpsFailingOnLastIter.size() == 1)
1470 OptimisticSkipLastIter = !ICmpsFailingOnLastIter.count(OldCond);
1471 }
1472 if (auto Replaced =
1473 createReplacement(OldCond, L, ExitingBB, MaxIter, Inverted,
1474 OptimisticSkipLastIter, SE, Rewriter)) {
1475 Changed = true;
1476 auto *NewCond = *Replaced;
1477 if (auto *NCI = dyn_cast<Instruction>(NewCond)) {
1478 NCI->setName(OldCond->getName() + ".first_iter");
1479 }
1480 LLVM_DEBUG(dbgs() << "Unknown exit count: Replacing " << *OldCond
1481 << " with " << *NewCond << "\n");
1482 assert(OldCond->hasOneUse() && "Must be!");
1483 OldCond->replaceAllUsesWith(NewCond);
1484 DeadInsts.push_back(OldCond);
1485 // Make sure we no longer consider this condition as failing on last
1486 // iteration.
1487 ICmpsFailingOnLastIter.erase(OldCond);
1488 }
1489 }
1490 return Changed;
1491}
1492
1493bool IndVarSimplify::canonicalizeExitCondition(Loop *L) {
1494 // Note: This is duplicating a particular part on SimplifyIndVars reasoning.
1495 // We need to duplicate it because given icmp zext(small-iv), C, IVUsers
1496 // never reaches the icmp since the zext doesn't fold to an AddRec unless
1497 // it already has flags. The alternative to this would be to extending the
1498 // set of "interesting" IV users to include the icmp, but doing that
1499 // regresses results in practice by querying SCEVs before trip counts which
1500 // rely on them which results in SCEV caching sub-optimal answers. The
1501 // concern about caching sub-optimal results is why we only query SCEVs of
1502 // the loop invariant RHS here.
1503 SmallVector<BasicBlock*, 16> ExitingBlocks;
1504 L->getExitingBlocks(ExitingBlocks);
1505 bool Changed = false;
1506 for (auto *ExitingBB : ExitingBlocks) {
1507 auto *BI = dyn_cast<CondBrInst>(ExitingBB->getTerminator());
1508 if (!BI)
1509 continue;
1510
1511 auto *ICmp = dyn_cast<ICmpInst>(BI->getCondition());
1512 if (!ICmp || !ICmp->hasOneUse())
1513 continue;
1514
1515 auto *LHS = ICmp->getOperand(0);
1516 auto *RHS = ICmp->getOperand(1);
1517 // For the range reasoning, avoid computing SCEVs in the loop to avoid
1518 // poisoning cache with sub-optimal results. For the must-execute case,
1519 // this is a neccessary precondition for correctness.
1520 if (!L->isLoopInvariant(RHS)) {
1521 if (!L->isLoopInvariant(LHS))
1522 continue;
1523 // Same logic applies for the inverse case
1524 std::swap(LHS, RHS);
1525 }
1526
1527 // Match (icmp signed-cond zext, RHS)
1528 Value *LHSOp = nullptr;
1529 if (!match(LHS, m_ZExt(m_Value(LHSOp))) || !ICmp->isSigned())
1530 continue;
1531
1532 const unsigned InnerBitWidth = DL.getTypeSizeInBits(LHSOp->getType());
1533 const unsigned OuterBitWidth = DL.getTypeSizeInBits(RHS->getType());
1534 auto FullCR = ConstantRange::getFull(InnerBitWidth);
1535 FullCR = FullCR.zeroExtend(OuterBitWidth);
1536 auto RHSCR = SE->getUnsignedRange(SE->applyLoopGuards(SE->getSCEV(RHS), L));
1537 if (FullCR.contains(RHSCR)) {
1538 // We have now matched icmp signed-cond zext(X), zext(Y'), and can thus
1539 // replace the signed condition with the unsigned version.
1540 ICmp->setPredicate(ICmp->getUnsignedPredicate());
1541 Changed = true;
1542 // Note: No SCEV invalidation needed. We've changed the predicate, but
1543 // have not changed exit counts, or the values produced by the compare.
1544 continue;
1545 }
1546 }
1547
1548 // Now that we've canonicalized the condition to match the extend,
1549 // see if we can rotate the extend out of the loop.
1550 for (auto *ExitingBB : ExitingBlocks) {
1551 auto *BI = dyn_cast<CondBrInst>(ExitingBB->getTerminator());
1552 if (!BI)
1553 continue;
1554
1555 auto *ICmp = dyn_cast<ICmpInst>(BI->getCondition());
1556 if (!ICmp || !ICmp->hasOneUse() || !ICmp->isUnsigned())
1557 continue;
1558
1559 bool Swapped = false;
1560 auto *LHS = ICmp->getOperand(0);
1561 auto *RHS = ICmp->getOperand(1);
1562 if (L->isLoopInvariant(LHS) == L->isLoopInvariant(RHS))
1563 // Nothing to rotate
1564 continue;
1565 if (L->isLoopInvariant(LHS)) {
1566 // Same logic applies for the inverse case until we actually pick
1567 // which operand of the compare to update.
1568 Swapped = true;
1569 std::swap(LHS, RHS);
1570 }
1571 assert(!L->isLoopInvariant(LHS) && L->isLoopInvariant(RHS));
1572
1573 // Match (icmp unsigned-cond zext, RHS)
1574 // TODO: Extend to handle corresponding sext/signed-cmp case
1575 // TODO: Extend to other invertible functions
1576 Value *LHSOp = nullptr;
1577 if (!match(LHS, m_ZExt(m_Value(LHSOp))))
1578 continue;
1579
1580 // In general, we only rotate if we can do so without increasing the number
1581 // of instructions. The exception is when we have an zext(add-rec). The
1582 // reason for allowing this exception is that we know we need to get rid
1583 // of the zext for SCEV to be able to compute a trip count for said loops;
1584 // we consider the new trip count valuable enough to increase instruction
1585 // count by one.
1586 if (!LHS->hasOneUse() && !isa<SCEVAddRecExpr>(SE->getSCEV(LHSOp)))
1587 continue;
1588
1589 // Given a icmp unsigned-cond zext(Op) where zext(trunc(RHS)) == RHS
1590 // replace with an icmp of the form icmp unsigned-cond Op, trunc(RHS)
1591 // when zext is loop varying and RHS is loop invariant. This converts
1592 // loop varying work to loop-invariant work.
1593 auto doRotateTransform = [&]() {
1594 assert(ICmp->isUnsigned() && "must have proven unsigned already");
1595 auto *NewRHS = CastInst::Create(
1596 Instruction::Trunc, RHS, LHSOp->getType(), "",
1597 L->getLoopPreheader()->getTerminator()->getIterator());
1598 // NewRHS is an operation that has been hoisted out of the loop, and
1599 // therefore should have a dropped location.
1600 NewRHS->setDebugLoc(DebugLoc::getDropped());
1601 ICmp->setOperand(Swapped ? 1 : 0, LHSOp);
1602 ICmp->setOperand(Swapped ? 0 : 1, NewRHS);
1603 // Samesign flag cannot be preserved after narrowing the compare.
1604 ICmp->setSameSign(false);
1605 if (LHS->use_empty())
1606 DeadInsts.push_back(LHS);
1607 };
1608
1609 const unsigned InnerBitWidth = DL.getTypeSizeInBits(LHSOp->getType());
1610 const unsigned OuterBitWidth = DL.getTypeSizeInBits(RHS->getType());
1611 auto FullCR = ConstantRange::getFull(InnerBitWidth);
1612 FullCR = FullCR.zeroExtend(OuterBitWidth);
1613 auto RHSCR = SE->getUnsignedRange(SE->applyLoopGuards(SE->getSCEV(RHS), L));
1614 if (FullCR.contains(RHSCR)) {
1615 doRotateTransform();
1616 Changed = true;
1617 // Note, we are leaving SCEV in an unfortunately imprecise case here
1618 // as rotation tends to reveal information about trip counts not
1619 // previously visible.
1620 continue;
1621 }
1622 }
1623
1624 return Changed;
1625}
1626
1627bool IndVarSimplify::optimizeLoopExits(Loop *L, SCEVExpander &Rewriter) {
1628 SmallVector<BasicBlock*, 16> ExitingBlocks;
1629 L->getExitingBlocks(ExitingBlocks);
1630
1631 // Remove all exits which aren't both rewriteable and execute on every
1632 // iteration.
1633 llvm::erase_if(ExitingBlocks, [&](BasicBlock *ExitingBB) {
1634 // If our exitting block exits multiple loops, we can only rewrite the
1635 // innermost one. Otherwise, we're changing how many times the innermost
1636 // loop runs before it exits.
1637 if (LI->getLoopFor(ExitingBB) != L)
1638 return true;
1639
1640 // Can't rewrite non-branch yet.
1641 CondBrInst *BI = dyn_cast<CondBrInst>(ExitingBB->getTerminator());
1642 if (!BI)
1643 return true;
1644
1645 // Likewise, the loop latch must be dominated by the exiting BB.
1646 if (!DT->dominates(ExitingBB, L->getLoopLatch()))
1647 return true;
1648
1649 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
1650 // If already constant, nothing to do. However, if this is an
1651 // unconditional exit, we can still replace header phis with their
1652 // preheader value.
1653 if (!L->contains(BI->getSuccessor(CI->isNullValue())))
1654 replaceLoopPHINodesWithPreheaderValues(LI, L, DeadInsts, *SE);
1655 return true;
1656 }
1657
1658 return false;
1659 });
1660
1661 if (ExitingBlocks.empty())
1662 return false;
1663
1664 // Get a symbolic upper bound on the loop backedge taken count.
1665 const SCEV *MaxBECount = SE->getSymbolicMaxBackedgeTakenCount(L);
1666 if (isa<SCEVCouldNotCompute>(MaxBECount))
1667 return false;
1668
1669 // Visit our exit blocks in order of dominance. We know from the fact that
1670 // all exits must dominate the latch, so there is a total dominance order
1671 // between them.
1672 llvm::sort(ExitingBlocks, [&](BasicBlock *A, BasicBlock *B) {
1673 // std::sort sorts in ascending order, so we want the inverse of
1674 // the normal dominance relation.
1675 if (A == B) return false;
1676 if (DT->properlyDominates(A, B))
1677 return true;
1678 else {
1679 assert(DT->properlyDominates(B, A) &&
1680 "expected total dominance order!");
1681 return false;
1682 }
1683 });
1684#ifdef ASSERT
1685 for (unsigned i = 1; i < ExitingBlocks.size(); i++) {
1686 assert(DT->dominates(ExitingBlocks[i-1], ExitingBlocks[i]));
1687 }
1688#endif
1689
1690 bool Changed = false;
1691 bool SkipLastIter = false;
1692 const SCEV *CurrMaxExit = SE->getCouldNotCompute();
1693 auto UpdateSkipLastIter = [&](const SCEV *MaxExitCount) {
1694 if (SkipLastIter || isa<SCEVCouldNotCompute>(MaxExitCount))
1695 return;
1696 if (isa<SCEVCouldNotCompute>(CurrMaxExit))
1697 CurrMaxExit = MaxExitCount;
1698 else
1699 CurrMaxExit = SE->getUMinFromMismatchedTypes(CurrMaxExit, MaxExitCount);
1700 // If the loop has more than 1 iteration, all further checks will be
1701 // executed 1 iteration less.
1702 if (CurrMaxExit == MaxBECount)
1703 SkipLastIter = true;
1704 };
1705 SmallPtrSet<const SCEV *, 8> DominatingExactExitCounts;
1706 for (BasicBlock *ExitingBB : ExitingBlocks) {
1707 const SCEV *ExactExitCount = SE->getExitCount(L, ExitingBB);
1708 const SCEV *MaxExitCount = SE->getExitCount(
1709 L, ExitingBB, ScalarEvolution::ExitCountKind::SymbolicMaximum);
1710 if (isa<SCEVCouldNotCompute>(ExactExitCount)) {
1711 // Okay, we do not know the exit count here. Can we at least prove that it
1712 // will remain the same within iteration space?
1713 auto *BI = cast<CondBrInst>(ExitingBB->getTerminator());
1714 auto OptimizeCond = [&](bool SkipLastIter) {
1715 return optimizeLoopExitWithUnknownExitCount(L, BI, ExitingBB,
1716 MaxBECount, SkipLastIter,
1717 SE, Rewriter, DeadInsts);
1718 };
1719
1720 // TODO: We might have proved that we can skip the last iteration for
1721 // this check. In this case, we only want to check the condition on the
1722 // pre-last iteration (MaxBECount - 1). However, there is a nasty
1723 // corner case:
1724 //
1725 // for (i = len; i != 0; i--) { ... check (i ult X) ... }
1726 //
1727 // If we could not prove that len != 0, then we also could not prove that
1728 // (len - 1) is not a UINT_MAX. If we simply query (len - 1), then
1729 // OptimizeCond will likely not prove anything for it, even if it could
1730 // prove the same fact for len.
1731 //
1732 // As a temporary solution, we query both last and pre-last iterations in
1733 // hope that we will be able to prove triviality for at least one of
1734 // them. We can stop querying MaxBECount for this case once SCEV
1735 // understands that (MaxBECount - 1) will not overflow here.
1736 if (OptimizeCond(false))
1737 Changed = true;
1738 else if (SkipLastIter && OptimizeCond(true))
1739 Changed = true;
1740 UpdateSkipLastIter(MaxExitCount);
1741 continue;
1742 }
1743
1744 UpdateSkipLastIter(ExactExitCount);
1745
1746 // If we know we'd exit on the first iteration, rewrite the exit to
1747 // reflect this. This does not imply the loop must exit through this
1748 // exit; there may be an earlier one taken on the first iteration.
1749 // We know that the backedge can't be taken, so we replace all
1750 // the header PHIs with values coming from the preheader.
1751 if (ExactExitCount->isZero()) {
1752 foldExit(L, ExitingBB, true, DeadInsts);
1753 replaceLoopPHINodesWithPreheaderValues(LI, L, DeadInsts, *SE);
1754 Changed = true;
1755 continue;
1756 }
1757
1758 assert(ExactExitCount->getType()->isIntegerTy() &&
1759 MaxBECount->getType()->isIntegerTy() &&
1760 "Exit counts must be integers");
1761
1762 Type *WiderType =
1763 SE->getWiderType(MaxBECount->getType(), ExactExitCount->getType());
1764 ExactExitCount = SE->getNoopOrZeroExtend(ExactExitCount, WiderType);
1765 MaxBECount = SE->getNoopOrZeroExtend(MaxBECount, WiderType);
1766 assert(MaxBECount->getType() == ExactExitCount->getType());
1767
1768 // Can we prove that some other exit must be taken strictly before this
1769 // one?
1770 if (SE->isLoopEntryGuardedByCond(L, CmpInst::ICMP_ULT, MaxBECount,
1771 ExactExitCount)) {
1772 foldExit(L, ExitingBB, false, DeadInsts);
1773 Changed = true;
1774 continue;
1775 }
1776
1777 // As we run, keep track of which exit counts we've encountered. If we
1778 // find a duplicate, we've found an exit which would have exited on the
1779 // exiting iteration, but (from the visit order) strictly follows another
1780 // which does the same and is thus dead.
1781 if (!DominatingExactExitCounts.insert(ExactExitCount).second) {
1782 foldExit(L, ExitingBB, false, DeadInsts);
1783 Changed = true;
1784 continue;
1785 }
1786
1787 // TODO: There might be another oppurtunity to leverage SCEV's reasoning
1788 // here. If we kept track of the min of dominanting exits so far, we could
1789 // discharge exits with EC >= MDEC. This is less powerful than the existing
1790 // transform (since later exits aren't considered), but potentially more
1791 // powerful for any case where SCEV can prove a >=u b, but neither a == b
1792 // or a >u b. Such a case is not currently known.
1793 }
1794 return Changed;
1795}
1796
1797static bool crashingBBWithoutEffect(const BasicBlock &BB) {
1798 return llvm::all_of(BB, [](const Instruction &I) {
1799 // TODO: for now this is overly restrictive, to make sure nothing in this
1800 // BB can depend on the loop body.
1801 // It's not enough to check for !I.mayHaveSideEffects(), because e.g. a
1802 // load does not have a side effect, but we could have
1803 // %a = load ptr, ptr %ptr
1804 // %b = load i32, ptr %a
1805 // Now if the loop stored a non-nullptr to %a, we could cause a nullptr
1806 // dereference by skipping over loop iterations.
1807 if (const auto *CB = dyn_cast<CallBase>(&I)) {
1808 if (CB->onlyAccessesInaccessibleMemory())
1809 return true;
1810 }
1811 return isa<UnreachableInst>(I);
1812 });
1813}
1814
1815bool IndVarSimplify::predicateLoopExits(Loop *L, SCEVExpander &Rewriter) {
1816 SmallVector<BasicBlock*, 16> ExitingBlocks;
1817 L->getExitingBlocks(ExitingBlocks);
1818
1819 // Finally, see if we can rewrite our exit conditions into a loop invariant
1820 // form. If we have a read-only loop, and we can tell that we must exit down
1821 // a path which does not need any of the values computed within the loop, we
1822 // can rewrite the loop to exit on the first iteration. Note that this
1823 // doesn't either a) tell us the loop exits on the first iteration (unless
1824 // *all* exits are predicateable) or b) tell us *which* exit might be taken.
1825 // This transformation looks a lot like a restricted form of dead loop
1826 // elimination, but restricted to read-only loops and without neccesssarily
1827 // needing to kill the loop entirely.
1828 if (!Opts.indvars_predicate_loops)
1829 return false;
1830
1831 // Note: ExactBTC is the exact backedge taken count *iff* the loop exits
1832 // through *explicit* control flow. We have to eliminate the possibility of
1833 // implicit exits (see below) before we know it's truly exact.
1834 const SCEV *ExactBTC = SE->getBackedgeTakenCount(L);
1835 if (isa<SCEVCouldNotCompute>(ExactBTC) || !Rewriter.isSafeToExpand(ExactBTC))
1836 return false;
1837
1838 assert(SE->isLoopInvariant(ExactBTC, L) && "BTC must be loop invariant");
1839 assert(ExactBTC->getType()->isIntegerTy() && "BTC must be integer");
1840
1841 auto BadExit = [&](BasicBlock *ExitingBB) {
1842 // If our exiting block exits multiple loops, we can only rewrite the
1843 // innermost one. Otherwise, we're changing how many times the innermost
1844 // loop runs before it exits.
1845 if (LI->getLoopFor(ExitingBB) != L)
1846 return true;
1847
1848 // Can't rewrite non-branch yet.
1849 CondBrInst *BI = dyn_cast<CondBrInst>(ExitingBB->getTerminator());
1850 if (!BI)
1851 return true;
1852
1853 // If already constant, nothing to do.
1854 if (isa<Constant>(BI->getCondition()))
1855 return true;
1856
1857 // If the exit block has phis, we need to be able to compute the values
1858 // within the loop which contains them. This assumes trivially lcssa phis
1859 // have already been removed; TODO: generalize
1860 BasicBlock *ExitBlock =
1861 BI->getSuccessor(L->contains(BI->getSuccessor(0)) ? 1 : 0);
1862 if (!ExitBlock->phis().empty())
1863 return true;
1864
1865 const SCEV *ExitCount = SE->getExitCount(L, ExitingBB);
1866 if (isa<SCEVCouldNotCompute>(ExitCount) ||
1867 !Rewriter.isSafeToExpand(ExitCount))
1868 return true;
1869
1870 assert(SE->isLoopInvariant(ExitCount, L) &&
1871 "Exit count must be loop invariant");
1872 assert(ExitCount->getType()->isIntegerTy() && "Exit count must be integer");
1873 return false;
1874 };
1875
1876 // Make sure all exits dominate the latch. This means there is a linear chain
1877 // of exits. We check this before sorting so we have a total order.
1878 BasicBlock *Latch = L->getLoopLatch();
1879 for (BasicBlock *ExitingBB : ExitingBlocks)
1880 if (!DT->dominates(ExitingBB, Latch))
1881 return false;
1882
1883 // If we have any exits which can't be predicated themselves, than we can't
1884 // predicate any exit which isn't guaranteed to execute before it. Consider
1885 // two exits (a) and (b) which would both exit on the same iteration. If we
1886 // can predicate (b), but not (a), and (a) preceeds (b) along some path, then
1887 // we could convert a loop from exiting through (a) to one exiting through
1888 // (b). Note that this problem exists only for exits with the same exit
1889 // count, and we could be more aggressive when exit counts are known inequal.
1890 llvm::sort(ExitingBlocks, [&](BasicBlock *A, BasicBlock *B) {
1891 // llvm::sort sorts in ascending order, so we want the inverse of
1892 // the normal dominance relation.
1893 if (A == B)
1894 return false;
1895 if (DT->properlyDominates(A, B))
1896 return true;
1897 if (DT->properlyDominates(B, A))
1898 return false;
1899 llvm_unreachable("Should have total dominance order");
1900 });
1901
1902 // Make sure our exit blocks are really a total order (i.e. a linear chain of
1903 // exits before the backedge).
1904 for (unsigned i = 1; i < ExitingBlocks.size(); i++)
1905 assert(DT->dominates(ExitingBlocks[i - 1], ExitingBlocks[i]) &&
1906 "Not sorted by dominance");
1907
1908 // Given our sorted total order, we know that exit[j] must be evaluated
1909 // after all exit[i] such j > i.
1910 for (unsigned i = 0, e = ExitingBlocks.size(); i < e; i++)
1911 if (BadExit(ExitingBlocks[i])) {
1912 ExitingBlocks.resize(i);
1913 break;
1914 }
1915
1916 if (ExitingBlocks.empty())
1917 return false;
1918
1919 // Predication may skip iterations of L, which is only safe if none of them
1920 // would run forever. Calls that may not return are rejected below.
1921 if (!isLoopNestFinite(L, *SE, *LI))
1922 return false;
1923
1924 // At this point, ExitingBlocks consists of only those blocks which are
1925 // predicatable. Given that, we know we have at least one exit we can
1926 // predicate if the loop is doesn't have side effects and doesn't have any
1927 // implicit exits (because then our exact BTC isn't actually exact).
1928 // @Reviewers - As structured, this is O(I^2) for loop nests. Any
1929 // suggestions on how to improve this? I can obviously bail out for outer
1930 // loops, but that seems less than ideal. MemorySSA can find memory writes,
1931 // is that enough for *all* side effects?
1932 bool HasThreadLocalSideEffects = false;
1933 for (BasicBlock *BB : L->blocks())
1934 for (auto &I : *BB) {
1935 // TODO:isGuaranteedToTransfer
1936 if (I.mayHaveSideEffects()) {
1937 if (!Opts.indvars_predicate_loop_traps)
1938 return false;
1939 HasThreadLocalSideEffects = true;
1940 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
1941 // Simple stores cannot be observed by other threads.
1942 // If HasThreadLocalSideEffects is set, we check
1943 // crashingBBWithoutEffect to make sure that the crashing BB cannot
1944 // observe them either.
1945 if (!SI->isSimple())
1946 return false;
1947 } else {
1948 return false;
1949 }
1950 }
1951
1952 // Skip if the loop has tokens referenced outside the loop to avoid
1953 // changing convergence behavior.
1954 if (I.getType()->isTokenTy()) {
1955 for (Instruction *UserInst : I.users()) {
1956 if (!L->contains(UserInst))
1957 return false;
1958 }
1959 }
1960 }
1961
1962 bool Changed = false;
1963 // Finally, do the actual predication for all predicatable blocks. A couple
1964 // of notes here:
1965 // 1) We don't bother to constant fold dominated exits with identical exit
1966 // counts; that's simply a form of CSE/equality propagation and we leave
1967 // it for dedicated passes.
1968 // 2) We insert the comparison at the branch. Hoisting introduces additional
1969 // legality constraints and we leave that to dedicated logic. We want to
1970 // predicate even if we can't insert a loop invariant expression as
1971 // peeling or unrolling will likely reduce the cost of the otherwise loop
1972 // varying check.
1973 Rewriter.setInsertPoint(L->getLoopPreheader()->getTerminator());
1974 IRBuilder<> B(L->getLoopPreheader()->getTerminator());
1975 Value *ExactBTCV = nullptr; // Lazily generated if needed.
1976 for (BasicBlock *ExitingBB : ExitingBlocks) {
1977 const SCEV *ExitCount = SE->getExitCount(L, ExitingBB);
1978
1979 auto *BI = cast<CondBrInst>(ExitingBB->getTerminator());
1980 if (HasThreadLocalSideEffects) {
1981 const BasicBlock *Unreachable = nullptr;
1982 for (const BasicBlock *Succ : BI->successors()) {
1983 if (isa<UnreachableInst>(Succ->getTerminator()))
1984 Unreachable = Succ;
1985 }
1986 // Exit BB which have one branch back into the loop and another one to
1987 // a trap can still be optimized, because local side effects cannot
1988 // be observed in the exit case (the trap). We could be smarter about
1989 // this, but for now lets pattern match common cases that directly trap.
1990 if (Unreachable == nullptr || !crashingBBWithoutEffect(*Unreachable))
1991 return Changed;
1992 }
1993 Value *NewCond;
1994 if (ExitCount == ExactBTC) {
1995 NewCond = L->contains(BI->getSuccessor(0)) ?
1996 B.getFalse() : B.getTrue();
1997 } else {
1998 Value *ECV = Rewriter.expandCodeFor(ExitCount);
1999 if (!ExactBTCV)
2000 ExactBTCV = Rewriter.expandCodeFor(ExactBTC);
2001 Value *RHS = ExactBTCV;
2002 if (ECV->getType() != RHS->getType()) {
2003 Type *WiderTy = SE->getWiderType(ECV->getType(), RHS->getType());
2004 ECV = B.CreateZExt(ECV, WiderTy);
2005 RHS = B.CreateZExt(RHS, WiderTy);
2006 }
2007 auto Pred = L->contains(BI->getSuccessor(0)) ?
2008 ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
2009 NewCond = B.CreateICmp(Pred, ECV, RHS);
2010 }
2011 Value *OldCond = BI->getCondition();
2012 BI->setCondition(NewCond);
2013 if (OldCond->use_empty())
2014 DeadInsts.emplace_back(OldCond);
2015 Changed = true;
2016 RunUnswitching = true;
2017 }
2018
2019 return Changed;
2020}
2021
2022//===----------------------------------------------------------------------===//
2023// IndVarSimplify driver. Manage several subpasses of IV simplification.
2024//===----------------------------------------------------------------------===//
2025
2026bool IndVarSimplify::run(Loop *L) {
2027 // We need (and expect!) the incoming loop to be in LCSSA.
2028 assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
2029 "LCSSA required to run indvars!");
2030
2031 // If LoopSimplify form is not available, stay out of trouble. Some notes:
2032 // - LSR currently only supports LoopSimplify-form loops. Indvars'
2033 // canonicalization can be a pessimization without LSR to "clean up"
2034 // afterwards.
2035 // - We depend on having a preheader; in particular,
2036 // Loop::getCanonicalInductionVariable only supports loops with preheaders,
2037 // and we're in trouble if we can't find the induction variable even when
2038 // we've manually inserted one.
2039 // - LFTR relies on having a single backedge.
2040 if (!L->isLoopSimplifyForm())
2041 return false;
2042
2043 bool Changed = false;
2044 // If there are any floating-point recurrences, attempt to
2045 // transform them to use integer recurrences.
2046 Changed |= rewriteNonIntegerIVs(L);
2047
2048 // Create a rewriter object which we'll use to transform the code with.
2049 SCEVExpander Rewriter(*SE, "indvars");
2050#if LLVM_ENABLE_ABI_BREAKING_CHECKS
2051 Rewriter.setDebugType(DEBUG_TYPE);
2052#endif
2053
2054 // Eliminate redundant IV users.
2055 //
2056 // Simplification works best when run before other consumers of SCEV. We
2057 // attempt to avoid evaluating SCEVs for sign/zero extend operations until
2058 // other expressions involving loop IVs have been evaluated. This helps SCEV
2059 // set no-wrap flags before normalizing sign/zero extension.
2060 Rewriter.disableCanonicalMode();
2061 Changed |= simplifyAndExtend(L, Rewriter, LI);
2062
2063 // Check to see if we can compute the final value of any expressions
2064 // that are recurrent in the loop, and substitute the exit values from the
2065 // loop into any instructions outside of the loop that use the final values
2066 // of the current expressions.
2067 if (Opts.replexitval != NeverRepl) {
2068 if (int Rewrites = rewriteLoopExitValues(L, LI, TLI, SE, TTI, Rewriter, DT,
2069 Opts.replexitval, DeadInsts)) {
2070 NumReplaced += Rewrites;
2071 Changed = true;
2072 }
2073 }
2074
2075 // Eliminate redundant IV cycles.
2076 NumElimIV += Rewriter.replaceCongruentIVs(L, DT, DeadInsts, TTI);
2077
2078 // Try to convert exit conditions to unsigned and rotate computation
2079 // out of the loop. Note: Handles invalidation internally if needed.
2080 Changed |= canonicalizeExitCondition(L);
2081
2082 // Try to eliminate loop exits based on analyzeable exit counts
2083 if (optimizeLoopExits(L, Rewriter)) {
2084 Changed = true;
2085 // Given we've changed exit counts, notify SCEV
2086 // Some nested loops may share same folded exit basic block,
2087 // thus we need to notify top most loop.
2088 SE->forgetTopmostLoop(L);
2089 }
2090
2091 // Try to form loop invariant tests for loop exits by changing how many
2092 // iterations of the loop run when that is unobservable.
2093 if (predicateLoopExits(L, Rewriter)) {
2094 Changed = true;
2095 // Given we've changed exit counts, notify SCEV
2096 SE->forgetLoop(L);
2097 }
2098
2099 // If we have a trip count expression, rewrite the loop's exit condition
2100 // using it.
2101 if (!Opts.disable_lftr) {
2102 BasicBlock *PreHeader = L->getLoopPreheader();
2103
2104 SmallVector<BasicBlock*, 16> ExitingBlocks;
2105 L->getExitingBlocks(ExitingBlocks);
2106 for (BasicBlock *ExitingBB : ExitingBlocks) {
2107 // Can't rewrite non-branch yet.
2108 if (!isa<CondBrInst>(ExitingBB->getTerminator()))
2109 continue;
2110
2111 // If our exitting block exits multiple loops, we can only rewrite the
2112 // innermost one. Otherwise, we're changing how many times the innermost
2113 // loop runs before it exits.
2114 if (LI->getLoopFor(ExitingBB) != L)
2115 continue;
2116
2117 if (!needsLFTR(L, ExitingBB))
2118 continue;
2119
2120 const SCEV *ExitCount = SE->getExitCount(L, ExitingBB);
2121 if (isa<SCEVCouldNotCompute>(ExitCount))
2122 continue;
2123
2124 // This was handled above, but as we form SCEVs, we can sometimes refine
2125 // existing ones; this allows exit counts to be folded to zero which
2126 // weren't when optimizeLoopExits saw them. Arguably, we should iterate
2127 // until stable to handle cases like this better.
2128 if (ExitCount->isZero())
2129 continue;
2130
2131 PHINode *IndVar = FindLoopCounter(L, ExitingBB, ExitCount, SE, DT);
2132 if (!IndVar)
2133 continue;
2134
2135 // Avoid high cost expansions. Note: This heuristic is questionable in
2136 // that our definition of "high cost" is not exactly principled.
2137 if (Rewriter.isHighCostExpansion(ExitCount, L, SCEVCheapExpansionBudget,
2138 TTI, PreHeader->getTerminator()))
2139 continue;
2140
2141 if (!Rewriter.isSafeToExpand(ExitCount))
2142 continue;
2143
2144 Changed |= linearFunctionTestReplace(L, ExitingBB,
2145 ExitCount, IndVar,
2146 Rewriter);
2147 }
2148 }
2149 // Clear the rewriter cache, because values that are in the rewriter's cache
2150 // can be deleted in the loop below, causing the AssertingVH in the cache to
2151 // trigger.
2152 Rewriter.clear();
2153
2154 // Now that we're done iterating through lists, clean up any instructions
2155 // which are now dead.
2156 while (!DeadInsts.empty()) {
2157 Value *V = DeadInsts.pop_back_val();
2158
2159 if (PHINode *PHI = dyn_cast_or_null<PHINode>(V))
2160 Changed |= RecursivelyDeleteDeadPHINode(PHI, TLI, MSSAU.get());
2161 else if (Instruction *Inst = dyn_cast_or_null<Instruction>(V))
2162 Changed |=
2164 }
2165
2166 // The Rewriter may not be used from this point on.
2167
2168 // Loop-invariant instructions in the preheader that aren't used in the
2169 // loop may be sunk below the loop to reduce register pressure.
2170 Changed |= sinkUnusedInvariants(L);
2171
2172 // rewriteFirstIterationLoopExitValues does not rely on the computation of
2173 // trip count and therefore can further simplify exit values in addition to
2174 // rewriteLoopExitValues.
2175 Changed |= rewriteFirstIterationLoopExitValues(L);
2176
2177 // Clean up dead instructions.
2178 Changed |= DeleteDeadPHIs(L->getHeader(), TLI, MSSAU.get());
2179
2180 // Check a post-condition.
2181 assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
2182 "Indvars did not preserve LCSSA!");
2183 if (VerifyMemorySSA && MSSAU)
2184 MSSAU->getMemorySSA()->verifyMemorySSA();
2185
2186 return Changed;
2187}
2188
2191 LPMUpdater &) {
2192 Function *F = L.getHeader()->getParent();
2193 const DataLayout &DL = F->getDataLayout();
2194 const ScalarOptions &Opts = getScalarOptions(*F);
2195
2196 IndVarSimplify IVS(Opts, &AR.LI, &AR.SE, &AR.DT, DL, &AR.TLI, &AR.TTI,
2197 AR.MSSA, WidenIndVars && Opts.indvars_widen_indvars);
2198 if (!IVS.run(&L))
2199 return PreservedAnalyses::all();
2200
2201 auto PA = getLoopPassPreservedAnalyses();
2202 PA.preserveSet<CFGAnalyses>();
2203 if (IVS.runUnswitching()) {
2205 PA.preserve<ShouldRunExtraSimpleLoopUnswitch>();
2206 }
2207
2208 if (AR.MSSA)
2209 PA.preserve<MemorySSAAnalysis>();
2210 return PA;
2211}
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AArch64 Predicate As Counter Loop Rewrites
uint64_t uint64_t
Rewrite undef for PHI
This file declares a class to represent arbitrary precision floating point values and provide a varie...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define DEBUG_TYPE
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
static bool optimizeLoopExitWithUnknownExitCount(const Loop *L, CondBrInst *BI, BasicBlock *ExitingBB, const SCEV *MaxIter, bool SkipLastIter, ScalarEvolution *SE, SCEVExpander &Rewriter, SmallVectorImpl< WeakTrackingVH > &DeadInsts)
static Value * genLoopLimit(PHINode *IndVar, BasicBlock *ExitingBB, const SCEV *ExitCount, bool UsePostInc, Loop *L, SCEVExpander &Rewriter, ScalarEvolution *SE)
Insert an IR expression which computes the value held by the IV IndVar (which must be an loop counter...
static bool isLoopExitTestBasedOn(Value *V, BasicBlock *ExitingBB)
Whether the current loop exit test is based on this value.
static void visitIVCast(CastInst *Cast, WideIVInfo &WI, ScalarEvolution *SE, const TargetTransformInfo *TTI)
Update information about the induction variable that is extended by this sign or zero extend operatio...
static bool isRepresentableAsExactInteger(const APFloat &FPVal, int64_t IntVal)
Ensure we stay within the bounds of fp values that can be represented as integers without gaps,...
static void replaceLoopPHINodesWithPreheaderValues(LoopInfo *LI, Loop *L, SmallVectorImpl< WeakTrackingVH > &DeadInsts, ScalarEvolution &SE)
static void replaceExitCond(CondBrInst *BI, Value *NewCond, SmallVectorImpl< WeakTrackingVH > &DeadInsts)
static bool needsLFTR(Loop *L, BasicBlock *ExitingBB)
linearFunctionTestReplace policy.
static Value * createInvariantCond(const Loop *L, BasicBlock *ExitingBB, const ScalarEvolution::LoopInvariantPredicate &LIP, SCEVExpander &Rewriter)
static bool isLoopCounter(PHINode *Phi, Loop *L, ScalarEvolution *SE)
Return true if the given phi is a "counter" in L.
static std::optional< Value * > createReplacement(ICmpInst *ICmp, const Loop *L, BasicBlock *ExitingBB, const SCEV *MaxIter, bool Inverted, bool SkipLastIter, ScalarEvolution *SE, SCEVExpander &Rewriter)
static bool hasConcreteDefImpl(Value *V, SmallPtrSetImpl< Value * > &Visited, unsigned Depth)
Recursive helper for hasConcreteDef().
static bool hasConcreteDef(Value *V)
Return true if the given value is concrete.
static void foldExit(const Loop *L, BasicBlock *ExitingBB, bool IsTaken, SmallVectorImpl< WeakTrackingVH > &DeadInsts)
static PHINode * getLoopPhiForCounter(Value *IncV, Loop *L)
Given an Value which is hoped to be part of an add recurance in the given loop, return the associated...
static Constant * createFoldedExitCond(const Loop *L, BasicBlock *ExitingBB, bool IsTaken)
static std::optional< IntegerIV > tryConvertToIntegerIV(const FloatingPointIV &FPIV)
Ensure that the floating-point IV can be converted to a semantics-preserving signed 32-bit integer IV...
static std::optional< FloatingPointIV > maybeFloatingPointRecurrence(Loop *L, PHINode *PN, const DominatorTree &DT)
Analyze a PN to determine whether it represents a simple floating-point induction variable,...
static void canonicalizeToIntegerIV(Loop *L, PHINode *PN, const FloatingPointIV &FPIV, const IntegerIV &IIV, const TargetLibraryInfo *TLI, std::unique_ptr< MemorySSAUpdater > &MSSAU)
Rewrite the floating-point IV as an integer IV.
static PHINode * FindLoopCounter(Loop *L, BasicBlock *ExitingBB, const SCEV *BECount, ScalarEvolution *SE, DominatorTree *DT)
Search the loop header for a loop counter (anadd rec w/step of one) suitable for use by LFTR.
static bool crashingBBWithoutEffect(const BasicBlock &BB)
static CmpInst::Predicate getIntegerPredicate(CmpInst::Predicate FPPred)
static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal)
Convert APF to an integer, if possible.
SmallVector< MachineOperand, 4 > Cond
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
#define P(N)
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
virt reg Virtual Register Rewriter
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
static constexpr roundingMode rmTowardZero
Definition APFloat.h:383
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:609
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:650
const fltSemantics & getSemantics() const
Definition APFloat.h:1624
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1469
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:508
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Definition InstrTypes.h:674
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:748
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:756
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
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
static LLVM_ABI StringRef getPredicateName(Predicate P)
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
Conditional Branch instruction.
void setCondition(Value *V)
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
iterator_range< succ_iterator > successors()
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
bool isLegalInteger(uint64_t Width) const
Returns true if the specified type is known to be a native integer type supported by the CPU.
Definition DataLayout.h:244
static DebugLoc getDropped()
Definition DebugLoc.h:155
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction compares its operands according to the predicate given to the constructor.
This instruction compares its operands according to the predicate given to the constructor.
CmpPredicate getCmpPredicate() const
CmpPredicate getInverseCmpPredicate() const
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
LLVM_ABI PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Instruction * user_back()
iterator_range< user_iterator > users()
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
Class to represent integer types.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form.
Definition LoopInfo.h:470
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
An analysis that produces MemorySSA for a function.
Definition MemorySSA.h:930
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:692
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
void setIncomingValue(unsigned i, Value *V)
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
static unsigned getIncomingValueNumForOperand(unsigned i)
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
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
This node represents a polynomial recurrence on the trip count of the specified loop.
LLVM_ABI const SCEV * evaluateAtIteration(const SCEV *It, ScalarEvolution &SE) const
Return the value of this chain of recurrences at the specified iteration number.
LLVM_ABI const SCEVAddRecExpr * getPostIncExpr(ScalarEvolution &SE) const
Return an expression representing the value of this expression one iteration of the loop ahead.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This class uses information about analyze scalars to rewrite expressions in canonical form.
This class represents an analyzed expression in the program.
LLVM_ABI bool isOne() const
Return true if the expression is a constant one.
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
Type * getType() const
Return the LLVM type of this SCEV expression.
This class represents a cast from signed integer to floating point.
The main scalar evolution driver.
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantExitCondDuringFirstIterations(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI, const SCEV *MaxIter)
If the result of the predicate LHS Pred RHS is loop invariant with respect to L at given Context duri...
LLVM_ABI Type * getWiderType(Type *Ty1, Type *Ty2) const
LLVM_ABI bool isLoopEntryGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the loop is protected by a conditional between LHS and RHS.
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI ExitLimit computeExitLimitFromCond(const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit, bool AllowPredicates=false)
Compute the number of times the backedge of the specified loop will execute if its exit condition wer...
LLVM_ABI SCEVUse getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
LLVM_ABI uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI void forgetValues(ArrayRef< Value * > Values)
Batched forgetValue: invalidates all Values in one shared def-use walk, avoiding the redundant re-tra...
LLVM_ABI std::optional< bool > evaluatePredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Check whether the condition described by Pred, LHS, and RHS is true or false in the given Context.
LLVM_ABI void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
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 const SCEV * getTruncateExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI Type * getEffectiveSCEVType(Type *Ty) const
Return a type with the same bitwidth as the given type and which represents how SCEV will treat the g...
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
LLVM_ABI void forgetTopmostLoop(const Loop *L)
LLVM_ABI void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
const SCEV * getMinusOne(Type *Ty)
Return a SCEV for the constant -1 of a specific type.
LLVM_ABI SCEVUse getZeroExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getNoopOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI const SCEV * getUMinFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS, bool Sequential=false)
Promote the operands to the wider of the types using zero-extension, and then perform a umin operatio...
LLVM_ABI const SCEV * getCouldNotCompute()
LLVM_ABI const SCEV * getExitCount(const Loop *L, const BasicBlock *ExitingBlock, ExitCountKind Kind=Exact)
Return the number of times the backedge executes before the given exit would be taken; if not exactly...
LLVM_ABI SCEVUse getSignExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
@ SymbolicMaximum
An expression which provides an upper bound on the exact trip count.
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
LLVM_ABI bool isKnownPredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
const SCEV * getSymbolicMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEV that is greater than or equal to (i.e.
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
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.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
bool use_empty() const
Definition Value.h:348
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
Value handle that is nullable, but tries to track the Value.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
cst_pred_ty< is_one > m_scev_One()
Match an integer 1.
specificloop_ty m_SpecificLoop(const Loop *L)
bool match(const SCEV *S, const Pattern &P)
SCEVAffineAddRec_match< Op0_t, Op1_t, match_isa< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
@ User
could "use" a pointer
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool mustExecuteUBIfPoisonOnPathTo(Instruction *Root, Instruction *OnPathTo, DominatorTree *DT)
Return true if undefined behavior would provable be executed on the path to OnPathTo if Root produced...
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 RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:523
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q, SmallVectorImpl< Instruction * > *DropAnnotations=nullptr)
See if we can compute a simplified version of this instruction.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
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 PHINode * createWideIV(const WideIVInfo &WI, LoopInfo *LI, ScalarEvolution *SE, SCEVExpander &Rewriter, DominatorTree *DT, SmallVectorImpl< WeakTrackingVH > &DeadInsts, unsigned &NumElimExt, unsigned &NumWidened, bool HasGuards, bool UsePostIncrementRanges)
Widen Induction Variables - Extend the width of an IV to cover its widest uses.
SCEVUseT< const SCEV * > SCEVUse
LLVM_ABI bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=nullptr)
Examine each PHI in the given block and delete it if it is dead.
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
const ScalarOptions & getScalarOptions(const LLVMContext &C)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
LLVM_ABI cl::opt< unsigned > SCEVCheapExpansionBudget
LLVM_ABI bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=nullptr)
If the specified value is an effectively dead PHI node, due to being a def-use chain of single-use no...
Definition Local.cpp:623
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:74
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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::pair< bool, bool > simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT, LoopInfo *LI, const TargetTransformInfo *TTI, SmallVectorImpl< WeakTrackingVH > &Dead, SCEVExpander &Rewriter, IVVisitor *V=nullptr)
simplifyUsersOfIV - Simplify instructions that use this induction variable by using ScalarEvolution t...
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.
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
TargetTransformInfo TTI
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
DWARFExpression::Operation Op
constexpr U AbsoluteValue(T X)
Return the absolute value of a signed integer, converted to the corresponding unsigned integer type.
Definition MathExtras.h:592
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2210
LLVM_ABI bool isAlmostDeadIV(PHINode *IV, BasicBlock *LatchBlock, Value *Cond)
Return true if the induction variable IV in a Loop whose latch is LatchBlock would become dead if the...
LLVM_ABI int rewriteLoopExitValues(Loop *L, LoopInfo *LI, TargetLibraryInfo *TLI, ScalarEvolution *SE, const TargetTransformInfo *TTI, SCEVExpander &Rewriter, DominatorTree *DT, ReplaceExitVal ReplaceExitValue, SmallVector< WeakTrackingVH, 16 > &DeadInsts)
If the final value of any expressions that are recurrent in the loop can be computed,...
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
@ NeverRepl
Definition LoopUtils.h:607
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
Represents a floating-point induction variable pattern that may be convertible to integer form.
FloatingPointIV(APFloat Init, APFloat Incr, APFloat Exit, FCmpInst *Compare, bool ExitsOnTrue)
Represents the integer values for a converted IV.
int64_t InitValue
int64_t ExitValue
int64_t IncrValue
CmpInst::Predicate NewPred
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
A marker analysis to determine if SimpleLoopUnswitch should run again on a given loop.
Collect information about induction variables that are used by sign/zero extend operations.