Skip to content

[clang][CodeGen] Emit prefetch hints and frame address depth as i32 - #221477

Merged
efriedma-quic merged 4 commits into
llvm:mainfrom
zlfn:builtin
Sep 16, 2026
Merged

efriedma-quic merged 4 commits into
llvm:mainfrom
zlfn:builtin

Conversation

@zlfn

@zlfn zlfn commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

The hint operands of llvm.prefetch and the depth operand of llvm.frameaddress and llvm.returnaddress are declared as i32, but clang emitted the values at the width of the C argument's type.

__builtin_prefetch is declared with a variadic prototype, void(void const*, ...), so its hint arguments are never converted to a parameter type; only the default argument promotions apply. The depth argument is emitted at the type of unsigned int. Two cases end up with a width other than 32 bits:

Either way the emitted call does not match the intrinsic's signature. With assertions enabled this trips
assert(... "Calling a function with a bad signature!") in CallInst::init;

without them the verifier rejects the module:

$ clang -cc1 -triple msp430 -emit-llvm t.c -o -
  call void @llvm.prefetch.p0(ptr %0, i16 1, i16 3, i32 1)
  %0 = call ptr @llvm.frameaddress.p0(i16 0)
fatal error: error in backend: Broken module found, compilation aborted!

Zero-extend or truncate them to i32 before building the intrinsic call. The conversion is a no-op where the widths already match, and folds back to a constant, since Sema already requires these arguments to be constants in range.

This also removes the FIXME that pointed at the mismatch.

AI assistance helped me find the problem and work out the fix, but I wrote the code myself.

Assisted-by: Claude Opus 5

Fixes #202061, Fixes #222910

Co-authored-by: mygitljf 2410316423@qq.com

The hint operands of llvm.prefetch and the depth operand of
llvm.frameaddress and llvm.returnaddress are declared as i32, but clang
emitted the values at the width of the C argument's type.

Zero-extend or truncate them to i32 before building the intrinsic call.
The conversion is a no-op where the widths already match, and folds back
to a constant, since Sema already requires these arguments to be
constants in range.
@github-actions

github-actions Bot commented Sep 5, 2026

Copy link
Copy Markdown

Hello @zlfn 👋

Thank you for submitting a Pull Request (PR) to the LLVM Project. Since this is your first PR, here are a few useful links covering our main contribution policies and review practices.

  • All contributions to LLVM must follow our LLVM AI Tool Use Policy. In particular, if you used AI while working on this PR, remember to add a note to the PR description.
  • The LLVM Code-Review Policy and Practices document contains practical information about the PR process, including how patches are reviewed and accepted, and who can review a PR.
  • Our LLVM Developer Policy describes our expectations for code quality, commit summaries and contains notes on our CI system.

Please reply to this message to confirm that you have read these policies, especially the LLVM AI Tool Use Policy, and that any AI tool usage has been noted in the PR description.


Frequently asked questions

How do I add reviewers?

This PR will be automatically labeled, and the relevant teams will be notified. For some parts of the project, reviewers may also be added automatically.

You can also add reviewers manually using the Reviewers section on this page. If you cannot use that section, it is probably because you do not have write permissions for the repository. In that case, you can request a review by tagging reviewers in a comment using @ followed by their GitHub username.

What if there are no comments?

If you have not received any comments on your PR after a week, you can request a review by pinging the PR with a comment such as “Ping”. The common courtesy ping rate is once a week. Please remember that you are asking for volunteer time from other developers.

Are any special GitHub settings required to contribute to LLVM?

We only require contributors to have a public email address associated with their GitHub commits, see this section of LLVM Developer Policy for details.


If you have questions, feel free to leave a comment on this PR, or ask on LLVM Discord or LLVM Discourse.

Thank you,
The LLVM Community

@llvmorg-github-actions llvmorg-github-actions Bot added clang Clang issues not falling into any other category clang:codegen IR generation bugs: mangling, exceptions, etc. labels Sep 5, 2026
@llvmorg-github-actions

llvmorg-github-actions Bot commented Sep 5, 2026 •

Copy link
Copy Markdown

@llvm/pr-subscribers-clang

@llvm/pr-subscribers-clang-codegen

Author: Kiroo (Chanung) (zlfn)

Changes

The hint operands of llvm.prefetch and the depth operand of llvm.frameaddress and llvm.returnaddress are declared as i32, but clang emitted the values at the width of the C argument's type.

