Skip to content

Commit 30ede86

Browse files
committed
[GVN] Propagate equality from trunc nuw iN to i1
If the result of `trunc nuw iN` is known to be true/false, the original value of the truncated integer can be inferred. This is folded under GVN's propagateEquality. Fixes missed optimization noted in #142744
1 parent d570409 commit 30ede86

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

llvm/lib/Transforms/Scalar/GVN.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2579,6 +2579,17 @@ bool GVNPass::propagateEquality(Value *LHS, Value *RHS,
25792579

25802580
continue;
25812581
}
2582+
2583+
// Propagate equality that result from truncation with no unsigned wrap
2584+
// like (trunc nuw i64 %v to i1) == "true" or (trunc nuw i64 %v to i1) ==
2585+
// "false"
2586+
if (auto *Trunc = dyn_cast<TruncInst>(LHS)) {
2587+
if (Trunc->hasNoUnsignedWrap() && Trunc->getType()->isIntegerTy(1)) {
2588+
Value *Input = Trunc->getOperand(0);
2589+
Worklist.push_back({Input,
2590+
ConstantInt::get(Input->getType(), IsKnownTrue)});
2591+
}
2592+
}
25822593
}
25832594

25842595
return Changed;
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
; NOTE: Assertions have been autogenerated by utils/update_test_checks.py UTC_ARGS: --version 5
2+
; RUN: opt -passes=gvn -S < %s | FileCheck %s
3+
4+
define void @test(ptr %p, i64 %v) {
5+
; CHECK-LABEL: define void @test(
6+
; CHECK-SAME: ptr [[P:%.*]], i64 [[V:%.*]]) {
7+
; CHECK-NEXT: [[ENTRY:.*:]]
8+
; CHECK-NEXT: [[TR:%.*]] = trunc nuw i64 [[V]] to i1
9+
; CHECK-NEXT: br i1 [[TR]], label %[[RET:.*]], label %[[STORE:.*]]
10+
; CHECK: [[STORE]]:
11+
; CHECK-NEXT: store i64 0, ptr [[P]], align 4
12+
; CHECK-NEXT: ret void
13+
; CHECK: [[RET]]:
14+
; CHECK-NEXT: store i64 1, ptr [[P]], align 4
15+
; CHECK-NEXT: ret void
16+
;
17+
entry:
18+
%tr = trunc nuw i64 %v to i1
19+
br i1 %tr, label %ret, label %store
20+
21+
store:
22+
store i64 %v, ptr %p
23+
ret void
24+
25+
ret:
26+
store i64 %v, ptr %p
27+
ret void
28+
}

0 commit comments

Comments
 (0)