https://github.com/shiltian created https://github.com/llvm/llvm-project/pull/244964
In OpenCL and SYCL, `TryAddressSpaceCast` rejects a pointer cast between two address spaces that don't overlap, but a C-style cast to a reference is not checked (there is a FIXME for it). As a result, `(__local int &)global_var` is accepted and we emit an `addrspacecast`. This PR checks such reference casts in the same way. We only check the case where the reference binds to the operand directly, i.e. the two types are related. Other casts to a reference are not affected. This PR was assisted by AI but I reviewed all the changes. >From 79a0b1e9320cf6397bfd6882ec09bb8c3f90ac89 Mon Sep 17 00:00:00 2001 From: Shilei Tian <[email protected]> Date: Sat, 21 Nov 2026 17:52:21 -0500 Subject: [PATCH] [Clang] Check address space overlap for C-style casts to references In OpenCL and SYCL, `TryAddressSpaceCast` rejects a pointer cast between two address spaces that don't overlap, but a C-style cast to a reference is not checked (there is a FIXME for it). As a result, `(__local int &)global_var` is accepted and we emit an `addrspacecast`. This PR checks such reference casts in the same way. We only check the case where the reference binds to the operand directly, i.e. the two types are related. Other casts to a reference are not affected. This PR was assisted by AI but I reviewed all the changes. --- clang/lib/Sema/SemaCast.cpp | 33 +++++++++- .../address-space-reference-casts.clcpp | 65 +++++++++++++++++++ .../address-space-array-reference-casts.cpp | 10 +++ .../SemaSYCL/address-space-conversions.cpp | 3 + 4 files changed, 108 insertions(+), 3 deletions(-) create mode 100644 clang/test/SemaOpenCLCXX/address-space-reference-casts.clcpp create mode 100644 clang/test/SemaSYCL/address-space-array-reference-casts.cpp diff --git a/clang/lib/Sema/SemaCast.cpp b/clang/lib/Sema/SemaCast.cpp index da69fde4ce1c97..b01bc1e9350c07 100644 --- a/clang/lib/Sema/SemaCast.cpp +++ b/clang/lib/Sema/SemaCast.cpp @@ -2669,9 +2669,36 @@ static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr, // non-OpenCL mode too, we fast-path above because no other languages // define overlapping address spaces currently. auto SrcType = SrcExpr.get()->getType(); - // FIXME: Should this be generalized to references? The reference parameter - // however becomes a reference pointee type here and therefore rejected. - // Perhaps this is the right behavior though according to C++. + // A C-style cast to a reference, including the functional form `T(x)`, can + // bind the reference to the operand directly. In that case, it is basically + // the same as casting a pointer to another address space, so we apply the + // same overlap check here. This only happens when the two types are related, + // i.e. the same type, a base class, or a derived class in a downcast. Other + // casts to a reference, e.g. the ones that create a temporary, call a + // conversion function, or reinterpret the operand, are handled elsewhere. + if (const auto *DestRefType = DestType->getAs<ReferenceType>()) { + QualType DestPointeeType = DestRefType->getPointeeType(); + if (!CStyle || !SrcExpr.get()->isGLValue() || + DestPointeeType.isAddressSpaceOverlapping(SrcType, + Self.getASTContext())) + return TC_NotApplicable; + // Compare the types without qualifiers, because the check above already + // looked at the address spaces. + QualType Src = Self.Context.getUnqualifiedArrayType(SrcType); + QualType Dest = Self.Context.getUnqualifiedArrayType(DestPointeeType); + SourceLocation Loc = SrcExpr.get()->getBeginLoc(); + // As in static_cast, a downcast needs an lvalue operand or an rvalue + // reference type. + bool CanDowncast = + SrcExpr.get()->isLValue() || DestType->isRValueReferenceType(); + if (Self.CompareReferenceRelationship(Loc, Dest, Src) == + Sema::Ref_Incompatible && + (!CanDowncast || Self.CompareReferenceRelationship(Loc, Src, Dest) == + Sema::Ref_Incompatible)) + return TC_NotApplicable; + msg = diag::err_bad_cxx_cast_addr_space_mismatch; + return TC_Failed; + } auto SrcPtrType = SrcType->getAs<PointerType>(); if (!SrcPtrType) return TC_NotApplicable; diff --git a/clang/test/SemaOpenCLCXX/address-space-reference-casts.clcpp b/clang/test/SemaOpenCLCXX/address-space-reference-casts.clcpp new file mode 100644 index 00000000000000..dc0581fb2e4197 --- /dev/null +++ b/clang/test/SemaOpenCLCXX/address-space-reference-casts.clcpp @@ -0,0 +1,65 @@ +// RUN: %clang_cc1 %s -triple spir-unknown-unknown -pedantic -verify -fsyntax-only + +// A C-style or functional cast to a reference type that binds the reference to +// the operand cannot convert between address spaces that do not overlap, as +// the corresponding pointer cast cannot. A cast that makes a temporary, or +// uses a conversion function, is unaffected. + +typedef __local int &LocalRef; + +struct S { + int x; +}; + +struct Base { + int x; +}; + +struct Derived : Base {}; + +struct Conv { + operator __local int &(); +}; + +void casts(__global int &g, __constant int &c, __global S &gs, __global Base &gb, __global Derived &gd, Conv conv) { + (void)(__local int &)g; // expected-error {{C-style cast from '__global int' to '__local int &' converts between mismatching address spaces}} + (void)LocalRef(g); // expected-error {{functional-style cast from '__global int' to 'LocalRef' (aka '__local int &') converts between mismatching address spaces}} + (void)(int &)c; // expected-error {{C-style cast from '__constant int' to '__generic int &' converts between mismatching address spaces}} + (void)(__local int &&)g; // expected-error {{C-style cast from '__global int' to '__local int &&' converts between mismatching address spaces}} + (void)(__local S &)gs; // expected-error {{C-style cast from '__global S' to '__local S &' converts between mismatching address spaces}} + (void)(__local Base &)gd; // expected-error {{C-style cast from '__global Derived' to '__local Base &' converts between mismatching address spaces}} + (void)(__local Derived &)gb; // expected-error {{C-style cast from '__global Base' to '__local Derived &' converts between mismatching address spaces}} + (__local int &)g = 1; // expected-error {{C-style cast from '__global int' to '__local int &' converts between mismatching address spaces}} + + // addrspace_cast takes pointers only. + (void)addrspace_cast<__local int &>(g); // expected-error {{addrspace_cast from '__global int' to '__local int &' is not allowed}} + + // The address spaces overlap, the cast makes a temporary, or it uses a + // conversion function. + (void)(int &)g; + (void)(__global float &)g; + (void)(const __global int &)g; + (void)(float &&)c; + (void)(__local int &)conv; +} + +// The reference check is for C-style and functional casts only, so +// addrspace_cast to a reference does not complete the class, and fails in the +// immediate context. +template <class T> struct Box { typename T::missing value; }; +template <class T> +auto choose(T &x, int) -> decltype(addrspace_cast<__local int &>(x)); +template <class T> int choose(T &, long); +int use(__global Box<int> &x) { return ::choose(x, 0); } + +// A downcast needs an lvalue, or an xvalue for an rvalue reference. Otherwise +// the cast calls the conversion function. +struct ConvDerived; +struct ConvBase { + operator __local ConvDerived &(); +}; +struct ConvDerived : ConvBase { + int value; +}; +__global ConvBase &&get(); +int conversion() { return ((__local ConvDerived &)get()).value; } diff --git a/clang/test/SemaSYCL/address-space-array-reference-casts.cpp b/clang/test/SemaSYCL/address-space-array-reference-casts.cpp new file mode 100644 index 00000000000000..3997041e699318 --- /dev/null +++ b/clang/test/SemaSYCL/address-space-array-reference-casts.cpp @@ -0,0 +1,10 @@ +// RUN: %clang_cc1 -fsycl-is-device -std=c++20 -verify -fsyntax-only %s + +// In C++20 a reference to an array of unknown bound binds to an array of known +// bound, so a C-style cast to it cannot convert between address spaces that +// do not overlap either. +void f(int [[clang::sycl_global]] (&g)[4]) { + (void)(int [[clang::sycl_global]] (&)[])g; + (void)(int [[clang::sycl_local]] (&)[])g; // expected-error {{C-style cast from '[[clang::sycl_global]] int[4]' to '[[clang::sycl_local]] int (&)[]' converts between mismatching address spaces}} + (void)(int [[clang::sycl_local]] (&)[4])g; // expected-error {{C-style cast from '[[clang::sycl_global]] int[4]' to '[[clang::sycl_local]] int (&)[4]' converts between mismatching address spaces}} +} diff --git a/clang/test/SemaSYCL/address-space-conversions.cpp b/clang/test/SemaSYCL/address-space-conversions.cpp index 442dbc5f1e5ea8..789d7ad51563b2 100644 --- a/clang/test/SemaSYCL/address-space-conversions.cpp +++ b/clang/test/SemaSYCL/address-space-conversions.cpp @@ -58,6 +58,9 @@ void usages() { // Explicit casts between disjoint address spaces are disallowed GLOB = (int [[clang::sycl_global]] *)PRIV; // expected-error {{C-style cast from '[[clang::sycl_private]] int *' to '[[clang::sycl_global]] int *' converts between mismatching address spaces}} + (void)(int [[clang::sycl_global]] &)*PRIV; // expected-error {{C-style cast from '[[clang::sycl_private]] int' to '[[clang::sycl_global]] int &' converts between mismatching address spaces}} + (void)(int [[clang::sycl_local]] &)*GLOB; // expected-error {{C-style cast from '[[clang::sycl_global]] int' to '[[clang::sycl_local]] int &' converts between mismatching address spaces}} + (void)(int &)*GLOB; (void)static_cast<int *>(GLOB); (void)static_cast<void *>(GLOB); _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