__builtin_prefetch is declared with a variadic prototype, void(void const*, ...), so its hint arguments are never converted to a parameter type; only the default argument promotions apply. The depth argument is emitted at the type of unsigned int. Two cases end up with a width other than 32 bits:

  • Targets whose int is 16 bits, such as MSP430 and AVR.
    Plain __builtin_prefetch(p, 1, 3) or __builtin_frame_address(0) is hit this.
  • An argument written with a type wider than 32 bits, on any target.
    __builtin_prefetch(p, 1L, 3L) reproduces this on LP64 targets
    __builtin_prefetch(p, 1LL, 3LL) reproduces this on 32 bit targets

Either way the emitted call does not match the intrinsic's signature. With assertions enabled this trips
assert(... "Calling a function with a bad signature!") in CallInst::init;

without them the verifier rejects the module:

$ clang -cc1 -triple msp430 -emit-llvm t.c -o -
  call void @<!-- -->llvm.prefetch.p0(ptr %0, i16 1, i16 3, i32 1)
  %0 = call ptr @<!-- -->llvm.frameaddress.p0(i16 0)
fatal error: error in backend: Broken module found, compilation aborted!

Zero-extend or truncate them to i32 before building the intrinsic call. The conversion is a no-op where the widths already match, and folds back to a constant, since Sema already requires these arguments to be constants in range.

This also removes the FIXME that pointed at the mismatch.


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

