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