From da3e9968c1e6fc2d5b72cc6f3dc2d89a8a89c584 Mon Sep 17 00:00:00 2001 From: a91249061 Date: Sun, 11 Oct 2026 23:22:27 +0800 Subject: [PATCH 01/23] Allow building for unavailable devices in offline compile mode compile_and_link_program rejected any program whose device reported available == CL_FALSE. With POCL_OFFLINE_COMPILE a device only builds programs and is deliberately unavailable (e.g. almaif sets Available to CL_FALSE in offline mode), so clBuildProgram failed with CL_DEVICE_NOT_AVAILABLE before the build started. Skip the check in offline mode, matching the existing handling in devices.c and clCreateContext.c. --- lib/CL/pocl_build.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/lib/CL/pocl_build.c b/lib/CL/pocl_build.c index e75ba3f926..e5ec3c1bac 100644 --- a/lib/CL/pocl_build.c +++ b/lib/CL/pocl_build.c @@ -50,6 +50,8 @@ #include "pocl_binary.h" #include "pocl_shared.h" +extern int pocl_offline_compile; + #define REQUIRES_CR_SQRT_DIV_ERR \ "-cl-fp32-correctly-rounded-divide-sqrt build option " \ "was specified, but CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT " \ @@ -845,8 +847,9 @@ compile_and_link_program(int compile_program, for (i = 0; i < program->num_devices; ++i) { cl_device_id dev = program->devices[i]; - POCL_GOTO_ERROR_COND ((*dev->available == CL_FALSE), - CL_DEVICE_NOT_AVAILABLE); + POCL_GOTO_ERROR_COND ( + (!pocl_offline_compile && (*dev->available == CL_FALSE)), + CL_DEVICE_NOT_AVAILABLE); for (cl_uint j = 0; j < program->associated_num_devices; ++j) if (program->associated_devices[j] == dev) ++num_found; From 19d97d27db44f9b35b8875eeaeab9e34f1b1ae62 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Mon, 19 Oct 2026 17:00:12 +0200 Subject: [PATCH 02/23] Fix program-scope variable initialization on queried and rebuilt programs pocl_driver_build_poclbinary compiles the hidden gvar initialization kernel through pocl_driver_build_gvar_init_kernel without a callback, which also allocated the storage. The first launch then found the storage allocated and never ran the initializer, so querying CL_PROGRAM_BINARIES before running a kernel left all program-scope variables uninitialized. Only allocate the storage when the initializer actually runs, and do so under the program lock, publishing the storage after initialization, so that launches racing on different threads or queues can't see a half-initialized (or doubly allocated) buffer either. The CPU drivers' free_program also freed the storage without clearing the pointer, so after clBuildProgram on an already built program the initializer was skipped and kernels used freed memory. --- lib/CL/devices/basic/basic.c | 1 + lib/CL/devices/common_driver.c | 144 +++++++++++-------- tests/regression/test_program_scope_vars.cpp | 76 ++++++++++ 3 files changed, 165 insertions(+), 56 deletions(-) diff --git a/lib/CL/devices/basic/basic.c b/lib/CL/devices/basic/basic.c index dcb75513e1..22aa5314b1 100644 --- a/lib/CL/devices/basic/basic.c +++ b/lib/CL/devices/basic/basic.c @@ -656,6 +656,7 @@ pocl_basic_free_program (cl_device_id device, cl_program program, pocl_driver_free_program (device, program, dev_i); program->global_var_total_size[dev_i] = 0; pocl_aligned_free (program->gvar_storage[dev_i]); + program->gvar_storage[dev_i] = NULL; return 0; } /*********************** IMAGES ********************************/ diff --git a/lib/CL/devices/common_driver.c b/lib/CL/devices/common_driver.c index b4fde8709a..314b005ff5 100644 --- a/lib/CL/devices/common_driver.c +++ b/lib/CL/devices/common_driver.c @@ -1204,6 +1204,65 @@ pocl_driver_build_opencl_builtins (cl_program program, cl_uint device_i) #endif } +#ifdef ENABLE_HOST_CPU_DEVICES +/* Compiles the hidden initialization kernel and, with a callback, runs it on + STORAGE. */ +static int +compile_gvar_init_kernel (cl_program program, + cl_uint dev_i, + cl_device_id device, + void *storage, + gvar_init_callback_t callback) +{ + pocl_kernel_metadata_t fake_meta; + memset (&fake_meta, 0, sizeof (fake_meta)); + pocl_kernel_hash_t fake_build_hash; + + SHA1_CTX hash_ctx; + pocl_SHA1_Init (&hash_ctx); + pocl_SHA1_Update (&hash_ctx, (uint8_t *)program->build_hash[dev_i], + sizeof (SHA1_digest_t)); + pocl_SHA1_Update (&hash_ctx, (uint8_t *)POCL_GVAR_INIT_KERNEL_NAME, + strlen (POCL_GVAR_INIT_KERNEL_NAME)); + pocl_SHA1_Final (&hash_ctx, fake_build_hash); + + fake_meta.build_hash = &fake_build_hash; + + struct _cl_kernel fake_kernel; + memset (&fake_kernel, 0, sizeof (fake_kernel)); + fake_kernel.meta = &fake_meta; + fake_kernel.name = POCL_GVAR_INIT_KERNEL_NAME; + fake_kernel.context = program->context; + fake_kernel.program = program; + + _cl_command_node fake_cmd; + memset (&fake_cmd, 0, sizeof (_cl_command_node)); + fake_cmd.program_device_i = dev_i; + fake_cmd.device = device; + fake_cmd.type = CL_COMMAND_NDRANGE_KERNEL; + fake_cmd.command.run.kernel = &fake_kernel; + fake_cmd.command.run.hash = fake_meta.build_hash; + fake_cmd.command.run.pc.local_size[0] = 1; + fake_cmd.command.run.pc.local_size[1] = 1; + fake_cmd.command.run.pc.local_size[2] = 1; + fake_cmd.command.run.pc.work_dim = 3; + fake_cmd.command.run.pc.num_groups[0] = 1; + fake_cmd.command.run.pc.num_groups[1] = 1; + fake_cmd.command.run.pc.num_groups[2] = 1; + fake_cmd.command.run.pc.global_offset[0] = 0; + fake_cmd.command.run.pc.global_offset[1] = 0; + fake_cmd.command.run.pc.global_offset[2] = 0; + fake_cmd.command.run.pc.global_var_buffer = storage; + + if (device->ops->compile_kernel (&fake_cmd, &fake_kernel, device, 0) != 0) + return CL_INVALID_OPERATION; + + if (callback) + callback (program, dev_i, &fake_cmd); + return CL_SUCCESS; +} +#endif + /** * \brief Since the ProgramScopeVariables pass creates a hidden kernel * for variable initialization, we need to compile (and run) that kernel @@ -1213,9 +1272,12 @@ pocl_driver_build_opencl_builtins (cl_program program, cl_uint device_i) * as arguments. * * Can be used either to compile the hidden initialization kernel for -* a poclbinary, or to compile & run program-scope initialization before -* kernel execution. Should work with all devices that use PoCL's LLVM -* compilation. +* a poclbinary (callback NULL; the storage is left alone), or to compile & run +* program-scope initialization before kernel execution. The latter allocates +* the storage and runs the initializer once per device under the program +* lock, and only publishes the storage once it is initialized, so that +* concurrent launches never see uninitialized variables. Should work with all +* devices that use PoCL's LLVM compilation. * * \param [in] program the cl_program used * \param [in] device the device used @@ -1229,64 +1291,34 @@ pocl_driver_build_gvar_init_kernel (cl_program program, gvar_init_callback_t callback) { #ifdef ENABLE_HOST_CPU_DEVICES - if (device->run_program_scope_variables_pass == CL_FALSE) + if (device->run_program_scope_variables_pass == CL_FALSE + || program->global_var_total_size[dev_i] == 0) return CL_SUCCESS; - if (program->global_var_total_size[dev_i] > 0 && program->gvar_storage[dev_i] == NULL) + if (callback == NULL) + return compile_gvar_init_kernel (program, dev_i, device, NULL, NULL); + + int err = CL_SUCCESS; + POCL_LOCK_OBJ (program); + if (program->gvar_storage[dev_i] == NULL) { - program->gvar_storage[dev_i] = pocl_aligned_malloc ( - MAX_EXTENDED_ALIGNMENT, program->global_var_total_size[dev_i]); - - pocl_kernel_metadata_t fake_meta; - memset (&fake_meta, 0, sizeof (fake_meta)); - pocl_kernel_hash_t fake_build_hash; - - SHA1_CTX hash_ctx; - pocl_SHA1_Init (&hash_ctx); - pocl_SHA1_Update (&hash_ctx, (uint8_t *)program->build_hash[dev_i], - sizeof (SHA1_digest_t)); - pocl_SHA1_Update (&hash_ctx, (uint8_t *)POCL_GVAR_INIT_KERNEL_NAME, - strlen (POCL_GVAR_INIT_KERNEL_NAME)); - pocl_SHA1_Final (&hash_ctx, fake_build_hash); - - fake_meta.build_hash = &fake_build_hash; - - struct _cl_kernel fake_kernel; - memset (&fake_kernel, 0, sizeof (fake_kernel)); - fake_kernel.meta = &fake_meta; - fake_kernel.name = POCL_GVAR_INIT_KERNEL_NAME; - fake_kernel.context = program->context; - fake_kernel.program = program; - - _cl_command_node fake_cmd; - memset (&fake_cmd, 0, sizeof (_cl_command_node)); - fake_cmd.program_device_i = dev_i; - fake_cmd.device = device; - fake_cmd.type = CL_COMMAND_NDRANGE_KERNEL; - fake_cmd.command.run.kernel = &fake_kernel; - fake_cmd.command.run.hash = fake_meta.build_hash; - fake_cmd.command.run.pc.local_size[0] = 1; - fake_cmd.command.run.pc.local_size[1] = 1; - fake_cmd.command.run.pc.local_size[2] = 1; - fake_cmd.command.run.pc.work_dim = 3; - fake_cmd.command.run.pc.num_groups[0] = 1; - fake_cmd.command.run.pc.num_groups[1] = 1; - fake_cmd.command.run.pc.num_groups[2] = 1; - fake_cmd.command.run.pc.global_offset[0] = 0; - fake_cmd.command.run.pc.global_offset[1] = 0; - fake_cmd.command.run.pc.global_offset[2] = 0; - fake_cmd.command.run.pc.global_var_buffer = program->gvar_storage[dev_i]; - - if (device->ops->compile_kernel (&fake_cmd, &fake_kernel, device, 0) - != 0) - return CL_INVALID_OPERATION; - - if (callback) { - callback (program, dev_i, &fake_cmd); - } + void *storage = pocl_aligned_malloc ( + MAX_EXTENDED_ALIGNMENT, program->global_var_total_size[dev_i]); + if (storage == NULL) + err = CL_OUT_OF_HOST_MEMORY; + else + err = compile_gvar_init_kernel (program, dev_i, device, storage, + callback); + if (err == CL_SUCCESS) + program->gvar_storage[dev_i] = storage; + else + pocl_aligned_free (storage); } -#endif + POCL_UNLOCK_OBJ (program); + return err; +#else return CL_SUCCESS; +#endif } diff --git a/tests/regression/test_program_scope_vars.cpp b/tests/regression/test_program_scope_vars.cpp index c596bb2917..83664fa53a 100644 --- a/tests/regression/test_program_scope_vars.cpp +++ b/tests/regression/test_program_scope_vars.cpp @@ -148,6 +148,28 @@ kernel void reader( global float2* dest, float2 ptr_write_val ) { )raw"; +/* Initializers must run even if the program binaries are queried (which + compiles the initializer kernel) before the first launch, and again after + the program is rebuilt. */ +static char programFiveSourceCode[] = R"raw( + +global int initVar = 42; +global int initArr[4] = { 1, 2, 3, 4 }; + +kernel void read_init (global int *out) { + out[0] = initVar; + for (int i = 0; i < 4; ++i) + out[1 + i] = initArr[i]; +} + +kernel void clobber_init () { + initVar = -1; + for (int i = 0; i < 4; ++i) + initArr[i] = -1; +} + +)raw"; + int main(void) { @@ -446,6 +468,60 @@ main(void) std::cout << "TEST_GVAR_PTR matching res: " << matching_res << "\n"; errors += (matching_res != 8 ? 1 : 0); + cl::Program::Sources sources5({programFiveSourceCode}); + cl::Program program5(context, sources5); + program5.build(devices, "-cl-std=CL3.0"); + program5.getInfo(); + + cl::Buffer outBuffer5 = cl::Buffer( + context, CL_MEM_READ_WRITE, 5 * sizeof(cl_int), nullptr); + const cl_int initExpected[5] = { 42, 1, 2, 3, 4 }; + + for (int build = 0; build < 2; ++build) { + if (build > 0) + program5.build(devices, "-cl-std=CL3.0"); + + cl::Kernel read_init(program5, "read_init"); + cl::Kernel clobber_init(program5, "clobber_init"); + read_init.setArg(0, outBuffer5); + queue.enqueueNDRangeKernel( + read_init, + cl::NullRange, + cl::NDRange(1), + cl::NullRange); + + cl_int initOut[5] = { 0 }; + queue.enqueueReadBuffer( + outBuffer5, + CL_TRUE, // block + 0, + sizeof(initOut), + (void*) &initOut[0]); + + matching_res = 0; + for (unsigned i = 0; i < 5; ++i) { + if (initOut[i] == initExpected[i]) { + ++matching_res; + } else { + std::cout << "FAIL at " << i << " build " << build + << " expected: " << initExpected[i] + << " got: " << initOut[i] << "\n"; + } + } + + std::cout << "TEST_GVAR_INIT build " << build + << " matching res: " << matching_res << "\n"; + errors += (matching_res != 5 ? 1 : 0); + + /* The rebuild must start from the initializers again. */ + queue.enqueueNDRangeKernel( + clobber_init, + cl::NullRange, + cl::NDRange(1), + cl::NullRange); + queue.finish(); + } + } catch (cl::Error &err) { std::cerr << "ERROR: " << err.what() << "(" << err.err() << ")" From 460bf3bc5bdf24cef25f7be784ee4ce2290ef226 Mon Sep 17 00:00:00 2001 From: anun333 Date: Sat, 26 Sep 2026 17:17:59 -0500 Subject: [PATCH 03/23] Test clCreateProgramWithBinary on sub-devices of one root and a second root With the device list [sub1, sub2, other], where sub1 and sub2 partition one root device, each device must run the binary given for it and every binary_status entry must be written. The same devices listed as [other, sub1, sub2] are the control. Runs with POCL_DEVICES="pthread basic" and skips where there is no partitionable device plus a second device. Co-Authored-By: Claude Opus 5.5 --- tests/runtime/CMakeLists.txt | 9 +- .../runtime/test_program_binary_subdevices.c | 198 ++++++++++++++++++ 2 files changed, 206 insertions(+), 1 deletion(-) create mode 100644 tests/runtime/test_program_binary_subdevices.c diff --git a/tests/runtime/CMakeLists.txt b/tests/runtime/CMakeLists.txt index cd67fdf2ca..367c51b7e1 100644 --- a/tests/runtime/CMakeLists.txt +++ b/tests/runtime/CMakeLists.txt @@ -37,7 +37,8 @@ set(C_PROGRAMS_TO_BUILD test_clFinish test_clGetDeviceInfo test_clGetEventInfo test_clSetEventCallback test_clEnqueueNativeKernel test_clBuildProgram test_clCreateKernelsInProgram test_clCreateKernel test_clGetKernelArgInfo test_version test_kernel_cache_includes test_event_cycle test_link_error - test_read-copy-write-buffer test_buffer-image-copy test_clCreateSubDevices test_event_free + test_read-copy-write-buffer test_buffer-image-copy test_clCreateSubDevices + test_program_binary_subdevices test_event_free test_event_double_wait test_event_failed_dependency test_buffer_migration test_buffer_ping_pong test_enqueue_kernel_from_binary test_user_event test_fill-buffer @@ -139,6 +140,12 @@ add_test_pocl(NAME "runtime/clCreateKernelsInProgram" COMMAND "test_clCreateKern add_test(NAME "runtime/clCreateSubDevices" COMMAND "test_clCreateSubDevices") +# two root devices, one of them partitionable; skips (77) where there aren't +add_test(NAME "runtime/test_program_binary_subdevices" COMMAND "test_program_binary_subdevices") +set_tests_properties("runtime/test_program_binary_subdevices" PROPERTIES + ENVIRONMENT "POCL_DEVICES=pthread basic" + SKIP_RETURN_CODE 77) + add_test_pocl(NAME "runtime/test_event_free" COMMAND "test_event_free" WORKITEM_HANDLER "loopvec") add_test_pocl(NAME "runtime/test_event_double_wait" COMMAND "test_event_double_wait" WORKITEM_HANDLER "loopvec") diff --git a/tests/runtime/test_program_binary_subdevices.c b/tests/runtime/test_program_binary_subdevices.c new file mode 100644 index 0000000000..7044235b0c --- /dev/null +++ b/tests/runtime/test_program_binary_subdevices.c @@ -0,0 +1,198 @@ +/* Tests that clCreateProgramWithBinary gives each device its own binary, and + writes every binary_status entry, when the device list mixes sub-devices of + one root device with a second root device. + + PoCL builds programs for root devices, so the device list is reduced to its + distinct roots. The per-device arrays (binaries, lengths, binary_status) + are the caller's, though, and must be read and written by the caller's + index. With the list [sub1, sub2, other] the distinct roots are + [other, root] (in that order), so reading the arrays by the reduced index + gives `other` the sub-devices' binary and never writes binary_status[2]. + The same devices listed as [other, sub1, sub2] are the control. + + Needs a partitionable device and a second root device; run with + POCL_DEVICES="pthread basic". Returns 77 (skip) when there aren't two. + + Copyright (c) 2026 PoCL developers + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include "poclu.h" + +#include +#include + +#define CHECK(x) \ + do \ + { \ + cl_int e_ = (x); \ + if (e_ != CL_SUCCESS) \ + { \ + printf ("FAIL %s: %d\n", #x, e_); \ + exit (1); \ + } \ + } \ + while (0) +#define UNWRITTEN 12345 + +static const char *SRC7 + = "kernel void k(global int *o) { o[get_global_id(0)] = 7; }"; +static const char *SRC9 + = "kernel void k(global int *o) { o[get_global_id(0)] = 9; }"; + +/* Build src on ctx's devices; return the binary reported for `want`, or for + `alt` (its root) where the program lists root devices. */ +static unsigned char * +binary_for (cl_context ctx, const char *src, cl_device_id want, + cl_device_id alt, size_t *len) +{ + cl_int e; + cl_program p = clCreateProgramWithSource (ctx, 1, &src, NULL, &e); + CHECK (e); + CHECK (clBuildProgram (p, 0, NULL, NULL, NULL, NULL)); + cl_uint n; + CHECK (clGetProgramInfo (p, CL_PROGRAM_NUM_DEVICES, sizeof n, &n, NULL)); + cl_device_id *d = malloc (n * sizeof *d); + size_t *sz = malloc (n * sizeof *sz); + unsigned char **b = malloc (n * sizeof *b); + CHECK (clGetProgramInfo (p, CL_PROGRAM_DEVICES, n * sizeof *d, d, NULL)); + CHECK (clGetProgramInfo (p, CL_PROGRAM_BINARY_SIZES, n * sizeof *sz, sz, + NULL)); + for (cl_uint i = 0; i < n; i++) + b[i] = malloc (sz[i] ? sz[i] : 1); + CHECK (clGetProgramInfo (p, CL_PROGRAM_BINARIES, n * sizeof *b, b, NULL)); + for (cl_uint i = 0; i < n; i++) + if (d[i] == want || d[i] == alt) + { + *len = sz[i]; + return b[i]; + } + printf ("FAIL: device not in CL_PROGRAM_DEVICES\n"); + exit (1); +} + +/* Create a program from bins for devs; every status must be written and + CL_SUCCESS, and every device must run its own binary (want[i]). */ +static int +trial (const char *name, cl_context ctx, cl_device_id *devs, + unsigned char **bins, size_t *lens, const int *want) +{ + cl_int e, st[3] = { UNWRITTEN, UNWRITTEN, UNWRITTEN }; + cl_program p = clCreateProgramWithBinary ( + ctx, 3, devs, lens, (const unsigned char **)bins, st, &e); + printf ("%s: error %d, binary_status {%d, %d, %d}", name, e, st[0], st[1], + st[2]); + int bad = (e != CL_SUCCESS); + for (int i = 0; i < 3; i++) + bad |= (st[i] != CL_SUCCESS); + if (e == CL_SUCCESS) + { + CHECK (clBuildProgram (p, 3, devs, NULL, NULL, NULL)); + cl_kernel k = clCreateKernel (p, "k", &e); + CHECK (e); + cl_mem m = clCreateBuffer (ctx, CL_MEM_READ_WRITE, sizeof (int), NULL, + &e); + CHECK (e); + CHECK (clSetKernelArg (k, 0, sizeof m, &m)); + printf (", outputs {"); + for (int i = 0; i < 3; i++) + { + cl_command_queue q + = clCreateCommandQueueWithProperties (ctx, devs[i], NULL, &e); + CHECK (e); + int z = 0, r = -1; + size_t g = 1; + CHECK (clEnqueueWriteBuffer (q, m, CL_TRUE, 0, sizeof z, &z, 0, NULL, + NULL)); + CHECK (clEnqueueNDRangeKernel (q, k, 1, NULL, &g, NULL, 0, NULL, + NULL)); + CHECK (clEnqueueReadBuffer (q, m, CL_TRUE, 0, sizeof r, &r, 0, NULL, + NULL)); + printf ("%s%d", i ? ", " : "", r); + bad |= (r != want[i]); + CHECK (clReleaseCommandQueue (q)); + } + printf ("}"); + CHECK (clReleaseMemObject (m)); + CHECK (clReleaseKernel (k)); + CHECK (clReleaseProgram (p)); + } + printf (" -> %s\n", bad ? "WRONG" : "ok"); + return bad; +} + +int +main (void) +{ + cl_platform_id pl; + CHECK (clGetPlatformIDs (1, &pl, NULL)); + cl_uint nd; + CHECK (clGetDeviceIDs (pl, CL_DEVICE_TYPE_ALL, 0, NULL, &nd)); + cl_device_id all[8]; + CHECK (clGetDeviceIDs (pl, CL_DEVICE_TYPE_ALL, nd > 8 ? 8 : nd, all, NULL)); + cl_device_id root = NULL, other = NULL; + for (cl_uint i = 0; i < nd && i < 8; i++) + { + cl_uint maxsub = 0; + clGetDeviceInfo (all[i], CL_DEVICE_PARTITION_MAX_SUB_DEVICES, + sizeof maxsub, &maxsub, NULL); + if (maxsub >= 2 && !root) + root = all[i]; + else if (!other) + other = all[i]; + } + if (!root || !other) + { + printf ("SKIP: needs a partitionable device and a second device\n"); + return 77; + } + + cl_device_partition_property pp[] + = { CL_DEVICE_PARTITION_BY_COUNTS, 1, 1, + CL_DEVICE_PARTITION_BY_COUNTS_LIST_END, 0 }; + cl_device_id sub[2]; + CHECK (clCreateSubDevices (root, pp, 2, sub, NULL)); + cl_int e; + cl_device_id cdevs[3] = { sub[0], sub[1], other }; + cl_context ctx = clCreateContext (NULL, 3, cdevs, NULL, NULL, &e); + CHECK (e); + + size_t lsub, lother; + unsigned char *bsub = binary_for (ctx, SRC7, sub[0], root, &lsub); + unsigned char *bother = binary_for (ctx, SRC9, other, other, &lother); + + cl_device_id ctl[3] = { other, sub[0], sub[1] }; + unsigned char *cbins[3] = { bother, bsub, bsub }; + size_t clens[3] = { lother, lsub, lsub }; + const int cwant[3] = { 9, 7, 7 }; + cl_device_id shift[3] = { sub[0], sub[1], other }; + unsigned char *sbins[3] = { bsub, bsub, bother }; + size_t slens[3] = { lsub, lsub, lother }; + const int swant[3] = { 7, 7, 9 }; + + int bad = trial ("[other, sub1, sub2]", ctx, ctl, cbins, clens, cwant); + bad |= trial ("[sub1, sub2, other]", ctx, shift, sbins, slens, swant); + + CHECK (clReleaseContext (ctx)); + CHECK (clReleaseDevice (sub[0])); + CHECK (clReleaseDevice (sub[1])); + printf (bad ? "FAIL\n" : "OK\n"); + return bad ? EXIT_FAILURE : EXIT_SUCCESS; +} From d9cd5e20d5349939b2e3f8ac0144dd0f8ea2babe Mon Sep 17 00:00:00 2001 From: anun333 Date: Sat, 26 Sep 2026 17:18:34 -0500 Subject: [PATCH 04/23] clCreateProgramWithBinary: read binaries and write binary_status by the caller's index The device list is reduced to distinct root devices before the binaries are read, and the loop then indexed the caller's binaries[], lengths[] and binary_status[] by the reduced position. When sub-devices of one root come before a second root device, [sub1, sub2, other] reduces to [other, root]: `other` was given the sub-devices' binary and ran it, and binary_status[2] was never written. Each root now reads the binary of the first caller entry that reduces to it, and its status is written to every caller entry that reduces to it. Co-Authored-By: Claude Opus 5.5 --- lib/CL/clCreateProgramWithBinary.c | 74 ++++++++++++++++++++++-------- 1 file changed, 56 insertions(+), 18 deletions(-) diff --git a/lib/CL/clCreateProgramWithBinary.c b/lib/CL/clCreateProgramWithBinary.c index 5c164d7775..092a7638af 100644 --- a/lib/CL/clCreateProgramWithBinary.c +++ b/lib/CL/clCreateProgramWithBinary.c @@ -30,6 +30,36 @@ #include "pocl_util.h" #include +/* The caller's binaries, lengths and binary_status are indexed by the + * caller's device list. The program has one slot per distinct root device, in + * the order pocl_unique_device_list leaves them, so a slot must find its + * entries by device, not by position: [sub1, sub2, other] reduces to + * [other, root]. */ +static unsigned +caller_index (const cl_device_id *caller_devs, cl_uint caller_num, + cl_device_id root) +{ + unsigned j; + for (j = 0; j < caller_num; ++j) + if (pocl_real_dev (caller_devs[j]) == root) + return j; + assert (0 && "every root comes from the caller's list"); + return 0; +} + +/* Every entry of the caller's list that reduces to root gets its status. */ +static void +set_binary_status (cl_int *binary_status, const cl_device_id *caller_devs, + cl_uint caller_num, cl_device_id root, cl_int status) +{ + unsigned j; + if (binary_status == NULL) + return; + for (j = 0; j < caller_num; ++j) + if (pocl_real_dev (caller_devs[j]) == root) + binary_status[j] = status; +} + /** Creates either a program with binaries, or an empty program. * * The latter is useful for clLinkProgram() which needs an empty program to put @@ -78,7 +108,10 @@ create_program_skeleton (cl_context context, cl_uint num_devices, "device %s specified multiple times\n", context->devices[i]->long_name); } - // convert subdevices to devices and remove duplicates + // convert subdevices to devices and remove duplicates; the caller's list + // still indexes binaries[], lengths[] and binary_status[] + const cl_device_id *caller_devs = device_list; + cl_uint caller_num = num_devices; cl_uint real_num_devices = 0; unique_devlist = pocl_unique_device_list(device_list, num_devices, &real_num_devices); num_devices = real_num_devices; @@ -157,14 +190,18 @@ create_program_skeleton (cl_context context, cl_uint num_devices, for (i = 0; i < num_devices; ++i) { + unsigned src = caller_index (caller_devs, caller_num, device_list[i]); + const unsigned char *binary = binaries[src]; + size_t length = lengths[src]; + /* Poclcc binary */ - if (pocl_binary_check_binary(device_list[i], binaries[i])) + if (pocl_binary_check_binary (device_list[i], binary)) { - program->pocl_binary_sizes[i] = lengths[i]; - program->pocl_binaries[i] = (unsigned char*) malloc (lengths[i]); - memcpy (program->pocl_binaries[i], binaries[i], lengths[i]); + program->pocl_binary_sizes[i] = length; + program->pocl_binaries[i] = (unsigned char *)malloc (length); + memcpy (program->pocl_binaries[i], binary, length); - pocl_binary_set_program_buildhash (program, i, binaries[i]); + pocl_binary_set_program_buildhash (program, i, binary); int error = pocl_cache_create_program_cachedir (program, i, NULL, 0, program_bc_path); POCL_GOTO_ERROR_ON((error != 0), CL_BUILD_PROGRAM_FAILURE, @@ -182,28 +219,29 @@ create_program_skeleton (cl_context context, cl_uint num_devices, program->binary_sizes[i] = (size_t)size; } - if (binary_status != NULL) - binary_status[i] = CL_SUCCESS; + set_binary_status (binary_status, caller_devs, caller_num, + device_list[i], CL_SUCCESS); } /* check if the driver supports that binary */ else { cl_device_id device = program->associated_devices[i]; if (device->ops->supports_binary - && device->ops->supports_binary (device, lengths[i], - (const char *)binaries[i])) + && device->ops->supports_binary (device, length, + (const char *)binary)) { - program->binary_sizes[i] = lengths[i]; - program->binaries[i] = (unsigned char *)malloc (lengths[i]); - memcpy (program->binaries[i], binaries[i], lengths[i]); - if (binary_status != NULL) - binary_status[i] = CL_SUCCESS; + program->binary_sizes[i] = length; + program->binaries[i] = (unsigned char *)malloc (length); + memcpy (program->binaries[i], binary, length); + set_binary_status (binary_status, caller_devs, caller_num, + device_list[i], CL_SUCCESS); } else { - POCL_MSG_WARN ("Could not recognize binary for device %i\n", i); - if (binary_status != NULL) - binary_status[i] = CL_INVALID_BINARY; + POCL_MSG_WARN ("Could not recognize binary for device %u\n", + src); + set_binary_status (binary_status, caller_devs, caller_num, + device_list[i], CL_INVALID_BINARY); errcode = CL_INVALID_BINARY; goto ERROR; } From c2c1033e77292c80897e05a6465d48c45d985fe9 Mon Sep 17 00:00:00 2001 From: anun333 Date: Mon, 19 Oct 2026 19:55:54 -0500 Subject: [PATCH 05/23] test_program_binary_subdevices: release the program and free the binaries The test leaked every program it built for its binaries, and the binaries themselves, which the asan CI job reports as leaks. --- .../runtime/test_program_binary_subdevices.c | 21 +++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/tests/runtime/test_program_binary_subdevices.c b/tests/runtime/test_program_binary_subdevices.c index 7044235b0c..b4cc264f11 100644 --- a/tests/runtime/test_program_binary_subdevices.c +++ b/tests/runtime/test_program_binary_subdevices.c @@ -78,14 +78,25 @@ binary_for (cl_context ctx, const char *src, cl_device_id want, for (cl_uint i = 0; i < n; i++) b[i] = malloc (sz[i] ? sz[i] : 1); CHECK (clGetProgramInfo (p, CL_PROGRAM_BINARIES, n * sizeof *b, b, NULL)); + unsigned char *r = NULL; for (cl_uint i = 0; i < n; i++) - if (d[i] == want || d[i] == alt) + if (!r && (d[i] == want || d[i] == alt)) { *len = sz[i]; - return b[i]; + r = b[i]; } - printf ("FAIL: device not in CL_PROGRAM_DEVICES\n"); - exit (1); + else + free (b[i]); + free (b); + free (sz); + free (d); + CHECK (clReleaseProgram (p)); + if (!r) + { + printf ("FAIL: device not in CL_PROGRAM_DEVICES\n"); + exit (1); + } + return r; } /* Create a program from bins for devs; every status must be written and @@ -190,6 +201,8 @@ main (void) int bad = trial ("[other, sub1, sub2]", ctx, ctl, cbins, clens, cwant); bad |= trial ("[sub1, sub2, other]", ctx, shift, sbins, slens, swant); + free (bsub); + free (bother); CHECK (clReleaseContext (ctx)); CHECK (clReleaseDevice (sub[0])); CHECK (clReleaseDevice (sub[1])); From e0a724e3b186724fd0d243a1f4a07b699e98b459 Mon Sep 17 00:00:00 2001 From: anun333 Date: Thu, 15 Oct 2026 17:16:53 -0500 Subject: [PATCH 06/23] tests: regression test for -cl-fp32-correctly-rounded-divide-sqrt For each device with a compiler, builds and compiles a kernel with -cl-fp32-correctly-rounded-divide-sqrt. A device whose CL_DEVICE_SINGLE_FP_CONFIG has CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT must return CL_SUCCESS; one without it must return CL_BUILD_PROGRAM_FAILURE from clBuildProgram and CL_COMPILE_PROGRAM_FAILURE from clCompileProgram, with the reason in the build log, so a driver that cannot compile the kernel does not pass by accident. Labelled for CUDA, Vulkan and Level Zero. The CUDA and Vulkan devices never set the bit and take the failure path; the x86-64 CPU devices set it and take the success path. Co-Authored-By: Claude Opus 5.5 --- tests/regression/CMakeLists.txt | 5 + tests/regression/test_cr_divide_sqrt_option.c | 134 ++++++++++++++++++ 2 files changed, 139 insertions(+) create mode 100644 tests/regression/test_cr_divide_sqrt_option.c diff --git a/tests/regression/CMakeLists.txt b/tests/regression/CMakeLists.txt index 6cfd1628c8..52d147ab5f 100644 --- a/tests/regression/CMakeLists.txt +++ b/tests/regression/CMakeLists.txt @@ -42,6 +42,7 @@ set(C_PROGRAMS_TO_BUILD test_assign_loop_variable_to_privvar_makes_it_local test_usm_indirect_ptrs test_usm_free_realloc test_sanitize_divrem + test_cr_divide_sqrt_option ) if(UNIX) list(APPEND C_PROGRAMS_TO_BUILD test_signal_handlers) @@ -213,6 +214,10 @@ add_test_pocl(NAME "regression/test_usm_free_realloc" COMMAND "test_usm_free_rea add_test_pocl(NAME "regression/test_sanitize_divrem" COMMAND "test_sanitize_divrem" LABELS ${SPIRV_LABELS}) +# Builds only; the CUDA and Vulkan devices lack CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT. +add_test_pocl(NAME "regression/test_cr_divide_sqrt_option" COMMAND "test_cr_divide_sqrt_option" + WORKITEM_HANDLER "loopvec" LABELS "cuda;vulkan;level0") + add_test_pocl(NAME "regression/test_issue_893" COMMAND "test_issue_893") add_test_pocl(NAME "regression/test_flatten_barrier_subs" COMMAND "test_flatten_barrier_subs" EXPECTED_OUTPUT "test_flatten_barrier_subs.output") diff --git a/tests/regression/test_cr_divide_sqrt_option.c b/tests/regression/test_cr_divide_sqrt_option.c new file mode 100644 index 0000000000..4de01cfe61 --- /dev/null +++ b/tests/regression/test_cr_divide_sqrt_option.c @@ -0,0 +1,134 @@ +/* Regression test for issue #2404: clBuildProgram and clCompileProgram must + fail with -cl-fp32-correctly-rounded-divide-sqrt for a device whose + CL_DEVICE_SINGLE_FP_CONFIG lacks CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT, and + succeed for a device that has it. + + Copyright (c) 2026 pocl developers + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to + deal in the Software without restriction, including without limitation the + rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + sell copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + IN THE SOFTWARE. +*/ + +#include "pocl_opencl.h" + +#include +#include +#include + +#define OPTION "-cl-fp32-correctly-rounded-divide-sqrt" + +static const char *source + = "kernel void k (global float *a) { a[0] = a[1] / a[2] + sqrt (a[3]); }"; + +/* Builds, or only compiles, the kernel for the device with OPTION and + returns 1 if the result does not match the device's + CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT bit. */ +static int +check_option (cl_device_id device, int has_cr, int compile_only) +{ + cl_int err; + cl_context context = clCreateContext (NULL, 1, &device, NULL, NULL, &err); + CHECK_CL_ERROR (err); + cl_program program + = clCreateProgramWithSource (context, 1, &source, NULL, &err); + CHECK_CL_ERROR (err); + + cl_int expected = CL_SUCCESS; + if (compile_only) + { + err = clCompileProgram (program, 1, &device, OPTION, 0, NULL, NULL, NULL, + NULL); + if (!has_cr) + expected = CL_COMPILE_PROGRAM_FAILURE; + } + else + { + err = clBuildProgram (program, 1, &device, OPTION, NULL, NULL); + if (!has_cr) + expected = CL_BUILD_PROGRAM_FAILURE; + } + + size_t log_size = 0; + CHECK_CL_ERROR (clGetProgramBuildInfo (program, device, CL_PROGRAM_BUILD_LOG, + 0, NULL, &log_size)); + char *log = (char *)calloc (log_size + 1, 1); + TEST_ASSERT (log != NULL); + CHECK_CL_ERROR (clGetProgramBuildInfo (program, device, CL_PROGRAM_BUILD_LOG, + log_size, log, NULL)); + + /* Without the bit, the build must fail because of the option, not + because the driver cannot compile the kernel. */ + int mismatch + = err != expected + || (!has_cr + && strstr (log, "CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT") == NULL); + if (mismatch) + { + char name[256] = ""; + clGetDeviceInfo (device, CL_DEVICE_NAME, sizeof (name) - 1, name, NULL); + printf ("FAIL: %s with " OPTION " on %s, which %s the bit, returned " + "%d, expected %d; build log: \"%s\"\n", + compile_only ? "clCompileProgram" : "clBuildProgram", name, + has_cr ? "has" : "lacks", err, expected, log); + } + + free (log); + CHECK_CL_ERROR (clReleaseProgram (program)); + CHECK_CL_ERROR (clReleaseContext (context)); + return mismatch; +} + +int +main (void) +{ + cl_platform_id platform; + cl_uint num_devices = 0; + int failures = 0; + + CHECK_CL_ERROR (clGetPlatformIDs (1, &platform, NULL)); + CHECK_CL_ERROR ( + clGetDeviceIDs (platform, CL_DEVICE_TYPE_ALL, 0, NULL, &num_devices)); + cl_device_id *devices + = (cl_device_id *)malloc (num_devices * sizeof (cl_device_id)); + TEST_ASSERT (devices != NULL); + CHECK_CL_ERROR ( + clGetDeviceIDs (platform, CL_DEVICE_TYPE_ALL, num_devices, devices, NULL)); + + for (cl_uint i = 0; i < num_devices; ++i) + { + cl_bool compiler = CL_FALSE; + cl_device_fp_config fp_config = 0; + CHECK_CL_ERROR (clGetDeviceInfo (devices[i], + CL_DEVICE_COMPILER_AVAILABLE, + sizeof (compiler), &compiler, NULL)); + if (!compiler) + continue; + CHECK_CL_ERROR (clGetDeviceInfo (devices[i], CL_DEVICE_SINGLE_FP_CONFIG, + sizeof (fp_config), &fp_config, NULL)); + int has_cr = (fp_config & CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT) != 0; + + failures += check_option (devices[i], has_cr, 0); + failures += check_option (devices[i], has_cr, 1); + } + + free (devices); + if (failures) + return EXIT_FAILURE; + printf ("OK\n"); + return EXIT_SUCCESS; +} From b254aec68672acfe622c06a3cf501834ccf1b17a Mon Sep 17 00:00:00 2001 From: anun333 Date: Mon, 19 Oct 2026 19:57:41 -0500 Subject: [PATCH 07/23] Check -cl-fp32-correctly-rounded-divide-sqrt against each device The API spec says clBuildProgram and clCompileProgram fail for a device whose CL_DEVICE_SINGLE_FP_CONFIG lacks CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT when -cl-fp32-correctly-rounded-divide-sqrt is given. compile_and_link_program has had that check since f39115835, but process_options set the flag it reads only inside the branch for cl_program_link_options, which does not contain this option. So the check never ran, and the option was accepted on every device, including CUDA, Vulkan and RISC-V CPUs without F, none of which set the bit. Set the flag where the option is accepted as a compile option, by exact token match, and only when compiling, so clLinkProgram accepts it as before. A build for several devices still fails as a whole when one of them lacks the bit. Level Zero devices do not set the bit, so the option is now refused there, as the spec requires: PoCL does not pass it to the device compiler, and their sqrt is not correctly rounded under it (the CTS sqrt_cr test fails by 0.66 ulp on an Intel UHD when the bit is mapped from ZE_DEVICE_FP_FLAG_ROUNDED_DIVIDE_SQRT). Mapping it waits until the build requests correct rounding. Fixes #2404 Co-Authored-By: Claude Opus 5.5 --- lib/CL/pocl_build.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/lib/CL/pocl_build.c b/lib/CL/pocl_build.c index e75ba3f926..21585780d0 100644 --- a/lib/CL/pocl_build.c +++ b/lib/CL/pocl_build.c @@ -264,10 +264,6 @@ process_options (const char *options, char *modded_options, char *link_options, { *flush_denorms = 1; } - if (strstr (token, "-cl-fp32-correctly-rounded-divide-sqrt")) - { - *requires_correctly_rounded_sqrt_div = 1; - } } if (pocl_option_listed (cl_parameters, token)) @@ -275,6 +271,14 @@ process_options (const char *options, char *modded_options, char *link_options, /* the LLVM API call pushes the parameters directly to the frontend without using -Xclang */ + /* clBuildProgram and clCompileProgram must fail for a device + without CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT; the devices are + checked in compile_and_link_program () */ + if (compiling + && strcmp (token, "-cl-fp32-correctly-rounded-divide-sqrt") + == 0) + *requires_correctly_rounded_sqrt_div = 1; + // LLVM 11 has removed "-cl-denorms-are-zero" option // https://reviews.llvm.org/D69878 if (strncmp(token, "-cl-denorms-are-zero", 20) == 0) { From 4527e33fc59efeba46c5862fa5c37e110c3e5f88 Mon Sep 17 00:00:00 2001 From: anun333 Date: Fri, 16 Oct 2026 07:44:28 -0500 Subject: [PATCH 08/23] CPU: report correctly rounded divide and sqrt on AArch64 The AArch64 CPU device reported the minimum single_fp_config, without CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT, which x86-64 and RISC-V with F set. Now that -cl-fp32-correctly-rounded-divide-sqrt is checked against the bit (#2404), builds with the option would start failing on ARM64. The device is correctly rounded: float division compiles to FDIV and the kernel library's sqrt (Sleef_sqrtf_u05, which is __builtin_sqrtf) to FSQRT, in scalar and vector code, and both instructions are correctly rounded. Measured through PoCL on a Neoverse N1 with LLVM 19, in a conformance and a default build: fp32 x/y on 16.8M pairs (random, subnormal and edge cases), and 1/x and sqrt on all 2^32 inputs, in scalar and float4 kernels, gave no result that was not correctly rounded. With the bit set, the CTS divide_cr and sqrt_cr tests, which are skipped without it, pass at 0 ulp for every vector size. Co-Authored-By: Claude Opus 5.5 --- lib/CL/devices/common_utils.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/lib/CL/devices/common_utils.c b/lib/CL/devices/common_utils.c index 5d1ba51dd3..7ddf393bb7 100644 --- a/lib/CL/devices/common_utils.c +++ b/lib/CL/devices/common_utils.c @@ -449,6 +449,15 @@ pocl_cpu_init_common (cl_device_id device, unsigned dev_i) device->double_fp_config |= CL_FP_DENORM; #endif +#endif + +#if defined(__aarch64__) || defined(_M_ARM64) + /* FDIV and FSQRT are correctly rounded, scalar and Advanced SIMD alike, and + * float division and the kernel library's sqrt compile to them. Measured on + * a Neoverse N1 with LLVM 19, conformance and default builds: fp32 x/y on + * 16.8M pairs and 1/x and sqrt on all 2^32 inputs, all correctly rounded, + * subnormals included. */ + device->single_fp_config |= CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT; #endif if (strstr (HOST_DEVICE_EXTENSIONS, "cl_khr_fp64") == NULL) From 4880e7153b7b946c652e9aadccd6893be850542d Mon Sep 17 00:00:00 2001 From: anun333 Date: Wed, 21 Oct 2026 14:04:23 -0500 Subject: [PATCH 09/23] test_subgroup_queries: look up clGetKernelSubGroupInfoKHR by name A device that offers cl_khr_subgroups must let an application reach the extension's entry point through clGetExtensionFunctionAddressForPlatform. Check that it does, and that it answers as the core function does. Co-Authored-By: Claude Opus 5.5 --- tests/runtime/test_subgroup_queries.c | 30 ++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/tests/runtime/test_subgroup_queries.c b/tests/runtime/test_subgroup_queries.c index 6c51e01968..e64c7e0f4a 100644 --- a/tests/runtime/test_subgroup_queries.c +++ b/tests/runtime/test_subgroup_queries.c @@ -52,6 +52,10 @@ static const size_t LOCAL_SIZES[][3] = { #define NUM_LOCAL_SIZES (sizeof (LOCAL_SIZES) / sizeof (LOCAL_SIZES[0])) #define MAX_LOCAL_SIZE 64 +/* cl_khr_subgroups' entry point, looked up by name when the device offers + the extension */ +static clGetKernelSubGroupInfoKHR_t *get_info_khr = NULL; + static int check_variant (cl_context ctx, cl_device_id dev, cl_command_queue queue, int with_attr) @@ -116,6 +120,14 @@ check_variant (cl_context ctx, cl_device_id dev, cl_command_queue queue, sizeof (size_t) * 3, ls, sizeof (host_count), &host_count, NULL)); TEST_ASSERT (host_max > 0); + if (get_info_khr != NULL) + { + size_t khr_max = 0; + CHECK_CL_ERROR (get_info_khr ( + kernel, dev, CL_KERNEL_MAX_SUB_GROUP_SIZE_FOR_NDRANGE, + sizeof (size_t) * 3, ls, sizeof (khr_max), &khr_max, NULL)); + TEST_ASSERT (khr_max == host_max); + } if (with_attr) TEST_ASSERT (host_max == REQD_SG_SIZE); /* the count must include a possibly smaller trailing sub-group */ @@ -175,12 +187,24 @@ main (int argc, char **argv) return 77; } - CHECK_CL_ERROR (check_variant (ctx, dev, queue, 0)); - - /* only test intel_reqd_sub_group_size where supported */ char extensions[4096]; CHECK_CL_ERROR (clGetDeviceInfo (dev, CL_DEVICE_EXTENSIONS, sizeof (extensions), extensions, NULL)); + + /* An application reaches clGetKernelSubGroupInfoKHR by name; without an + ICD loader, clGetExtensionFunctionAddressForPlatform must return it. */ + if (strstr (extensions, "cl_khr_subgroups") != NULL) + { + get_info_khr + = (clGetKernelSubGroupInfoKHR_t *) + clGetExtensionFunctionAddressForPlatform ( + platform, "clGetKernelSubGroupInfoKHR"); + TEST_ASSERT (get_info_khr != NULL); + } + + CHECK_CL_ERROR (check_variant (ctx, dev, queue, 0)); + + /* only test intel_reqd_sub_group_size where supported */ if (strstr (extensions, "cl_intel_required_subgroup_size") != NULL) CHECK_CL_ERROR (check_variant (ctx, dev, queue, 1)); From 3a6a2b83bd9d725aabbaf58129f95981bbc92f83 Mon Sep 17 00:00:00 2001 From: anun333 Date: Wed, 21 Oct 2026 14:04:23 -0500 Subject: [PATCH 10/23] Return clGetKernelSubGroupInfoKHR from clGetExtensionFunctionAddressForPlatform cl_khr_subgroups has one entry point, clGetKernelSubGroupInfoKHR, which an application gets by name from clGetExtensionFunctionAddressForPlatform. PoCL's list there had no entry for it, and PoCL exports no symbol of that name, so without an ICD loader (ENABLE_ICD=OFF) a device that advertises cl_khr_subgroups gave no way to reach it: OpenCL-CTS test_subgroups fails its *_ext sub-tests with "clGetKernelSubGroupInfoKHR function not available". Through a loader the name resolves (ocl-icd answers it from its own table; the Khronos loader's cl_khr_icd2 path asks clIcdGetFunctionAddressForPlatformKHR, which has had it since #2337), which hid the gap. Co-Authored-By: Claude Opus 5.5 --- lib/CL/clGetExtensionFunctionAddressForPlatform.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/lib/CL/clGetExtensionFunctionAddressForPlatform.c b/lib/CL/clGetExtensionFunctionAddressForPlatform.c index 7b9d934ba4..f0c6a529d0 100644 --- a/lib/CL/clGetExtensionFunctionAddressForPlatform.c +++ b/lib/CL/clGetExtensionFunctionAddressForPlatform.c @@ -73,6 +73,12 @@ CL_API_SUFFIX__VERSION_1_2 if (strcmp (func_name, "clCreateProgramWithILKHR") == 0) return (void *)&POname(clCreateProgramWithIL); + /* cl_khr_subgroups. Without an ICD loader this is the only way to reach + it; loaders answer the name themselves or through + clIcdGetFunctionAddressForPlatformKHR. */ + if (strcmp (func_name, "clGetKernelSubGroupInfoKHR") == 0) + return (void *)&POname (clGetKernelSubGroupInfo); + /* cl_khr_command_buffer */ if (strcmp (func_name, "clCreateCommandBufferKHR") == 0) return (void *)&POname (clCreateCommandBufferKHR); From a3f44c6b349602c5d478103628514203eba155f3 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Sat, 24 Oct 2026 14:45:00 +0200 Subject: [PATCH 11/23] VariableUniformityAnalysis: don't reuse the uniformity of deleted values The analysis caches uniformity by Value pointer and opts out of invalidation. Later transformations can delete a value and allocate another at the same address, which then inherits the cached uniformity. An incorrect "uniform" result makes WorkitemLoops skip saving the value separately for each work-item, so later uses can read the last work-item's value. Whether this happens depends on the allocator, so a kernel can compile correctly or not depending on the process's history. Store a WeakVH in each cache entry, and reject entries whose handle no longer matches the queried value. --- lib/llvmopencl/VariableUniformityAnalysis.cc | 31 ++++++++++++------- .../VariableUniformityAnalysisResult.hh | 13 +++++++- 2 files changed, 31 insertions(+), 13 deletions(-) diff --git a/lib/llvmopencl/VariableUniformityAnalysis.cc b/lib/llvmopencl/VariableUniformityAnalysis.cc index fdda2f4f6a..36c5c121d3 100644 --- a/lib/llvmopencl/VariableUniformityAnalysis.cc +++ b/lib/llvmopencl/VariableUniformityAnalysis.cc @@ -251,14 +251,24 @@ void VariableUniformityAnalysisResult::analyzeBBDivergence( } } -bool VariableUniformityAnalysisResult::isUniformityAnalyzed( - llvm::Function *F, llvm::Value *V) const { +const bool * +VariableUniformityAnalysisResult::lookupUniformity(llvm::Function *F, + llvm::Value *V) const { UniformityIndex &Cache = uniformityCache_[F]; - UniformityIndex::const_iterator I = Cache.find(V); - if (I != Cache.end()) { - return true; + UniformityIndex::iterator I = Cache.find(V); + if (I == Cache.end()) + return nullptr; + if (I->second.Handle != V) { + // the cached value was deleted, and V reuses its address + Cache.erase(I); + return nullptr; } - return false; + return &I->second.IsUniform; +} + +bool VariableUniformityAnalysisResult::isUniformityAnalyzed( + llvm::Function *F, llvm::Value *V) const { + return lookupUniformity(F, V) != nullptr; } /** @@ -275,11 +285,8 @@ bool VariableUniformityAnalysisResult::isUniformityAnalyzed( bool VariableUniformityAnalysisResult::isUniform(llvm::Function *F, llvm::Value *V) { - UniformityIndex &Cache = uniformityCache_[F]; - UniformityIndex::const_iterator I = Cache.find(V); - if (I != Cache.end()) { - return (*I).second; - } + if (const bool *Cached = lookupUniformity(F, V)) + return *Cached; if (llvm::BasicBlock *BB = dyn_cast(V)) { if (BB == &F->getEntryBlock()) { @@ -483,7 +490,7 @@ void VariableUniformityAnalysisResult::setUniform(llvm::Function *F, bool isUniform) { UniformityIndex &Cache = uniformityCache_[F]; - Cache[V] = isUniform; + Cache[V] = UniformityEntry{llvm::WeakVH(V), isUniform}; #ifdef DEBUG_UNIFORMITY_ANALYSIS std::cerr << "### "; diff --git a/lib/llvmopencl/VariableUniformityAnalysisResult.hh b/lib/llvmopencl/VariableUniformityAnalysisResult.hh index 5e1a5a4a84..c946b556fe 100644 --- a/lib/llvmopencl/VariableUniformityAnalysisResult.hh +++ b/lib/llvmopencl/VariableUniformityAnalysisResult.hh @@ -35,6 +35,8 @@ template class AnalysisManager; #include +#include + namespace pocl { class VariableUniformityAnalysisResult { @@ -58,8 +60,17 @@ public: private: bool isUniformityAnalyzed(llvm::Function *F, llvm::Value *V) const; + const bool *lookupUniformity(llvm::Function *F, llvm::Value *V) const; - using UniformityIndex = std::map; + // The result is not invalidated when later passes transform the function, + // so the cache outlives values those passes delete. Each entry keeps a + // handle to its value, so that a new value allocated at the address of a + // deleted one doesn't inherit its uniformity. + struct UniformityEntry { + llvm::WeakVH Handle; + bool IsUniform; + }; + using UniformityIndex = std::map; using UniformityCache = std::map; mutable UniformityCache uniformityCache_; }; From 6907c6aab90b50c559d5b1ae80aa67be150d0996 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Wed, 21 Oct 2026 14:44:31 +0200 Subject: [PATCH 12/23] cl_half.h: don't shift into the sign bit of int cl_half_to_float shifted the uint16_t sign, promoted to int, left by 31, which is undefined for a negative half and flagged by UBSan. Widen it to uint32_t first. KhronosGroup/OpenCL-Headers has the same shift, so note the local change for whoever syncs the header next. --- include/CL/cl_half.h | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/include/CL/cl_half.h b/include/CL/cl_half.h index 538300b845..3a4dab8d0d 100644 --- a/include/CL/cl_half.h +++ b/include/CL/cl_half.h @@ -368,6 +368,9 @@ static inline cl_float cl_half_to_float(cl_half h) } f32; // Extract sign bit + // pocl: the `sign << 31` below is cast to uint32_t, since shifting the + // promoted int into its sign bit is undefined. KhronosGroup/OpenCL-Headers + // still has the uncast shift; keep the casts when syncing this header. uint16_t sign = h >> 15; // Extract FP16 exponent and mantissa @@ -388,13 +391,13 @@ static inline cl_float cl_half_to_float(cl_half h) // NaN -> propagate mantissa and silence it uint32_t f_mant = h_mant << (CL_FLT_MANT_DIG - CL_HALF_MANT_DIG); f_mant |= 0x400000; - f32.i = (sign << 31) | 0x7F800000 | f_mant; + f32.i = ((uint32_t)sign << 31) | 0x7F800000 | f_mant; return f32.f; } else { // Infinity -> zero mantissa - f32.i = (sign << 31) | 0x7F800000; + f32.i = ((uint32_t)sign << 31) | 0x7F800000; return f32.f; } } @@ -423,7 +426,7 @@ static inline cl_float cl_half_to_float(cl_half h) } } - f32.i = (sign << 31) | (f_exp << 23) | (h_mant << 13); + f32.i = ((uint32_t)sign << 31) | (f_exp << 23) | (h_mant << 13); return f32.f; } From fd77eb37af238465614a0f47e686fc4d97c464c3 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Thu, 15 Oct 2026 18:35:03 +0200 Subject: [PATCH 13/23] printf: decode half arguments without _Float16 The _Float16 half printf formatter makes GCC emit calls to __extendhfdf2 and __extendhfxf2, which x86 libgcc_s only exports from GCC 12 on. A libpocl built with GCC 12 then fails to load in a process that already loaded an older libgcc_s, e.g. under `nsys profile`. Decode the half bits with pocl_half_to_float instead. The conversion is exact, so the output is unchanged, and half printf now also works without host _Float16 support, where it printed an error and the raw bits. Extend the halfn printf test with subnormals, the largest finite half, -0, -inf and a negative NaN. --- lib/CL/devices/printf_buffer.c | 47 ++++++++----------- tests/kernel/test_printf_vectors_halfn.cl | 6 +++ .../test_printf_vectors_halfn_expout.txt | 2 + 3 files changed, 28 insertions(+), 27 deletions(-) diff --git a/lib/CL/devices/printf_buffer.c b/lib/CL/devices/printf_buffer.c index 6dafbba760..f4e0c749f6 100644 --- a/lib/CL/devices/printf_buffer.c +++ b/lib/CL/devices/printf_buffer.c @@ -27,6 +27,7 @@ #include "printf_buffer.h" #include "common.h" #include "pocl_compiler_macros.h" +#include "pocl_cl_half_util.h" #include "pocl_debug.h" #include "printf_base.h" @@ -101,12 +102,13 @@ DEFINE_PRINT_INTS (ulong, int64_t, uint64_t) /* Note: NANs are printed always positive. * This is required to pass 1.2 conformance test. */ -#define DEFINE_PRINT_FLOATS(FLOAT_TYPE) \ - void __pocl_print_floats_##FLOAT_TYPE (param_t *p, const void *vals, int n) \ +#define DEFINE_PRINT_FLOATS(NAME, STORAGE_TYPE, TO_FLOAT_T) \ + void __pocl_print_floats_##NAME (param_t *p, const void *vals, int n) \ { \ const char *NANs[2] = { "nan", "NAN" }; \ const char *INFs[2] = { "inf", "INF" }; \ - FLOAT_TYPE val; \ + STORAGE_TYPE raw; \ + FLOAT_T val; \ DEBUG_PRINTF (("[printf:floats:n=%d]\n", n)); \ flags_t saved_user_flags = p->flags; \ for (int d = 0; d < n; ++d) \ @@ -115,17 +117,15 @@ DEFINE_PRINT_INTS (ulong, int64_t, uint64_t) p->flags = saved_user_flags; \ if (d != 0) \ __pocl_printf_putcf (p, ','); \ - memcpy (&val, vals, sizeof (FLOAT_TYPE)); \ - vals = (char *)vals + sizeof (FLOAT_TYPE); \ + memcpy (&raw, vals, sizeof (STORAGE_TYPE)); \ + vals = (char *)vals + sizeof (STORAGE_TYPE); \ + val = TO_FLOAT_T (raw); \ const char *other = NULL; \ - /* classify through double: exact for half/float, identity for double, \ - and avoids a _Float16 isnan/isinf/signbit path that traps on some \ - runtimes (e.g. MinGW libgcc). */ \ - if (isnan ((double)val)) \ + if (isnan (val)) \ other = NANs[p->flags.uc]; \ - if (isinf ((double)val)) \ + if (isinf (val)) \ { \ - p->flags.sign = signbit ((double)val) ? 1 : 0; \ + p->flags.sign = signbit (val) ? 1 : 0; \ other = INFs[p->flags.uc]; \ } \ if (other) \ @@ -136,17 +136,18 @@ DEFINE_PRINT_INTS (ulong, int64_t, uint64_t) } \ else \ { \ - __pocl_printf_float (p, (FLOAT_T)val); \ + __pocl_printf_float (p, val); \ } \ } \ DEBUG_PRINTF (("[printf:floats:done]\n")); \ } -#ifdef HOST_COMPILER_SUPPORTS_FLOAT16 -DEFINE_PRINT_FLOATS (_Float16) -#endif -DEFINE_PRINT_FLOATS (float) -DEFINE_PRINT_FLOATS (double) +/* Not _Float16: on x86, GCC lowers its conversions to libgcc helpers that + libgcc_s only exports from GCC 12 on, and libpocl then fails to load next + to an older libgcc_s. */ +DEFINE_PRINT_FLOATS (half, uint16_t, pocl_half_to_float) +DEFINE_PRINT_FLOATS (float, float, ) +DEFINE_PRINT_FLOATS (double, double, ) #undef DEFINE_PRINT_FLOATS @@ -574,16 +575,8 @@ __pocl_printf_format_full (param_t *p, char *buffer, uint32_t buffer_size) } else { -#ifdef HOST_COMPILER_SUPPORTS_FLOAT16 - __pocl_print_floats__Float16 (p, buffer, - vector_length); -#else - POCL_MSG_ERR ("printf error: host-side " - "support for FP16 missing\n"); - __pocl_print_ints_ushort (p, buffer, - vector_length, - 0); -#endif + __pocl_print_floats_half (p, buffer, + vector_length); // half2 vectors <64 bits are stored in 64bits if (alloca_length < pointer_size_bytes) alloca_length = pointer_size_bytes; diff --git a/tests/kernel/test_printf_vectors_halfn.cl b/tests/kernel/test_printf_vectors_halfn.cl index d6f7fc3ade..a8a6c25e30 100644 --- a/tests/kernel/test_printf_vectors_halfn.cl +++ b/tests/kernel/test_printf_vectors_halfn.cl @@ -30,6 +30,12 @@ kernel void test_printf_vectors_halfn() printf ("\nhalf VECTORS\n\n"); ushort2 u2 = (ushort2)(0x7C00, 0x7E00); printf("half2 %v2hf\n", (as_half2(u2))); + /* min/max subnormal, min normal, max finite */ + ushort4 u4 = (ushort4)(0x0001, 0x03FF, 0x0400, 0x7BFF); + printf("half4 %v4he\n", (as_half4(u4))); + /* -0, -inf, negative NaN, -min subnormal */ + u4 = (ushort4)(0x8000, 0xFC00, 0xFE00, 0x8001); + printf("half4 %v4hg\n", (as_half4(u4))); printf("half2 %v2hf\n", (half2)(10.112, 20.222)); printf("half3 %v3hf\n", (half3)(10.113, 20.223, 30.333)); printf("half4 %v4hf\n", (half4)(10.114, 20.224, 30.334, 40.444)); diff --git a/tests/kernel/test_printf_vectors_halfn_expout.txt b/tests/kernel/test_printf_vectors_halfn_expout.txt index ea64de26ff..2f51541378 100644 --- a/tests/kernel/test_printf_vectors_halfn_expout.txt +++ b/tests/kernel/test_printf_vectors_halfn_expout.txt @@ -3,6 +3,8 @@ Running test test_printf_vectors_halfn... half VECTORS half2 inf,nan +half4 5.960464e-08,6.097555e-05,6.103516e-05,6.550400e+04 +half4 -0,-inf,nan,-5.96046e-08 half2 10.109375,20.218750 half3 10.109375,20.218750,30.328125 half4 10.117188,20.218750,30.328125,40.437500 From ea24dc230a54a450658501d07c7a2c76c6e24d8c Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Mon, 19 Oct 2026 17:07:11 +0200 Subject: [PATCH 14/23] Account for the z extent and global offset in the grid width pocl_cmd_max_grid_dim_width multiplied the z local size with itself instead of with the number of groups, and ignored the global offset. A grid that is wide only in z, or that is small but offset far from the origin, therefore got the work-group function specialized for small grids, whose range assumptions on the group counts and global offsets then let the optimizer fold e.g. get_num_groups(2) > 65535 or get_global_offset(0) > 65535 to false. --- lib/CL/devices/common.c | 11 ++- tests/regression/CMakeLists.txt | 3 + tests/regression/test_tall_grid.c | 121 ++++++++++++++++++++++++++++++ 3 files changed, 131 insertions(+), 4 deletions(-) create mode 100644 tests/regression/test_tall_grid.c diff --git a/lib/CL/devices/common.c b/lib/CL/devices/common.c index 5f0ca7087f..65f93c49dd 100644 --- a/lib/CL/devices/common.c +++ b/lib/CL/devices/common.c @@ -983,13 +983,16 @@ pocl_fill_dev_sampler_t (dev_sampler_t *ds, struct pocl_argument *parg) } /* Returns the width of the widest dimension in the grid of the given - run command. */ + run command, counted from the origin: the small-grid work-group functions + assume that both the group counts and the global offsets are bounded. */ size_t pocl_cmd_max_grid_dim_width (_cl_command_run *cmd) { - return max (max (cmd->pc.local_size[0] * cmd->pc.num_groups[0], - cmd->pc.local_size[1] * cmd->pc.num_groups[1]), - cmd->pc.local_size[2] * cmd->pc.local_size[2]); + size_t width = 0; + for (unsigned d = 0; d < 3; ++d) + width = max (width, cmd->pc.global_offset[d] + + cmd->pc.local_size[d] * cmd->pc.num_groups[d]); + return width; } diff --git a/tests/regression/CMakeLists.txt b/tests/regression/CMakeLists.txt index a17a518440..c0c6622455 100644 --- a/tests/regression/CMakeLists.txt +++ b/tests/regression/CMakeLists.txt @@ -44,6 +44,7 @@ set(C_PROGRAMS_TO_BUILD test_assign_loop_variable_to_privvar_makes_it_local test_usm_indirect_ptrs test_usm_free_realloc test_sanitize_divrem + test_tall_grid ) if(UNIX) list(APPEND C_PROGRAMS_TO_BUILD test_signal_handlers) @@ -205,6 +206,8 @@ add_test_pocl(NAME "regression/spirv_intel_subgroups" WORKITEM_HANDLER "loops;lo add_test_pocl(NAME "regression/divergent_implicit_barrier_entry" WORKITEM_HANDLER "loops;loopvec;cbs;" COMMAND "test_divergent_implicit_barrier_entry") +add_test_pocl(NAME "regression/tall_grid" COMMAND "test_tall_grid") + add_test_pocl(NAME "regression/uniform_implicit_barrier_entry" WORKITEM_HANDLER "loops;loopvec;cbs;" COMMAND "test_uniform_implicit_barrier_entry") add_test_pocl(NAME "regression/localmem_load_across_barrier" WORKITEM_HANDLER "loops;loopvec;cbs;" COMMAND "test_localmem_load_across_barrier") diff --git a/tests/regression/test_tall_grid.c b/tests/regression/test_tall_grid.c new file mode 100644 index 0000000000..f03aa53623 --- /dev/null +++ b/tests/regression/test_tall_grid.c @@ -0,0 +1,121 @@ +// Copyright (c) 2026 PoCL developers +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +/* + A grid that is only wide in its third dimension, or that is small but far + away from the origin, must not get the work-group function specialized for + small grids: that one tells the optimizer that the group counts and global + offsets are below the specialization limit (65535 on CPUs), so the kernels + below would see get_num_groups(2) and get_global_offset(0) <= 65535 + regardless of the launch. +*/ + +#include "pocl_opencl.h" + +#include +#include + +#define CHECK_ERROR(err) \ + if (err != CL_SUCCESS) \ + { \ + printf ("OpenCL Error %d at %s:%d\n", err, __FILE__, __LINE__); \ + return EXIT_FAILURE; \ + } + +static const char *source + = "kernel void tall (global uint *out) {\n" + " if (get_global_id (2) == get_global_size (2) - 1)\n" + " out[0] = get_num_groups (2) > 65535 ? get_num_groups (2) : 0;\n" + "}\n" + "kernel void offset (global uint *out) {\n" + " out[0] = get_global_offset (0) > 65535 ? get_global_offset (0) : 0;\n" + "}\n"; + +static int +run (cl_context context, + cl_command_queue queue, + cl_program program, + const char *name, + const size_t *offset, + const size_t *global, + cl_uint expected) +{ + cl_int err; + cl_kernel kernel = clCreateKernel (program, name, &err); + CHECK_ERROR (err); + + cl_uint result = 0; + cl_mem out + = clCreateBuffer (context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, + sizeof (result), &result, &err); + CHECK_ERROR (err); + CHECK_ERROR (clSetKernelArg (kernel, 0, sizeof (cl_mem), &out)); + + const size_t local[3] = { 1, 1, 1 }; + CHECK_ERROR (clEnqueueNDRangeKernel (queue, kernel, 3, offset, global, local, + 0, NULL, NULL)); + CHECK_ERROR (clEnqueueReadBuffer (queue, out, CL_TRUE, 0, sizeof (result), + &result, 0, NULL, NULL)); + + CHECK_ERROR (clReleaseMemObject (out)); + CHECK_ERROR (clReleaseKernel (kernel)); + + if (result != expected) + { + printf ("FAIL: kernel %s returned %u, expected %u\n", name, result, + expected); + return EXIT_FAILURE; + } + return EXIT_SUCCESS; +} + +int +main (void) +{ + cl_int err; + cl_platform_id platform; + cl_device_id device; + cl_context context; + cl_command_queue queue; + + CHECK_ERROR (poclu_get_any_device2 (&context, &device, &queue, &platform)); + + cl_program program + = clCreateProgramWithSource (context, 1, &source, NULL, &err); + CHECK_ERROR (err); + CHECK_ERROR (clBuildProgram (program, 1, &device, NULL, NULL, NULL)); + const size_t tall_global[3] = { 1, 1, 70000 }; + int failed = run (context, queue, program, "tall", NULL, tall_global, 70000); + + const size_t offset[3] = { 100000, 0, 0 }; + const size_t small_global[3] = { 1, 1, 1 }; + failed + |= run (context, queue, program, "offset", offset, small_global, 100000); + + CHECK_ERROR (clReleaseProgram (program)); + CHECK_ERROR (clReleaseCommandQueue (queue)); + CHECK_ERROR (clReleaseContext (context)); + CHECK_ERROR (clUnloadPlatformCompiler (platform)); + + if (failed) + return EXIT_FAILURE; + printf ("OK\n"); + return EXIT_SUCCESS; +} From 17d39e8cc8770b7bdd135ebd248a9a8a1de9f3a5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:17:10 +0000 Subject: [PATCH 15/23] build(deps): bump the codeql-dependencies group with 3 updates Bumps the codeql-dependencies group with 3 updates: [github/codeql-action/init](https://github.com/github/codeql-action), [github/codeql-action/analyze](https://github.com/github/codeql-action) and [github/codeql-action/upload-sarif](https://github.com/github/codeql-action). Updates `github/codeql-action/init` from 4.39.0 to 4.39.1 - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee...9b3254085494b55a0f7c4c2b3d2d52cc712ce370) Updates `github/codeql-action/analyze` from 4.39.0 to 4.39.1 - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee...9b3254085494b55a0f7c4c2b3d2d52cc712ce370) Updates `github/codeql-action/upload-sarif` from 4.39.0 to 4.39.1 - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee...9b3254085494b55a0f7c4c2b3d2d52cc712ce370) --- updated-dependencies: - dependency-name: github/codeql-action/init dependency-version: 4.39.1 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: codeql-dependencies - dependency-name: github/codeql-action/analyze dependency-version: 4.39.1 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: codeql-dependencies - dependency-name: github/codeql-action/upload-sarif dependency-version: 4.39.1 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: codeql-dependencies ... Signed-off-by: dependabot[bot] --- .github/workflows/codeql.yml | 4 ++-- .github/workflows/scorecard.yml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 23be969f9c..4cab6ec057 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -62,7 +62,7 @@ jobs: # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee + uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 with: languages: ${{ matrix.language }} build-mode: ${{ matrix.build-mode }} @@ -90,6 +90,6 @@ jobs: exit 1 - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee + uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 with: category: "/language:${{matrix.language}}" diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index 59c5ed2137..cf4edf9d17 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -69,6 +69,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard (optional). # Commenting out will disable upload of results to your repo's Code Scanning dashboard - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee + uses: github/codeql-action/upload-sarif@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 with: sarif_file: results.sarif From a74c7d0230c18bf9098a56a96fdf0c354408e3fa Mon Sep 17 00:00:00 2001 From: anun333 Date: Fri, 30 Oct 2026 11:40:39 -0500 Subject: [PATCH 16/23] clCreateProgramWithBinary: names and comments from review find_index_for_root_device for caller_index, original_device_list and original_num_devices for the caller's list, loop counters declared in the loops, and the comment on set_binary_status as suggested. No change in behaviour. Co-Authored-By: Claude Opus 5.5 --- lib/CL/clCreateProgramWithBinary.c | 35 ++++++++++++++++-------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/lib/CL/clCreateProgramWithBinary.c b/lib/CL/clCreateProgramWithBinary.c index 092a7638af..32bc35d9f8 100644 --- a/lib/CL/clCreateProgramWithBinary.c +++ b/lib/CL/clCreateProgramWithBinary.c @@ -36,26 +36,24 @@ * entries by device, not by position: [sub1, sub2, other] reduces to * [other, root]. */ static unsigned -caller_index (const cl_device_id *caller_devs, cl_uint caller_num, - cl_device_id root) +find_index_for_root_device (const cl_device_id *caller_devs, + cl_uint caller_num, cl_device_id root) { - unsigned j; - for (j = 0; j < caller_num; ++j) + for (unsigned j = 0; j < caller_num; ++j) if (pocl_real_dev (caller_devs[j]) == root) return j; assert (0 && "every root comes from the caller's list"); return 0; } -/* Every entry of the caller's list that reduces to root gets its status. */ +/* Set binary status to 'status' for devices matching to or sub-divided from 'root' device. */ static void set_binary_status (cl_int *binary_status, const cl_device_id *caller_devs, cl_uint caller_num, cl_device_id root, cl_int status) { - unsigned j; if (binary_status == NULL) return; - for (j = 0; j < caller_num; ++j) + for (unsigned j = 0; j < caller_num; ++j) if (pocl_real_dev (caller_devs[j]) == root) binary_status[j] = status; } @@ -110,8 +108,8 @@ create_program_skeleton (cl_context context, cl_uint num_devices, // convert subdevices to devices and remove duplicates; the caller's list // still indexes binaries[], lengths[] and binary_status[] - const cl_device_id *caller_devs = device_list; - cl_uint caller_num = num_devices; + const cl_device_id *original_device_list = device_list; + cl_uint original_num_devices = num_devices; cl_uint real_num_devices = 0; unique_devlist = pocl_unique_device_list(device_list, num_devices, &real_num_devices); num_devices = real_num_devices; @@ -190,7 +188,9 @@ create_program_skeleton (cl_context context, cl_uint num_devices, for (i = 0; i < num_devices; ++i) { - unsigned src = caller_index (caller_devs, caller_num, device_list[i]); + unsigned src = find_index_for_root_device (original_device_list, + original_num_devices, + device_list[i]); const unsigned char *binary = binaries[src]; size_t length = lengths[src]; @@ -219,8 +219,9 @@ create_program_skeleton (cl_context context, cl_uint num_devices, program->binary_sizes[i] = (size_t)size; } - set_binary_status (binary_status, caller_devs, caller_num, - device_list[i], CL_SUCCESS); + set_binary_status (binary_status, original_device_list, + original_num_devices, device_list[i], + CL_SUCCESS); } /* check if the driver supports that binary */ else @@ -233,15 +234,17 @@ create_program_skeleton (cl_context context, cl_uint num_devices, program->binary_sizes[i] = length; program->binaries[i] = (unsigned char *)malloc (length); memcpy (program->binaries[i], binary, length); - set_binary_status (binary_status, caller_devs, caller_num, - device_list[i], CL_SUCCESS); + set_binary_status (binary_status, original_device_list, + original_num_devices, device_list[i], + CL_SUCCESS); } else { POCL_MSG_WARN ("Could not recognize binary for device %u\n", src); - set_binary_status (binary_status, caller_devs, caller_num, - device_list[i], CL_INVALID_BINARY); + set_binary_status (binary_status, original_device_list, + original_num_devices, device_list[i], + CL_INVALID_BINARY); errcode = CL_INVALID_BINARY; goto ERROR; } From 8a741e5273830e394a306cc8d933639a0861d4cd Mon Sep 17 00:00:00 2001 From: anun333 Date: Sat, 31 Oct 2026 08:09:41 -0500 Subject: [PATCH 17/23] test_program_binary_subdevices: refuse different binaries for sub-devices of one root A program keeps one binary per root device, so two sub-devices of one root given different binaries cannot both be kept: kernels on the second would run the first one's binary. clCreateProgramWithBinary must fail with CL_INVALID_BINARY and say so in both entries of binary_status. Co-Authored-By: Claude Opus 5.5 --- .../runtime/test_program_binary_subdevices.c | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tests/runtime/test_program_binary_subdevices.c b/tests/runtime/test_program_binary_subdevices.c index b4cc264f11..7481ca95a6 100644 --- a/tests/runtime/test_program_binary_subdevices.c +++ b/tests/runtime/test_program_binary_subdevices.c @@ -201,6 +201,27 @@ main (void) int bad = trial ("[other, sub1, sub2]", ctx, ctl, cbins, clens, cwant); bad |= trial ("[sub1, sub2, other]", ctx, shift, sbins, slens, swant); + /* Two sub-devices of one root given different binaries: the program keeps + one binary per root device, so it must refuse rather than run sub1's + binary on sub2. */ + size_t lsub9; + unsigned char *bsub9 = binary_for (ctx, SRC9, sub[0], root, &lsub9); + unsigned char *dbins[3] = { bsub, bsub9, bother }; + size_t dlens[3] = { lsub, lsub9, lother }; + cl_int dst[3] = { UNWRITTEN, UNWRITTEN, UNWRITTEN }; + cl_program dp = clCreateProgramWithBinary ( + ctx, 3, shift, dlens, (const unsigned char **)dbins, dst, &e); + printf ("[sub1, sub2, other] with different binaries for sub1 and sub2: " + "error %d, binary_status {%d, %d, %d}", + e, dst[0], dst[1], dst[2]); + int dbad = (e != CL_INVALID_BINARY || dp != NULL + || dst[0] != CL_INVALID_BINARY || dst[1] != CL_INVALID_BINARY); + printf (" -> %s\n", dbad ? "WRONG" : "ok"); + if (dp != NULL) + CHECK (clReleaseProgram (dp)); + bad |= dbad; + free (bsub9); + free (bsub); free (bother); CHECK (clReleaseContext (ctx)); From 171ed9ad7e6c32873fe85530c1b8e5b10ec69f25 Mon Sep 17 00:00:00 2001 From: anun333 Date: Sat, 31 Oct 2026 08:09:49 -0500 Subject: [PATCH 18/23] clCreateProgramWithBinary: refuse different binaries for one root device A program keeps one binary per root device, and sub-devices use their root's slot. When two entries of the caller's list reduce to the same root and carry different binaries, the second could not be kept and kernels on its device would run the first's. Fail with CL_INVALID_BINARY and set it in both entries of binary_status. Identical binaries, the usual case for a program built once for both sub-devices, keep working. Co-Authored-By: Claude Opus 5.5 --- lib/CL/clCreateProgramWithBinary.c | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/lib/CL/clCreateProgramWithBinary.c b/lib/CL/clCreateProgramWithBinary.c index 32bc35d9f8..4357f770f9 100644 --- a/lib/CL/clCreateProgramWithBinary.c +++ b/lib/CL/clCreateProgramWithBinary.c @@ -131,6 +131,29 @@ create_program_skeleton (cl_context context, cl_uint num_devices, device_list[i]->long_name); } + /* The program keeps one binary per root device, so entries that reduce to + the same root must carry the same binary: a different one could not be + kept, and kernels on its device would run the other's. */ + if (binaries != NULL && lengths != NULL) + for (i = 0; i < original_num_devices; ++i) + for (j = i + 1; j < original_num_devices; ++j) + { + if (pocl_real_dev (original_device_list[i]) + != pocl_real_dev (original_device_list[j]) + || binaries[i] == NULL || binaries[j] == NULL) + continue; + if (lengths[i] == lengths[j] + && (binaries[i] == binaries[j] + || memcmp (binaries[i], binaries[j], lengths[i]) == 0)) + continue; + if (binary_status != NULL) + binary_status[i] = binary_status[j] = CL_INVALID_BINARY; + POCL_GOTO_ERROR_ON (1, CL_INVALID_BINARY, + "devices %u and %u share a root device but " + "were given different binaries\n", + i, j); + } + if ((program = (cl_program) calloc (1, sizeof (struct _cl_program))) == NULL) { errcode = CL_OUT_OF_HOST_MEMORY; From 6b8a44a484b51842cda731de279ba8edd5fac333 Mon Sep 17 00:00:00 2001 From: Woody Chow Date: Mon, 2 Nov 2026 02:54:26 +0000 Subject: [PATCH 19/23] Pass LLVMContext to PassBuilder constructor for LLVM 24 In LLVM 24, the llvm::PassBuilder constructor was updated to take llvm::LLVMContext &Context as its first parameter: https://github.com/llvm/llvm-project/commit/910cdcd093775616973dfaf6c09850bc93873cb3 (PR https://github.com/llvm/llvm-project/pull/233150) Guard the PassBuilder constructor calls in pocl_llvm_wg.cc with #if LLVM_MAJOR >= 24 to pass Context when building with LLVM 24 while preserving backward compatibility with older LLVM versions. --- lib/CL/pocl_llvm_wg.cc | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/lib/CL/pocl_llvm_wg.cc b/lib/CL/pocl_llvm_wg.cc index e1712c733b..a5e2a5e20a 100644 --- a/lib/CL/pocl_llvm_wg.cc +++ b/lib/CL/pocl_llvm_wg.cc @@ -244,7 +244,11 @@ llvm::Error PoCLModulePassManager::build(std::string PoclPipeline, // Take a look at the PassBuilder constructor parameters for more // customization, e.g. specifying a TargetMachine or various debugging // options. +#if LLVM_MAJOR >= 24 + PassB.reset(new PassBuilder(Context, TM, PTO, std::nullopt, &PIC)); +#else PassB.reset(new PassBuilder(TM, PTO, std::nullopt, &PIC)); +#endif PassBuilder &PB = *PassB.get(); #if 0 @@ -1574,7 +1578,11 @@ void populateModulePM([[maybe_unused]] void *Passes, void *Module, PrintPassOpts)); SI->registerCallbacks(PIC, &MAM); +#if LLVM_MAJOR >= 24 + PassBuilder PB(Context, TM, PTO, std::nullopt, &PIC); +#else PassBuilder PB(TM, PTO, std::nullopt, &PIC); +#endif // Register all the basic analyses with the managers. PB.registerModuleAnalyses(MAM); From c6310934e83575caa1a203ea93be49eb49db8966 Mon Sep 17 00:00:00 2001 From: Woody Chow Date: Mon, 2 Nov 2026 02:54:27 +0000 Subject: [PATCH 20/23] [llvmopencl] Use BasicBlock::getFirstNonPHIOrLifetime for LLVM 24 In LLVM 24, llvm::BasicBlock::getFirstNonPHIOrDbgOrLifetime() was renamed to llvm::BasicBlock::getFirstNonPHIOrLifetime(): https://github.com/llvm/llvm-project/commit/06d62fc244617b7b3e70c93ec9b28a40c1280261 (PR https://github.com/llvm/llvm-project/pull/232604) Guard the call in SubCFGFormation.cc with #if LLVM_MAJOR >= 24 to support LLVM 24 while preserving backward compatibility with older LLVM versions. --- lib/llvmopencl/SubCFGFormation.cc | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/llvmopencl/SubCFGFormation.cc b/lib/llvmopencl/SubCFGFormation.cc index 8048b3a089..7c2300ec2f 100644 --- a/lib/llvmopencl/SubCFGFormation.cc +++ b/lib/llvmopencl/SubCFGFormation.cc @@ -1226,7 +1226,11 @@ void SubCFGFormation::arrayifyAllocas( for (auto &SubCfg : SubCfgs) { +#if LLVM_MAJOR >= 24 + auto Before = SubCfg.getLoadBB()->getFirstNonPHIOrLifetime(); +#else auto Before = SubCfg.getLoadBB()->getFirstNonPHIOrDbgOrLifetime(); +#endif #if LLVM_MAJOR < 20 auto GEP = createContextArrayGEP(Alloca, Before, PaddingAdded); #else From e5aa2826b611b9c937f0c5b5be436e7fd662155a Mon Sep 17 00:00:00 2001 From: Paulius Velesko Date: Mon, 26 Oct 2026 17:37:21 +0200 Subject: [PATCH 21/23] Fix the SVM and USM shadow-buffer failure paths clMemAllocINTEL and clSVMAlloc detect a failed shadow clCreateBuffer only through errcode. That path is reachable when no device in the context supports cl_ext_buffer_device_address (clCreateBuffer then fails with CL_INVALID_DEVICE), and, once clCreateBuffer reports an overlapping device address as an error (pocl/pocl#2376), on an overlap too. Both were broken: clMemAllocINTEL returned NULL without writing errcode_ret. Go through the common ERROR exit instead. clSVMAlloc called pocl_raw_ptr_set_erase, which frees the item, and then POCL_MEM_FREE on the same item. Drop the second free. --- lib/CL/clMemAllocINTEL.c | 3 ++- lib/CL/clSVMAlloc.c | 1 - 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/CL/clMemAllocINTEL.c b/lib/CL/clMemAllocINTEL.c index af7961b50b..9abcdf7a90 100644 --- a/lib/CL/clMemAllocINTEL.c +++ b/lib/CL/clMemAllocINTEL.c @@ -172,7 +172,8 @@ pocl_usm_alloc (unsigned alloc_type, cl_context context, cl_device_id device, POCL_UNLOCK_OBJ (context); device->ops->usm_free (device, ptr); POCL_MSG_ERR ("Failed to allocate memory a shadow cl_mem object.\n"); - return NULL; + ptr = NULL; + goto ERROR; } item->shadow_cl_mem = clmem_shadow; diff --git a/lib/CL/clSVMAlloc.c b/lib/CL/clSVMAlloc.c index 2cc24970e4..700346f591 100644 --- a/lib/CL/clSVMAlloc.c +++ b/lib/CL/clSVMAlloc.c @@ -137,7 +137,6 @@ POname(clSVMAlloc)(cl_context context, POCL_LOCK_OBJ (context); pocl_raw_ptr_set_erase (context->raw_ptrs, item); POCL_UNLOCK_OBJ (context); - POCL_MEM_FREE (item); context->svm_allocdev->ops->svm_free (context->svm_allocdev, ptr); POCL_MSG_ERR ("Failed to allocate memory a shadow cl_mem object.\n"); return NULL; From e4afc5decf268688080c1c76e5d6f9f0712c0bff Mon Sep 17 00:00:00 2001 From: Paulius Velesko Date: Mon, 26 Oct 2026 17:37:33 +0200 Subject: [PATCH 22/23] Do not touch *event when an SVM/USM memcpy fails to enqueue pocl_svm_memcpy_common forwards to clEnqueueCopyBuffer, clEnqueueWriteBuffer or clEnqueueReadBuffer and then writes (*event)->command_type whenever event is non-NULL. When the inner call fails it does not create an event, so *event is whatever the caller left there, typically NULL, and clEnqueueSVMMemcpy or clEnqueueMemcpyINTEL crashes instead of returning the error (for example CL_INVALID_CONTEXT for a wait-list event from another context, or CL_INVALID_MEM_OBJECT for a pointer whose shadow buffer is missing). Only set the command type on success. Adds a check to runtime/test_svm. --- lib/CL/clEnqueueSVMMemcpy.c | 2 +- tests/runtime/test_svm.cpp | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/lib/CL/clEnqueueSVMMemcpy.c b/lib/CL/clEnqueueSVMMemcpy.c index 3f89b7fe20..358dc02413 100644 --- a/lib/CL/clEnqueueSVMMemcpy.c +++ b/lib/CL/clEnqueueSVMMemcpy.c @@ -155,7 +155,7 @@ pocl_svm_memcpy_common (cl_command_buffer_khr command_buffer, } // TODO this is likely very wrong - if (event != NULL) + if (errcode == CL_SUCCESS && event != NULL) (*event)->command_type = command_type; return errcode; diff --git a/tests/runtime/test_svm.cpp b/tests/runtime/test_svm.cpp index 7198bb72a5..7c2d4acf22 100644 --- a/tests/runtime/test_svm.cpp +++ b/tests/runtime/test_svm.cpp @@ -397,6 +397,35 @@ int TestMultiDevice_CGSVM(cl::Platform Platform) { return EXIT_FAILURE; } +// A failed SVM memcpy enqueue must return its error without touching *event. +int TestSVMMemcpyFailedEnqueue(cl::Platform Platform) { + try { + cl_context_properties cprops[] = {CL_CONTEXT_PLATFORM, + (cl_context_properties)Platform(), 0}; + cl::Context Context(CL_DEVICE_TYPE_CPU | CL_DEVICE_TYPE_GPU, cprops); + cl::Device Device = Context.getInfo()[0]; + cl::CommandQueue Queue(Context, Device); + cl::Context Other(Device); + cl::UserEvent Foreign(Other); + + char Host[64]; + void *Svm = clSVMAlloc(Context(), CL_MEM_READ_WRITE, sizeof(Host), 0); + cl_event Ev = nullptr; + cl_event Wait = Foreign(); + cl_int Err = clEnqueueSVMMemcpy(Queue(), CL_FALSE, Svm, Host, sizeof(Host), + 1, &Wait, &Ev); + clSVMFree(Context(), Svm); + if (Err == CL_INVALID_CONTEXT) { + std::cout << "OK" << std::endl; + return EXIT_SUCCESS; + } + std::cout << "FAIL: got error " << Err << std::endl; + } catch (cl::Error &err) { + std::cout << "FAIL with OpenCL error = " << err.err() << std::endl; + } + return EXIT_FAILURE; +} + static char SimpleKernelSourceCode[] = R"raw( __kernel void simple_kernel(__global int *Out, @@ -930,6 +959,10 @@ int main() { if (TestMultiDevice_CGSVM(PlatformList[0]) == EXIT_FAILURE) return EXIT_FAILURE; + std::cout << "TestSVMMemcpyFailedEnqueue: "; + if (TestSVMMemcpyFailedEnqueue(PlatformList[0]) == EXIT_FAILURE) + return EXIT_FAILURE; + PlatformList[0].unloadCompiler(); std::cout << "OK" << std::endl; From 77460a179eaa69f48d4a010e047e44f9d4344b5d Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Tue, 3 Nov 2026 14:56:43 +0100 Subject: [PATCH 23/23] Fix abs() of the minimum signed integer abs() returns ugentype, so abs(INT_MIN) is (uint)2147483648. The int overload used __builtin_abs, which is undefined for INT_MIN and becomes llvm.abs with int_min_is_poison set, and the long overload negated the signed value with an nsw sub. LLVM then assumed that the result's top bit is clear, e.g. folding abs(x) >> 31 to 0 or converting abs(x) to float as a signed value. Vector overloads were split down to these scalar ones, and abs_diff() of operands with different signs uses abs(). Negate in the unsigned type instead, for all types at once, which LLVM turns into llvm.abs without the poison flag. Register the existing kernel/test_abs and kernel/test_abs_diff, which were never run, and check the top bit of abs() of the minimum value. --- lib/kernel/abs.cl | 16 +++++++--------- tests/kernel/CMakeLists.txt | 7 +++++++ tests/kernel/test_abs.cl | 26 ++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 9 deletions(-) diff --git a/lib/kernel/abs.cl b/lib/kernel/abs.cl index 22b6e4ff40..14bea59c45 100644 --- a/lib/kernel/abs.cl +++ b/lib/kernel/abs.cl @@ -24,12 +24,10 @@ #include "templates.h" -#define __builtin_abshh(a) ((uchar )(a>=(char )0 ? a : (char )-a)) -#define __builtin_absh(a) ((ushort)(a>=(short)0 ? a : (short)-a)) -#define __builtin_absl(a) ((ulong )(a>=(long )0 ? a : (long )-a)) -#define __builtin_absuhh(a) a -#define __builtin_absuh(a) a -#define __builtin_absu(a) a -#define __builtin_absul(a) a - -DEFINE_BUILTIN_UG_G(abs) +/* abs(INT_MIN) is 2^31 as uint. Negate in the unsigned type: negating the + signed value overflows for the minimum value, and __builtin_abs is + undefined for it. */ +DEFINE_EXPR_UG_G (abs, ({ + ugtype u = __builtin_astype (a, ugtype); + a < (gtype)0 ? -u : u; + })) diff --git a/tests/kernel/CMakeLists.txt b/tests/kernel/CMakeLists.txt index f2e9dca6f8..710e42edc8 100644 --- a/tests/kernel/CMakeLists.txt +++ b/tests/kernel/CMakeLists.txt @@ -52,6 +52,12 @@ add_test_pocl(NAME "kernel/test_convert_type_8" add_test_pocl(NAME "kernel/test_convert_type_16" COMMAND "kernel" "test_convert_type_16") +add_test_pocl(NAME "kernel/test_abs" + COMMAND "kernel" "test_abs") + +add_test_pocl(NAME "kernel/test_abs_diff" + COMMAND "kernel" "test_abs_diff") + add_test_pocl(NAME "kernel/test_bitselect" COMMAND "kernel" "test_bitselect") @@ -128,6 +134,7 @@ foreach(VARIANT ${VARIANTS}) "kernel/test_convert_type_1_${VARIANT}" "kernel/test_convert_type_2_${VARIANT}" "kernel/test_convert_type_4_${VARIANT}" "kernel/test_convert_type_8_${VARIANT}" "kernel/test_convert_type_16_${VARIANT}" "kernel/test_hadd_${VARIANT}" "kernel/test_rotate_${VARIANT}" + "kernel/test_abs_${VARIANT}" "kernel/test_abs_diff_${VARIANT}" PROPERTIES COST 40.0 PROCESSORS 1 diff --git a/tests/kernel/test_abs.cl b/tests/kernel/test_abs.cl index f41007f206..78c648e5b8 100644 --- a/tests/kernel/test_abs.cl +++ b/tests/kernel/test_abs.cl @@ -19,6 +19,32 @@ DEFINE_BODY_G_HADD (test_abs, ({ } error = true; } + // abs of the minimum value is 2^(bits-1), so the top + // bit of the result is set. Computing it as a signed + // negation overflows, after which LLVM may assume that + // the bit is clear. + Tvec m, res_top; + for (int n = 0; n < vecsize; ++n) + { + m.s[n] = x.s[n] & tmin; + } + res_top.u = abs (m.v) >> (sugtype)(bits - 1); + equal = true; + for (int n = 0; n < vecsize; ++n) + { + equal = equal && res_top.s[n] == (m.s[n] != 0); + } + if (!equal) + { + printf ("FAIL: abs top bit type=%s\n", typename); + for (int n = 0; n < vecsize; ++n) + { + printf (" [%d] a=%s good=%d res=%d\n", n, + m.s[n] != 0 ? "min" : "0", + (int)(m.s[n] != 0), (int)res_top.s[n]); + } + error = true; + } })) kernel void