Skip to content

[llvm][GVN] Propagate trunc nuw to i1 equalities #143273

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Merged
merged 1 commit into from
Jun 8, 2025

Conversation

yashnator
Copy link
Contributor

@yashnator yashnator commented Jun 7, 2025

This patch adds to GVN's propagateEquality() to reason about equality constraints through trunc nuw iN to i1.

Given:
%tr = trunc nuw iN %v to i1

We can deduce that if %tr == true, then %v == 1, and if %tr == false, then %v == 0. This is valid because nuw guarantees that truncation didn't lose unsigned bits, so %v must have been either 0 or 1.

The patch adds logic to propagate this information via the GVN worklist. This enables further simplification opportunities downstream, such as folding redundant stores or conditionals that depend on %v.

Includes a test case in GVN/trunc-nuw-equality.ll.

Resolves #142744

Copy link

github-actions bot commented Jun 7, 2025

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@llvmbot
Copy link
Member

llvmbot commented Jun 7, 2025

@llvm/pr-subscribers-llvm-transforms

Author: Yash Solanki (yashnator)

Changes

This patch adds to GVN's propagateEquality() to reason about equality constraints through trunc nuw iN to i1.

Given:
%tr = trunc nuw iN %v to i1
br i1 %tr, ...

We can deduce that if %tr == true, then %v == 1, and if %tr == false, then %v == 0. This is valid because nuw guarantees that truncation didn't lose unsigned bits, so %v must have been either 0 or 1.

The patch adds logic to propagate this information via the GVN worklist. This enables further simplification opportunities downstream, such as folding redundant stores or conditionals that depend on %v.

Includes a test case in GVN/trunc-nuw-equality.ll.


Full diff: https://github.com/llvm/llvm-project/pull/143273.diff

2 Files Affected:

  • (modified) llvm/lib/Transforms/Scalar/GVN.cpp (+16)
  • (added) llvm/test/Transforms/GVN/trunc-nuw-equality.ll (+23)
diff --git a/llvm/lib/Transforms/Scalar/GVN.cpp b/llvm/lib/Transforms/Scalar/GVN.cpp
index 77ca14f88a834..046918d8cf6a2 100644
--- a/llvm/lib/Transforms/Scalar/GVN.cpp
+++ b/llvm/lib/Transforms/Scalar/GVN.cpp
@@ -2579,6 +2579,22 @@ bool GVNPass::propagateEquality(Value *LHS, Value *RHS,
 
       continue;
     }
+
+    // Propagate equality that result from truncation with no unsigned wrap
+    // like (trunc nuw i64 %v to i1) == "true" or (trunc nuw i64 %v to i1) ==
+    // "false"
+    if (auto *Trunc = dyn_cast<TruncInst>(LHS)) {
+      if (Trunc->hasNoUnsignedWrap() && Trunc->getType()->isIntegerTy(1)) {
+        Value *Input = Trunc->getOperand(0);
+        if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
+          if (CI->isZero()) {
+            Worklist.push_back({Input, ConstantInt::get(Input->getType(), 0)});
+          } else if (CI->isOne()) {
+            Worklist.push_back({Input, ConstantInt::get(Input->getType(), 1)});
+          }
+        }
+      }
+    }
   }
 
   return Changed;
diff --git a/llvm/test/Transforms/GVN/trunc-nuw-equality.ll b/llvm/test/Transforms/GVN/trunc-nuw-equality.ll
new file mode 100644
index 0000000000000..03d4a16aeaf20
--- /dev/null
+++ b/llvm/test/Transforms/GVN/trunc-nuw-equality.ll
@@ -0,0 +1,23 @@
+; RUN: opt -passes=gvn -S < %s | FileCheck %s
+
+define void @test(ptr %p, i64 %v) {
+; CHECK-LABEL: @test(
+; CHECK: %tr = trunc nuw i64 %v to i1
+; CHECK-NEXT: br i1 %tr, label %ret, label %store
+
+entry:
+  %tr = trunc nuw i64 %v to i1
+  br i1 %tr, label %ret, label %store
+
+store:
+  ; CHECK-LABEL: store:
+  ; CHECK: store i64 0, ptr %p
+  store i64 %v, ptr %p
+  ret void
+
+ret:
+  ; CHECK-LABEL: ret:
+  ; CHECK: store i64 1, ptr %p
+  store i64 %v, ptr %p
+  ret void
+}

Copy link
Contributor

@andjo403 andjo403 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

have not worked in GVN before but posted some comments.

Maybe not a question for this PR but is it possible to support not condition (xor i1 %tr, true) also?

@yashnator yashnator force-pushed the gvn-trunc-nuw branch 4 times, most recently from 4e7a479 to 30ede86 Compare June 7, 2025 22:48
Copy link

github-actions bot commented Jun 8, 2025

✅ With the latest revision this PR passed the C/C++ code formatter.

Copy link
Contributor

@nikic nikic left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

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 llvm#142744
Copy link
Contributor

@andjo403 andjo403 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you want help to merge?

@yashnator
Copy link
Contributor Author

@andjo403 Yes, that would be helpful. Thank you.

Maybe not a question for this PR but is it possible to support not condition (xor i1 %tr, true) also?

I tried out some examples but found out that visitXor is folding not instructions. Do you have an example where it is missed?

@andjo403
Copy link
Contributor

andjo403 commented Jun 8, 2025

@yashnator here is one example for the not link probably some easier way to trigger it but can not think of any now and I'm on my way out, will merge this PR when I'm back

@andjo403 andjo403 merged commit 73a351e into llvm:main Jun 8, 2025
7 checks passed
Copy link

github-actions bot commented Jun 8, 2025

@yashnator Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

# for free to join this conversation on GitHub. Already have an account? # to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Missed optimization of constant folding when using 'trunc nuw i64 %v to i1'
4 participants