Skip to content

Commit 1b201d8

Browse files
authored
[SYCL] Fix operator- for sycl::vec<bool, N> (#11816)
Since bool vectors have a backing storage of chars, the unary minus operator was in fact producing `(char)-1`, and thus not adhering to the ABI where bools should be either 0 or 1. This could manifest itself in bugs, for instance where the "bool" elements wouldn't compare equal to other bools, such as those in arrays. This only manifested itself in device code (possibly because the array of bools is also an array of bytes under the hood), hence the test case that differs in style somewhat from the rest.
1 parent 5cdc096 commit 1b201d8

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

sycl/include/sycl/types.hpp

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1060,7 +1060,11 @@ template <typename Type, int NumElements> class vec {
10601060

10611061
// operator -
10621062
template <typename T = vec> EnableIfNotUsingArray<T> operator-() const {
1063-
return vec{-m_Data};
1063+
vec Ret{-m_Data};
1064+
if constexpr (std::is_same_v<Type, bool>) {
1065+
Ret.ConvertToDataT();
1066+
}
1067+
return Ret;
10641068
}
10651069

10661070
template <typename T = vec> EnableIfUsingArray<T> operator-() const {

sycl/test-e2e/Basic/vec_bool.cpp

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,31 @@ int main() {
5757
}
5858
check_result(resVec, expected);
5959

60+
// Test negate (operator -)
61+
bool res = true;
62+
{
63+
sycl::buffer<bool, 1> bufResVec(&res, 1);
64+
65+
q.submit([&](sycl::handler &cgh) {
66+
sycl::accessor accRes(bufResVec, cgh, sycl::write_only);
67+
cgh.single_task([=]() {
68+
std::array<bool, size> arrTrue;
69+
for (int i = 0; i < size; ++i) {
70+
arrTrue[i] = -(static_cast<bool>(1));
71+
}
72+
auto vecTrue = sycl::vec<bool, size>(static_cast<bool>(1));
73+
sycl::vec<bool, size> resVec = -vecTrue;
74+
// Check that the vector matches the array.
75+
for (int i = 0; i < size; ++i) {
76+
if (resVec[i] != arrTrue[i]) {
77+
accRes[0] = false;
78+
}
79+
}
80+
});
81+
}).wait_and_throw();
82+
}
83+
assert(res && "Incorrect result");
84+
6085
// Test left shift (operator <<) 1
6186
{
6287
init_arr(expected, true);

0 commit comments

Comments
 (0)