Skip to content

[clang][CodeGen] Add range metadata for atomic load of boolean type. #131476 #133546

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Apr 14, 2025

Conversation

janagor
Copy link
Contributor

@janagor janagor commented Mar 29, 2025

Addresses #131476.

For x86_64 it folds

movzbl	t1(%rip), %eax
andb	$1, %al

into

movzbl	t1(%rip), %eax

when run: clang -S atomic-ops-load.c -o atomic-ops-load.s -O1 --target=x86_64.

But for riscv replaces:

lb	a0, %lo(t1)(a0)
andi	a0, a0, 1

with

lb	a0, %lo(t1)(a0)
zext.b	a0, a0

when run: clang -S atomic-ops-load.c -o atomic-ops-load.s -O1 --target=riscv64.

Copy link

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 llvmbot added clang Clang issues not falling into any other category clang:codegen IR generation bugs: mangling, exceptions, etc. labels Mar 29, 2025
@llvmbot
Copy link
Member

llvmbot commented Mar 29, 2025

@llvm/pr-subscribers-backend-powerpc
@llvm/pr-subscribers-clang

@llvm/pr-subscribers-clang-codegen

Author: Jan Górski (janagor)

Changes

Addresses #131476.

For x86_64 it folds

movzbl	t1(%rip), %eax
andb	$1, %al

into

movzbl	t1(%rip), %eax

when run: clang -S atomic-ops-load.c -o atomic-ops-load.s -O1 --target=x86_64.

But for riscv replaces:

lb	a0, %lo(t1)(a0)
andi	a0, a0, 1

with

lb	a0, %lo(t1)(a0)
zext.b	a0, a0

