Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions clang/include/clang/Basic/DiagnosticSemaKinds.td
Original file line number Diff line number Diff line change
Expand Up @@ -13993,6 +13993,12 @@ def warn_sycl_old_and_new_kernel_attributes : Warning<
"kernel has both attribute %0 and kernel properties; if the kernel "
"properties contains the property \"%1\" it will be ignored">,
InGroup<IgnoredAttributes>;
def err_sycl_khr_kernel_property_attr_mismatch : Error<
"%0 attribute arguments '%1' do not match the value '%2' of kernel property "
"'sycl::khr::property::%3' embedded by "
"'get(sycl::khr::property::tag::kernel)'">;
def note_sycl_khr_kernel_properties_getter : Note<
"kernel properties are embedded by this member function">;
def err_attribute_argument_is_not_valid : Error<
"%0 attribute requires integer constant value 0 or 1">;
def warn_sycl_work_group_scope_dtor : Warning<
Expand Down
3 changes: 3 additions & 0 deletions clang/include/clang/Sema/SemaSYCL.h
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,9 @@ class SemaSYCL : public SemaBase {
void handleSYCLRegisteredKernels(Decl *D, const ParsedAttr &AL);

void checkSYCLAddIRAttributesFunctionAttrConflicts(Decl *D);
// Diagnoses kernel attributes that do not match the kernel properties
// embedded by 'get(sycl::khr::property::tag::kernel)'.
void checkSYCLKhrKernelPropertiesAttrConflicts(Decl *D);

SYCLReqdWorkGroupSizeAttr *
mergeSYCLReqdWorkGroupSizeAttr(Decl *D, const SYCLReqdWorkGroupSizeAttr &A);
Expand Down
1 change: 1 addition & 0 deletions clang/lib/Sema/SemaSYCL.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5920,6 +5920,7 @@ void SemaSYCL::MarkDevices() {
PropagateAndDiagnoseDeviceAttr(*this, A, T.GetSYCLKernel(),
T.GetKernelBody());
checkSYCLAddIRAttributesFunctionAttrConflicts(T.GetSYCLKernel());
checkSYCLKhrKernelPropertiesAttrConflicts(T.GetSYCLKernel());
}
}

Expand Down
192 changes: 192 additions & 0 deletions clang/lib/Sema/SemaSYCLDeclAttr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@
#include "clang/Basic/TargetInfo.h"
#include "clang/Sema/Attr.h"
#include "clang/Sema/Initialization.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/ParsedAttr.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/SemaSYCL.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/TargetParser/NVPTXTargetParser.h"

using namespace clang;
Expand Down Expand Up @@ -1721,6 +1723,196 @@ void SemaSYCL::checkSYCLAddIRAttributesFunctionAttrConflicts(Decl *D) {
<< Attr << PotentialConflictProp;
}

// Returns true if \p Ty is 'sycl::khr::property::tag::kernel'.
static bool isKhrKernelPropertiesTagType(QualType Ty) {
const auto *RD = Ty.getNonReferenceType()->getAsCXXRecordDecl();
if (!RD || !RD->getIdentifier() || RD->getName() != "kernel")
return false;
const DeclContext *DC = RD->getDeclContext();
for (StringRef NS : {"tag", "property", "khr"}) {
const auto *ND = dyn_cast<NamespaceDecl>(DC);
if (!ND || !ND->getIdentifier() || ND->getName() != NS)
return false;
DC = ND->getDeclContext();
}
// Skip the inline ABI namespace(s).
while (isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->isInline())
DC = DC->getParent();
const auto *ND = dyn_cast<NamespaceDecl>(DC);
return ND && ND->getIdentifier() && ND->getName() == "sycl" &&
ND->getDeclContext()->isTranslationUnit();
}