3 Files Affected:

  • (modified) clang/lib/CodeGen/CGBuiltin.cpp (+4-1)
  • (added) clang/test/CodeGen/builtin-frame-address-arg-type.c (+16)
  • (added) clang/test/CodeGen/builtin-prefetch-arg-type.c (+22)
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index f4598a8a54e1b..034c1cbfbdc40 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -4117,12 +4117,13 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
   case Builtin::BI__builtin_prefetch: {
     Value *Locality, *RW, *Address = EmitScalarExpr(E->getArg(0));
     unsigned ICEArguments = (1 << 1) | (1 << 2);
-    // FIXME: Technically these constants should of type 'int', yes?
     RW = (E->getNumArgs() > 1) ? EmitScalarOrConstFoldImmArg(ICEArguments, 1, E)
                                : llvm::ConstantInt::get(Int32Ty, 0);
+    RW = Builder.CreateZExtOrTrunc(RW, Int32Ty);
     Locality = (E->getNumArgs() > 2)
                    ? EmitScalarOrConstFoldImmArg(ICEArguments, 2, E)
                    : llvm::ConstantInt::get(Int32Ty, 3);
+    Locality = Builder.CreateZExtOrTrunc(Locality, Int32Ty);
     Value *Data = llvm::ConstantInt::get(Int32Ty, 1);
     Function *F = CGM.getIntrinsic(Intrinsic::prefetch, Address->getType());
     Builder.CreateCall(F, {Address, RW, Locality, Data});
@@ -5135,6 +5136,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
   case Builtin::BI__builtin_return_address: {
     Value *Depth = ConstantEmitter(*this).emitAbstract(E->getArg(0),
                                                    getContext().UnsignedIntTy);
+    Depth = Builder.CreateZExtOrTrunc(Depth, Int32Ty);
     Function *F =
         CGM.getIntrinsic(Intrinsic::returnaddress, {CGM.ProgramPtrTy});
     return RValue::get(Builder.CreateCall(F, Depth));
@@ -5147,6 +5149,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
   case Builtin::BI__builtin_frame_address: {
     Value *Depth = ConstantEmitter(*this).emitAbstract(E->getArg(0),
                                                    getContext().UnsignedIntTy);
+    Depth = Builder.CreateZExtOrTrunc(Depth, Int32Ty);
     Function *F = CGM.getIntrinsic(Intrinsic::frameaddress, AllocaInt8PtrTy);
     return RValue::get(Builder.CreateCall(F, Depth));
   }
diff --git a/clang/test/CodeGen/builtin-frame-address-arg-type.c b/clang/test/CodeGen/builtin-frame-address-arg-type.c
new file mode 100644
index 0000000000000..91cd94ec32072
--- /dev/null
+++ b/clang/test/CodeGen/builtin-frame-address-arg-type.c
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -triple x86_64-pc-linux -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -triple msp430 -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -triple avr -emit-llvm %s -o - | FileCheck %s
+
+// The depth operand of these intrinsics is i32 regardless of the width of
+// unsigned int on the target.
+
+void *test_return_address(void) {
+  // CHECK: call{{.*}} @llvm.returnaddress.p{{[0-9]}}(i32 0)
+  return __builtin_return_address(0);
+}
+
+void *test_frame_address(void) {
+  // CHECK: call{{.*}} @llvm.frameaddress.p{{[0-9]}}(i32 0)
+  return __builtin_frame_address(0);
+}
diff --git a/clang/test/CodeGen/builtin-prefetch-arg-type.c b/clang/test/CodeGen/builtin-prefetch-arg-type.c
new file mode 100644
index 0000000000000..c2481f1e77dde
--- /dev/null
+++ b/clang/test/CodeGen/builtin-prefetch-arg-type.c
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 -triple x86_64-pc-linux -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -triple msp430 -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -triple avr -emit-llvm %s -o - | FileCheck %s
+
+// The hint operands of llvm.prefetch are i32 regardless of the type of the
+// corresponding C argument, which is narrower on targets with a 16-bit int and
+// wider when the caller passes a long.
+
+void test_int(void *p) {
+  // CHECK: call{{.*}} void @llvm.prefetch.p0(ptr {{%.+}}, i32 1, i32 3, i32 1)
+  __builtin_prefetch(p, 1, 3);
+}
+
+void test_long(void *p) {
+  // CHECK: call{{.*}} void @llvm.prefetch.p0(ptr {{%.+}}, i32 1, i32 3, i32 1)
+  __builtin_prefetch(p, 1L, 3L);
+}
+
+void test_defaulted_hints(void *p) {
+  // CHECK: call{{.*}} void @llvm.prefetch.p0(ptr {{%.+}}, i32 0, i32 3, i32 1)
+  __builtin_prefetch(p);
+}

@zlfn

zlfn commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

Found while running the GCC C torture test suite against an out-of-tree 8-bit target.

@zlfn

zlfn commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

#202111 covers the prefetch hints at the Sema level. A fix at that level works for machines with a 32-bit or wider int, but it does not address the problem on targets with 16-bit int.

Converting the arguments to int will still produce a mismatch on targets where int is not 32 bits.

The review on that PR asks for the conversion to be done in Sema rather than in CodeGen,
but I think it belongs in CodeGen.

@efriedma-quic, would you mind taking a look?

@zlfn

zlfn commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

Also, this PR resolves #202061 when merged.

@zlfn

zlfn commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Hello, @topperc
it seems that you most recently reviewed this section, and if you have time, I would appreciate it if you could look at this as well.

@efriedma-quic

Copy link
Copy Markdown
Contributor

For __builtin_returnaddress, the argument type is explicitly "int"; I guess converting it makes sense given the required form for LLVM.

For __builtin_prefetch, it looks like we're just not doing any conversions at all in Sema, which is wrong; SemaChecking should be doing lvalue-to-rvalue conversion, and converting to some reasonable type. I guess at that point, if the chosen type is int, you still end up needing to do a conversion on some targets, but still, I'd like to fix it while we're looking at this.

Co-authored-by: mygitljf <2410316423@qq.com>
@llvmorg-github-actions llvmorg-github-actions Bot added the clang:frontend Language frontend issues, e.g. anything involving "Sema" label Sep 8, 2026
@zlfn

zlfn commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor Author

@efriedma-quic I have added the conversion on the Sema side. I wrote this code myself,
but since @mygitljf already has an open PR for it, I added them as a co-author on this PR (Please let me know if you would rather I did not.)

@zlfn

zlfn commented Sep 8, 2026

Copy link
Copy Markdown
Contributor Author

I ran BuiltinConstantArgRange() before convertArgumentToType(), which is the opposite of what you suggested on #202111.

Converting first changes which calls are accepted. For example, __builtin_prefetch(p, 0x100000001LL) is an error for now; but after the conversion it becomes 1. Of course, warnings will occur, but I thought it isn't good, so I wrote code this way.

@efriedma-quic

Copy link
Copy Markdown
Contributor

The reason to do the conversions first is that sometimes you can't evaluate the unconverted value. For example, you can do struct S { int x; constexpr operator unsigned int() const { return x; } }; constexpr S x = {1}; void *f() { return __builtin_frame_address(x);}.

@zlfn

zlfn commented Sep 9, 2026

Copy link
Copy Markdown
Contributor Author

That makes sense; I missed that part. I switched the order as you suggested.

@zlfn

zlfn commented Sep 13, 2026

Copy link
Copy Markdown
Contributor Author

This PR resovles #222910 too.

@zlfn

zlfn commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

@efriedma-quic Could you please review this changes when you have a moment?

@efriedma-quic efriedma-quic left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

@zlfn

zlfn commented Sep 16, 2026

Copy link
Copy Markdown
Contributor Author

@efriedma-quic Thanks for the review! I don’t have repository write permissions, so could you merge this for me?

@efriedma-quic
efriedma-quic merged commit e141b66 into llvm:main Sep 16, 2026
12 checks passed
@github-actions

Copy link
Copy Markdown

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clang:codegen IR generation bugs: mangling, exceptions, etc. clang:frontend Language frontend issues, e.g. anything involving "Sema" clang Clang issues not falling into any other category

Projects

None yet

2 participants