when run: when run clang -S atomic-ops-load.c -o atomic-ops-load.s -O1 --target=riscv64`.


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

2 Files Affected:

  • (modified) clang/lib/CodeGen/CGAtomic.cpp (+23)
  • (added) clang/test/CodeGen/atomic-ops-load.c (+11)
diff --git a/clang/lib/CodeGen/CGAtomic.cpp b/clang/lib/CodeGen/CGAtomic.cpp
index 3adb2a7ad207f..2c9613deef744 100644
--- a/clang/lib/CodeGen/CGAtomic.cpp
+++ b/clang/lib/CodeGen/CGAtomic.cpp
@@ -590,6 +590,29 @@ static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, Address Dest,
     llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr);
     Load->setAtomic(Order, Scope);
     Load->setVolatile(E->isVolatile());
+
+    if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
+      CGF.Builder.CreateStore(Load, Dest);
+      return;
+    }
+
+    QualType Ty = E->getValueType();
+    if (!Ty->isBooleanType()) {
+      CGF.Builder.CreateStore(Load, Dest);
+      return;
+    }
+
+    llvm::MDBuilder MDHelper(CGF.getLLVMContext());
+    llvm::APInt BooleanMin = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
+    llvm::APInt BooleanEnd = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
+
+    if (llvm::MDNode *RangeInfo =
+            MDHelper.createRange(BooleanMin, BooleanEnd)) {
+      Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
+      Load->setMetadata(llvm::LLVMContext::MD_noundef,
+                        llvm::MDNode::get(CGF.getLLVMContext(), {}));
+    }
+
     CGF.Builder.CreateStore(Load, Dest);
     return;
   }
diff --git a/clang/test/CodeGen/atomic-ops-load.c b/clang/test/CodeGen/atomic-ops-load.c
new file mode 100644
index 0000000000000..778a7ebdc2618
--- /dev/null
+++ b/clang/test/CodeGen/atomic-ops-load.c
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -triple riscv64 -O1 -emit-llvm %s -o - | FileCheck %s
+#include <stdbool.h>
+
+extern bool t1;
+bool test1(void) {
+// CHECK-LABEL: define{{.*}} i1 @test1
+// CHECK: load atomic i8, ptr @t1 monotonic, align 1, !range ![[$WS_RANGE:[0-9]*]], !noundef !{{[0-9]+}}
+// CHECK-NEXT: trunc nuw i8 %{{.*}} to i1
+// CHECK-NEXT: ret i1 %{{.*}}
+  return __atomic_load_n(&t1, __ATOMIC_RELAXED);
+}

@janagor janagor changed the title Add range metadata for atomic load of boolean type. #131476 [clang][CodeGen] Add range metadata for atomic load of boolean type. #131476 Mar 31, 2025
llvm::APInt BooleanEnd = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);

if (llvm::MDNode *RangeInfo =
MDHelper.createRange(BooleanMin, BooleanEnd)) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Please refactor the code from CodeGenFunction::EmitLoadOfScalar, instead of reinventing the code to compute the range metadata.

QualType Ty = E->getValueType();
if (!Ty->isBooleanType()) {
CGF.Builder.CreateStore(Load, Dest);
return;
Copy link
Collaborator

Choose a reason for hiding this comment

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

Using an early return like this is weird; just stick a normal if statement around the code that creates the metadata.

@efriedma-quic
Copy link
Collaborator

I don't really understand what the new version of the patch is doing... instcombine can infer nuw on trunc if the operand has range metadata. There isn't any reason to duplicate that code.

@janagor
Copy link
Contributor Author

janagor commented Apr 10, 2025

I don't really understand what the new version of the patch is doing... instcombine can infer nuw on trunc if the operand has range metadata. There isn't any reason to duplicate that code.

The unoptimized version of the IR that is generated is as follows:

  %atomic-temp = alloca i8, align 1
  %0 = load atomic i8, ptr @t1 monotonic, align 1
  store i8 %0, ptr %atomic-temp, align 1
  %1 = load i8, ptr %atomic-temp, align 1
  %loadedv = trunc i8 %1 to i1
  ret i1 %loadedv

Lines 2-3 are generated by 'EmitAtomicOp' in CGAtomic, while CodeGenFunction::EmitLoadOfScalar adds range! only to line 4 when -O1. Lack of adding range! to 2nd line does not generate nuw at the end in trunc. From what I saw there were 2 ways to solve it: either add nuw the way I did it there, or add range! in EmitAtomicOp. I think in such case in order to no longer duplicate code would be to just make getRangeForLoadFromType a public method and use it for atomic load as well.

@efriedma-quic
Copy link
Collaborator

Oh, hmm, we have range metadata, but it gets killed by mem2reg. So instcombine could do the transform, but it runs too late. (In theory it could try to preserve range metadata; see convertMetadataToAssumes . But probably simpler here to just generate the markings.)

make getRangeForLoadFromType a public method and use it for atomic load as well

This seems fine.

@@ -590,6 +590,16 @@ static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, Address Dest,
llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr);
Load->setAtomic(Order, Scope);
Load->setVolatile(E->isVolatile());
QualType Ty = E->getValueType();
if (CGF.EmitScalarRangeCheck(Load, Ty, E->getExprLoc())) {
} else if (CGF.CGM.getCodeGenOpts().OptimizationLevel > 0) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Can you refactor more of the code? Instead of just getRangeForLoadFromType, make a helper that calls EmitScalarRangeCheck() and add the metadata.

…ng range metadata. Made `getRangeForLoadFromType` private function as it was before f25e687.
Copy link
Collaborator

@efriedma-quic efriedma-quic left a comment

Choose a reason for hiding this comment

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

LGTM

@efriedma-quic
Copy link
Collaborator

Not sure why automation didn't catch this, but:

⚠️ We detected that you are using a GitHub private e-mail address to contribute to the repo.
Please turn off Keep my email addresses private setting in your account.
See LLVM Discourse for more information.

@janagor
Copy link
Contributor Author

janagor commented Apr 14, 2025

Oh, I see, I changed it.

@efriedma-quic efriedma-quic merged commit ff687af into llvm:main Apr 14, 2025
11 checks passed
Copy link

@janagor 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!

var-const pushed a commit to ldionne/llvm-project that referenced this pull request Apr 17, 2025
…lvm#131476 (llvm#133546)

Fixes llvm#131476.

For `x86_64` it folds
```
movzbl	t1(%rip), %eax
andb	$1, %al
```
into
```
movzbl	t1(%rip), %eax
```
when run: `clang -S atomic-ops-load.c -o atomic-ops-load.s -O1
--target=x86_64`.

But for riscv replaces:
```
lb	a0, %lo(t1)(a0)
andi	a0, a0, 1
```
with
```
lb	a0, %lo(t1)(a0)
zext.b	a0, a0
``` 
when run: `clang -S atomic-ops-load.c -o atomic-ops-load.s -O1
--target=riscv64`.
@janagor janagor deleted the add_range_metadata branch April 27, 2025 16:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backend:PowerPC clang:codegen IR generation bugs: mangling, exceptions, etc. clang Clang issues not falling into any other category
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants