Skip to content

Commit

Permalink
[SCEV] Fix incorrect extension in computeConstantDifference()
Browse files Browse the repository at this point in the history
The Mul factor was zero-extended here, resulting in incorrect
results for integers larger than 64-bit.

As we currently only multiply by 1 or -1, just split this into
two cases -- there's no need for a full multiplication here.

Fixes #102597.
  • Loading branch information
nikic committed Aug 12, 2024
1 parent 513c372 commit 3512bcc
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
11 changes: 8 additions & 3 deletions llvm/lib/Analysis/ScalarEvolution.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11961,9 +11961,14 @@ ScalarEvolution::computeConstantDifference(const SCEV *More, const SCEV *Less) {
SmallDenseMap<const SCEV *, int, 8> Multiplicity;
APInt Diff(BW, 0);
auto Add = [&](const SCEV *S, int Mul) {
if (auto *C = dyn_cast<SCEVConstant>(S))
Diff += C->getAPInt() * Mul;
else
if (auto *C = dyn_cast<SCEVConstant>(S)) {
if (Mul == 1) {
Diff += C->getAPInt();
} else {
assert(Mul == -1);
Diff -= C->getAPInt();
}
} else
Multiplicity[S] += Mul;
};
auto Decompose = [&](const SCEV *S, int Mul) {
Expand Down
5 changes: 3 additions & 2 deletions llvm/test/Transforms/IndVarSimplify/pr102597.ll
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
; NOTE: Assertions have been autogenerated by utils/update_test_checks.py UTC_ARGS: --version 5
; RUN: opt -S -passes=indvars < %s | FileCheck %s

; FIXME: This is a miscompile.
; The %tobool condition should not be optimized away.
define void @test() {
; CHECK-LABEL: define void @test() {
; CHECK-NEXT: [[ENTRY:.*]]:
; CHECK-NEXT: br label %[[LOOP:.*]]
; CHECK: [[LOOP]]:
; CHECK-NEXT: [[IV:%.*]] = phi i128 [ 3, %[[ENTRY]] ], [ [[IV_DEC:%.*]], %[[LOOP_LATCH:.*]] ]
; CHECK-NEXT: br i1 true, label %[[LOOP_LATCH]], label %[[IF:.*]]
; CHECK-NEXT: [[TOBOOL:%.*]] = icmp ne i128 [[IV]], 0
; CHECK-NEXT: br i1 [[TOBOOL]], label %[[LOOP_LATCH]], label %[[IF:.*]]
; CHECK: [[IF]]:
; CHECK-NEXT: call void @foo()
; CHECK-NEXT: br label %[[LOOP_LATCH]]
Expand Down

0 comments on commit 3512bcc

Please sign in to comment.