// Finds the const 'get(sycl::khr::property::tag::kernel)' member function of
// the kernel function object type \p RD (possibly inherited, possibly a member
// function template specialization) whose return type is deduced.
static const CXXMethodDecl *findKhrKernelPropertiesGetter(Sema &S,
CXXRecordDecl *RD) {
LookupResult R(S, &S.Context.Idents.get("get"), RD->getLocation(),
Sema::LookupMemberName);
if (!S.LookupQualifiedName(R, RD))
return nullptr;

auto IsGetter = [](const FunctionDecl *FD) {
const auto *MD = dyn_cast<CXXMethodDecl>(FD);
return MD && MD->isConst() && MD->getNumParams() == 1 &&
isKhrKernelPropertiesTagType(MD->getParamDecl(0)->getType()) &&
!MD->getReturnType()->isUndeducedType();
};
for (NamedDecl *ND : R) {
ND = ND->getUnderlyingDecl();
if (const auto *MD = dyn_cast<CXXMethodDecl>(ND); MD && IsGetter(MD))
return MD;
if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(ND))
for (const FunctionDecl *Spec : FTD->specializations())
if (IsGetter(Spec))
return cast<CXXMethodDecl>(Spec);
}
return nullptr;
}

namespace {
// The sycl_khr_kernel_properties properties and the kernel attributes they are
// equivalent to.
struct KhrKernelPropertyInfo {
StringRef IRName;
StringRef PropertyName;
attr::Kind AttrKind;
};
constexpr KhrKernelPropertyInfo KhrKernelProperties[] = {
{"sycl-work-group-size", "work_group_size",
attr::Kind::SYCLReqdWorkGroupSize},
{"sycl-work-group-size-hint", "work_group_size_hint",
attr::Kind::SYCLWorkGroupSizeHint},
{"sycl-sub-group-size", "sub_group_size",
attr::Kind::IntelReqdSubGroupSize},
};
} // namespace

// Renders the arguments of a kernel attribute the way the corresponding
// property value is rendered in the IR attribute ("X[,Y[,Z]]"). Returns
// std::nullopt if an argument is not a constant.
static std::optional<std::string> getKernelAttrArgsAsString(const Attr *A) {
SmallVector<std::optional<llvm::APSInt>, 3> Vals;
if (const auto *RWGS = dyn_cast<SYCLReqdWorkGroupSizeAttr>(A)) {
Vals.push_back(RWGS->getXDimVal());
if (RWGS->getYDim())
Vals.push_back(RWGS->getYDimVal());
if (RWGS->getZDim())
Vals.push_back(RWGS->getZDimVal());
} else if (const auto *WGSH = dyn_cast<SYCLWorkGroupSizeHintAttr>(A)) {
Vals.push_back(WGSH->getXDimVal());
if (WGSH->getYDim())
Vals.push_back(WGSH->getYDimVal());
if (WGSH->getZDim())
Vals.push_back(WGSH->getZDimVal());
} else if (const auto *RSGS = dyn_cast<IntelReqdSubGroupSizeAttr>(A)) {
const auto *CE = dyn_cast<ConstantExpr>(RSGS->getValue());
if (!CE)
return std::nullopt;
Vals.push_back(CE->getResultAsAPSInt());
}

std::string Str;
llvm::raw_string_ostream OS(Str);
for (const auto &[I, Val] : llvm::enumerate(Vals)) {
if (!Val)
return std::nullopt;
OS << (I ? "," : "") << *Val;
}
return Str;
}

