diff --git a/llvm/lib/Analysis/ScalarEvolution.cpp b/llvm/lib/Analysis/ScalarEvolution.cpp --- a/llvm/lib/Analysis/ScalarEvolution.cpp +++ b/llvm/lib/Analysis/ScalarEvolution.cpp @@ -10561,7 +10561,13 @@ if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) BECount = BECountIfBackedgeTaken; else { - End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); + // If we know that RHS >= Start in the context of loop, then we know that + // max(RHS, Start) = RHS at this point. + if (isLoopEntryGuardedByCond( + L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, RHS, Start)) + End = RHS; + else + End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); } diff --git a/llvm/test/Analysis/ScalarEvolution/smin-smax-folds.ll b/llvm/test/Analysis/ScalarEvolution/smin-smax-folds.ll --- a/llvm/test/Analysis/ScalarEvolution/smin-smax-folds.ll +++ b/llvm/test/Analysis/ScalarEvolution/smin-smax-folds.ll @@ -98,13 +98,13 @@ ; CHECK-LABEL: 'smax_simplify_with_guard' ; CHECK-NEXT: Classifying expressions for: @smax_simplify_with_guard ; CHECK-NEXT: %k.0.i26 = phi i32 [ %start, %loop.ph ], [ %inc.i, %loop ] -; CHECK-NEXT: --> {%start,+,1}<%loop> U: full-set S: full-set Exits: (%start smax %n) LoopDispositions: { %loop: Computable } +; CHECK-NEXT: --> {%start,+,1}<%loop> U: full-set S: full-set Exits: %n LoopDispositions: { %loop: Computable } ; CHECK-NEXT: %inc.i = add nsw i32 %k.0.i26, 1 -; CHECK-NEXT: --> {(1 + %start),+,1}<%loop> U: full-set S: full-set Exits: (1 + (%start smax %n)) LoopDispositions: { %loop: Computable } +; CHECK-NEXT: --> {(1 + %start),+,1}<%loop> U: full-set S: full-set Exits: (1 + %n) LoopDispositions: { %loop: Computable } ; CHECK-NEXT: Determining loop execution counts for: @smax_simplify_with_guard -; CHECK-NEXT: Loop %loop: backedge-taken count is ((-1 * %start) + (%start smax %n)) +; CHECK-NEXT: Loop %loop: backedge-taken count is ((-1 * %start) + %n) ; CHECK-NEXT: Loop %loop: max backedge-taken count is -1 -; CHECK-NEXT: Loop %loop: Predicated backedge-taken count is ((-1 * %start) + (%start smax %n)) +; CHECK-NEXT: Loop %loop: Predicated backedge-taken count is ((-1 * %start) + %n) ; CHECK-NEXT: Predicates: ; CHECK: Loop %loop: Trip multiple is 1 entry: