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 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; } diff --git a/lib/CL/clCreateProgramWithBinary.c b/lib/CL/clCreateProgramWithBinary.c index 5c164d7775..4357f770f9 100644 --- a/lib/CL/clCreateProgramWithBinary.c +++ b/lib/CL/clCreateProgramWithBinary.c @@ -30,6 +30,34 @@ #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 +find_index_for_root_device (const cl_device_id *caller_devs, + cl_uint caller_num, cl_device_id root) +{ + 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; +} + +/* 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) +{ + if (binary_status == NULL) + return; + for (unsigned 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 +106,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 *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; @@ -100,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; @@ -157,14 +211,20 @@ create_program_skeleton (cl_context context, cl_uint num_devices, for (i = 0; i < num_devices; ++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]; + /* 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 +242,32 @@ 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, original_device_list, + original_num_devices, 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, original_device_list, + original_num_devices, 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, original_device_list, + original_num_devices, device_list[i], + CL_INVALID_BINARY); errcode = CL_INVALID_BINARY; goto ERROR; } 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/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); 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; 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.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/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/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) 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/lib/CL/pocl_build.c b/lib/CL/pocl_build.c index e75ba3f926..fab98863e1 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 " \ @@ -264,10 +266,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 +273,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) { @@ -845,8 +851,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; 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); 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/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 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_; }; 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 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 diff --git a/tests/regression/CMakeLists.txt b/tests/regression/CMakeLists.txt index a17a518440..863ca9e13c 100644 --- a/tests/regression/CMakeLists.txt +++ b/tests/regression/CMakeLists.txt @@ -44,6 +44,8 @@ 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 + test_tall_grid ) if(UNIX) list(APPEND C_PROGRAMS_TO_BUILD test_signal_handlers) @@ -205,6 +207,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") @@ -221,6 +225,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; +} 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() << ")" 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; +} 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..7481ca95a6 --- /dev/null +++ b/tests/runtime/test_program_binary_subdevices.c @@ -0,0 +1,232 @@ +/* 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)); + unsigned char *r = NULL; + for (cl_uint i = 0; i < n; i++) + if (!r && (d[i] == want || d[i] == alt)) + { + *len = sz[i]; + r = b[i]; + } + 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 + 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); + + /* 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)); + CHECK (clReleaseDevice (sub[0])); + CHECK (clReleaseDevice (sub[1])); + printf (bad ? "FAIL\n" : "OK\n"); + return bad ? EXIT_FAILURE : EXIT_SUCCESS; +} 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)); 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;