void SemaSYCL::checkSYCLKhrKernelPropertiesAttrConflicts(Decl *D) {
const auto *AddIRFuncAttr = D->getAttr<SYCLAddIRAttributesFunctionAttr>();
if (!AddIRFuncAttr ||
hasDependentExpr(AddIRFuncAttr->args_begin(), AddIRFuncAttr->args_size()))
return;

// \p D is the OpenCL kernel; the properties are template arguments of the
// kernel caller function it was generated from.
const FunctionDecl *Caller = nullptr;
for (const auto &[SYCLKernel, OpenCLKernel] : getKernelFDPairs())
if (OpenCLKernel == D) {
Caller = SYCLKernel;
break;
}
if (!Caller || Caller->getNumParams() == 0)
return;
const TemplateArgumentList *TAL = Caller->getTemplateSpecializationArgs();
if (!TAL || !TAL->size() ||
TAL->asArray().back().getKind() != TemplateArgument::Pack)
return;
CXXRecordDecl *KernelObj = Caller->getParamDecl(0)
->getType()
.getNonReferenceType()
->getAsCXXRecordDecl();
const CXXMethodDecl *Getter =
KernelObj ? findKhrKernelPropertiesGetter(SemaRef, KernelObj) : nullptr;
if (!Getter)
return;

// The getter returns a property or a property list of properties.
llvm::SmallPtrSet<const Type *, 4> GetterTypes;
QualType RetTy = Getter->getReturnType().getCanonicalType();
GetterTypes.insert(RetTy.getTypePtr());
if (const auto *Spec = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
RetTy->getAsCXXRecordDecl()))
for (const TemplateArgument &Arg : Spec->getTemplateArgs().asArray())
for (const TemplateArgument &Elt : Arg.getKind() == TemplateArgument::Pack
? Arg.pack_elements()
: ArrayRef(Arg))
if (Elt.getKind() == TemplateArgument::Type)
GetterTypes.insert(Elt.getAsType().getCanonicalType().getTypePtr());

// The SYCL headers pass the properties embedded by
// 'get(sycl::khr::property::tag::kernel)' unchanged as elements of the
// trailing template parameter pack of the kernel caller, and each element of
// that pack contributes one trailing name-value pair to the attribute.
ArrayRef<TemplateArgument> Pack = TAL->asArray().back().pack_elements();
size_t NumPairs =
(AddIRFuncAttr->args_size() - AddIRFuncAttr->hasFilterList()) / 2;
if (Pack.size() > NumPairs)
return;
Expr **Names = AddIRFuncAttr->args_begin() + AddIRFuncAttr->hasFilterList();
Expr **Values = Names + NumPairs;
ASTContext &Context = getASTContext();
for (const auto &[I, Elt] : llvm::enumerate(Pack)) {
if (Elt.getKind() != TemplateArgument::Type ||
!GetterTypes.contains(Elt.getAsType().getCanonicalType().getTypePtr()))
continue;
size_t PairIdx = NumPairs - Pack.size() + I;
std::optional<std::string> Name =
SYCLAddIRAttributesFunctionAttr::getValidAttributeNameAsString(
Names[PairIdx], Context);
std::optional<std::string> Value =
SYCLAddIRAttributesFunctionAttr::getValidAttributeValueAsString(
Values[PairIdx], Context);
if (!Name || !Value)
continue;
const auto *Info = llvm::find_if(
KhrKernelProperties, [&](const auto &P) { return P.IRName == *Name; });
if (Info == std::end(KhrKernelProperties))
continue;

for (const Attr *A : D->attrs()) {
if (A->getKind() != Info->AttrKind)
continue;
// Not propagated to the kernel, so it has no effect on it.
if (const auto *RSGS = dyn_cast<IntelReqdSubGroupSizeAttr>(A);
RSGS && RSGS->isSYCL2020Spelling())
continue;
std::optional<std::string> AttrArgs = getKernelAttrArgsAsString(A);
if (AttrArgs && *AttrArgs != *Value) {
Diag(A->getLocation(), diag::err_sycl_khr_kernel_property_attr_mismatch)
<< A << *AttrArgs << *Value << Info->PropertyName;
Diag(Getter->getLocation(),
diag::note_sycl_khr_kernel_properties_getter);
}
}
}
}

void SemaSYCL::handleSYCLRegisteredKernels(Decl *D, const ParsedAttr &A) {
// Check for SYCL device compilation context.
if (!getLangOpts().SYCLIsDevice)
Expand Down
158 changes: 158 additions & 0 deletions clang/test/SemaSYCL/khr-kernel-properties-conflict.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
// RUN: %clang_cc1 -fsycl-is-device -internal-isystem %S/Inputs -fsyntax-only -verify %s

// Tests the diagnostics for kernel attributes on the call operator that do not
// match the kernel properties embedded by
// 'get(sycl::khr::property::tag::kernel)' (sycl_khr_kernel_properties). The
// SYCL headers pass the properties as elements of the template parameter pack
// of the kernel entry point.

#include "sycl.hpp"

namespace sycl {
inline namespace _V1 {
namespace khr {
template <typename... Ps> struct properties {};
namespace property {
namespace tag {
struct kernel {};
} // namespace tag
template <int... Dims> struct work_group_size {};
template <int... Dims> struct work_group_size_hint {};
template <int Size> struct sub_group_size {};
} // namespace property
} // namespace khr
} // namespace _V1
} // namespace sycl

namespace kp = sycl::khr::property;
// Mimics PropertyMetaInfo.
template <typename P> struct MetaInfo;
template <> struct MetaInfo<kp::work_group_size<8>> {
static constexpr const char *name = "sycl-work-group-size";
static constexpr const char *value = "8";
};
template <> struct MetaInfo<kp::work_group_size<8, 4>> {
static constexpr const char *name = "sycl-work-group-size";
static constexpr const char *value = "8,4";
};
template <> struct MetaInfo<kp::work_group_size_hint<2, 2, 2>> {
static constexpr const char *name = "sycl-work-group-size-hint";
static constexpr const char *value = "2,2,2";
};
template <> struct MetaInfo<kp::sub_group_size<16>> {
static constexpr const char *name = "sycl-sub-group-size";
static constexpr int value = 16;
};
template <typename KernelName, typename KernelType, typename... Props>
[[__sycl_detail__::add_ir_attributes_function(
"sycl-single-task", MetaInfo<Props>::name..., nullptr,
MetaInfo<Props>::value...)]] __attribute__((sycl_kernel)) void
kernel_single_task(const KernelType &KernelFunc) {
KernelFunc();
}

template <typename KernelName, typename KernelType, typename... Props>
[[__sycl_detail__::add_ir_attributes_function(
MetaInfo<Props>::name..., MetaInfo<Props>::value...)]]
__attribute__((sycl_kernel)) void
kernel_parallel_for(const KernelType &KernelFunc) {
KernelFunc();
}

// Matching attributes: no error. The existing warning about kernels with both
// attributes and properties is unaffected.
struct Matching {
// expected-warning@+3 {{kernel has both attribute 'sycl::reqd_work_group_size' and kernel properties}}
// expected-warning@+2 {{kernel has both attribute 'sycl::work_group_size_hint' and kernel properties}}
// expected-warning@+2 {{kernel has both attribute 'sycl::reqd_sub_group_size' and kernel properties}}
[[sycl::reqd_work_group_size(8, 4)]] [[sycl::work_group_size_hint(2, 2, 2)]]
[[sycl::reqd_sub_group_size(16)]] void operator()() const {}
auto get(kp::tag::kernel) const {
return sycl::khr::properties<kp::work_group_size<8, 4>,
kp::work_group_size_hint<2, 2, 2>,
kp::sub_group_size<16>>{};
}
};

// A single property instead of a list.
struct MatchingSingle {
// expected-warning@+1 {{kernel has both attribute 'sycl::reqd_work_group_size' and kernel properties}}
[[sycl::reqd_work_group_size(8)]] void operator()() const {}
auto get(kp::tag::kernel) const { return kp::work_group_size<8>{}; }
};

struct Mismatching {
// expected-error@+6 {{'sycl::reqd_work_group_size' attribute arguments '8' do not match the value '8,4' of kernel property 'sycl::khr::property::work_group_size' embedded by 'get(sycl::khr::property::tag::kernel)'}}
// expected-warning@+5 {{kernel has both attribute 'sycl::reqd_work_group_size' and kernel properties}}
// expected-error@+5 {{'sycl::work_group_size_hint' attribute arguments '2,2' do not match the value '2,2,2' of kernel property 'sycl::khr::property::work_group_size_hint' embedded by 'get(sycl::khr::property::tag::kernel)'}}
// expected-warning@+4 {{kernel has both attribute 'sycl::work_group_size_hint' and kernel properties}}
// expected-error@+4 {{'sycl::reqd_sub_group_size' attribute arguments '32' do not match the value '16' of kernel property 'sycl::khr::property::sub_group_size' embedded by 'get(sycl::khr::property::tag::kernel)'}}
// expected-warning@+3 {{kernel has both attribute 'sycl::reqd_sub_group_size' and kernel properties}}
[[sycl::reqd_work_group_size(8)]]
[[sycl::work_group_size_hint(2, 2)]]
[[sycl::reqd_sub_group_size(32)]] void operator()() const {}
// expected-note@+1 3 {{kernel properties are embedded by this member function}}
auto get(kp::tag::kernel) const {
return sycl::khr::properties<kp::work_group_size<8, 4>,
kp::work_group_size_hint<2, 2, 2>,
kp::sub_group_size<16>>{};
}
};

// A property in the pack that does not come from the khr getter is not
// checked against the attributes.
struct OtherProperty {};
template <> struct MetaInfo<OtherProperty> {
static constexpr const char *name = "sycl-work-group-size";
static constexpr const char *value = "16";
};
struct NotFromGetter {
// expected-warning@+1 {{kernel has both attribute 'sycl::reqd_work_group_size' and kernel properties}}
[[sycl::reqd_work_group_size(8)]] void operator()() const {}
auto get(kp::tag::kernel) const { return kp::work_group_size<8>{}; }
};

// The getter is inherited from a base class.
struct Base {
// expected-note@+1 {{kernel properties are embedded by this member function}}
auto get(kp::tag::kernel) const { return kp::sub_group_size<16>{}; }
};
struct Derived : Base {
// expected-error@+2 {{'sycl::reqd_sub_group_size' attribute arguments '8' do not match the value '16' of kernel property 'sycl::khr::property::sub_group_size' embedded by 'get(sycl::khr::property::tag::kernel)'}}
// expected-warning@+1 {{kernel has both attribute 'sycl::reqd_sub_group_size' and kernel properties}}
[[sycl::reqd_sub_group_size(8)]] void operator()() const {}
};

// Not the khr tag: the khr checks do not apply.
namespace other {
struct kernel {};
}
struct WrongTag {
// expected-warning@+1 {{kernel has both attribute 'sycl::reqd_work_group_size' and kernel properties}}
[[sycl::reqd_work_group_size(4)]] void operator()() const {}
auto get(other::kernel) const { return kp::work_group_size<8>{}; }
};

// A non-const getter is not used (the SYCL headers reject it).
struct NonConstGetter {
// expected-warning@+1 {{kernel has both attribute 'sycl::reqd_work_group_size' and kernel properties}}
[[sycl::reqd_work_group_size(4)]] void operator()() const {}
auto get(kp::tag::kernel) { return kp::work_group_size<8>{}; }
};

int main() {
kernel_single_task<class K1, Matching, kp::work_group_size<8, 4>,
kp::work_group_size_hint<2, 2, 2>, kp::sub_group_size<16>>(
Matching{});
kernel_parallel_for<class K2, MatchingSingle, kp::work_group_size<8>>(
MatchingSingle{});
kernel_single_task<class K3, Mismatching, kp::work_group_size<8, 4>,
kp::work_group_size_hint<2, 2, 2>, kp::sub_group_size<16>>(
Mismatching{});
kernel_parallel_for<class K4, NotFromGetter, OtherProperty,
kp::work_group_size<8>>(NotFromGetter{});
kernel_single_task<class K7, Derived, kp::sub_group_size<16>>(Derived{});
kernel_single_task<class K8, WrongTag, kp::work_group_size<8>>(WrongTag{});
kernel_single_task<class K9, NonConstGetter, kp::work_group_size<8>>(
NonConstGetter{});
}
Loading
Loading