[llvm] [offload] Add olLaunchKernelWithPtrArgs with an argument pointer array (PR #194333)
Piotr Balcer via llvm-commits
llvm-commits at lists.llvm.org
Mon Apr 27 03:22:53 PDT 2026
https://github.com/pbalcer created https://github.com/llvm/llvm-project/pull/194333
The existing olLaunchKernel function accepts arguments through a single contiguous packaged buffer, with an unspecified, implementation-defined, layout. In practice, the existing AMDGPU and CUDA backend plugins require the layout to follow C/C++ ABI rules.
This makes for a simple API when the arguments are already packaged in an existing structure:
```
struct {
char A;
int *B;
short C;
} Args{0, nullptr, 0};
olLaunchKernel(Queue, Device, Kernel, &Args, sizeof(Args), &LaunchArgs);
```
In practice, this has a number of hard to workaround downsides.
# Limitations of the buffer-based API
## Runtime argument buffer construction
The example above shows the simplest scenario, where the olLaunchKernel function is invoked directly by a program. In practice, a language runtime that uses liboffload may need to construct the argument buffer at runtime. This may involve allocating a variably-sized buffer and populating it correctly, accounting for alignment and padding, with user-provided arguments.
Constructing such a buffer may be non-trivial, or even impossible, in scenarios where the language runtime doesn't have full argument metadata containing size or alignment information about arguments.
In addition to the above issue, constructing such a buffer, at runtime during kernel launch, adds an otherwise avoidable host copy before the plugin's, or driver's, own copy. Each existing (AMDGPU/HSA, CUDA, Level-Zero) and anticipated (OpenCL) backend already needs to create its own GPU-accessible copy of the kernel argument buffer, extending its lifetime past the kernel launch function.
## Unspecified argument buffer ABI
Another issue with an argument buffer is that its layout is currently implementation-defined. While they may be compatible in practice, relying on C/C++ ABI rules, the AMDGPU kernarg and NVPTX .param are two distinct ABIs.
Allowing the layout to be implementation-defined may require the caller to construct the buffer differently based on the underlying backend. In most scenarios, liboffload users should not need to be aware of the choice of the backend, instead relying on the provided abstractions. Similarily, the compiler can't optimize code that produces the buffer if the layout can't be determined at compile-time.
A target independent API accepting a buffer would have to define its own layout compatible with, or at least convertable to, all existing and future backends. Documenting the layout format would be a non-trivial endeavour, likely involving collaboration with various other entities, such as the Khronos Group, if we wanted for that layout to be natively supported by all the backends.
## Non-straightforward backend implementations
The only two backends that can natively implement the existing method of passing arguments are CUDA and AMDGPU. For OpenCL and Level-Zero, the plugins would need to internally translate the contiguous buffer into either calls to clSetKernelArg / zeKernelSetArgumentValue or, in the case of Level Zero, an array of pointers to arguments, for use in zeCommandListAppendLaunchKernelWithArguments
(https://oneapi-src.github.io/level-zero-spec/level-zero/latest/core/api.html#zecommandlistappendlaunchkernelwitharguments).
Doing this translation is non-trivial, since it requires the knowledge of size and alignment of arguments within the buffer. Information which is not provided through the olLaunchKernel API. There's currently no API in Level-Zero or OpenCL that can be reliably used to retrieve argument metadata from a program. Previously, we've attempted to solve this by adding explicit argument metadata to olLaunchKernel:
```
struct {
char A;
int *B;
short C;
} Args{0, nullptr, 0};
uint64_t ArgSizes[] = {sizeof(char), sizeof(int *), sizeof(short)};
ol_kernel_launch_prop_t Props[] = {
{OL_KERNEL_LAUNCH_PROP_TYPE_SIZE, ArgSizes},
OL_KERNEL_LAUNCH_PROP_END
};
olLaunchKernel(Queue, Device, Kernel, &Args, sizeof(Args), …, Props);
```
This makes the API harder to use, and, most importantly, is insufficient if we want the API to be target independent. The API above, with just an array of sizes for each argument, does not allow the plugin to account for padding inside of the buffer. OpenCL and Level-Zero plugins would need to see a tightly-packed buffer, while CUDA and AMDGPU plugins need a C/C++ ABI-padded one.
## Difficulty of extracting kernel argument metadata from programs
One solution to retrieving kernel argument metadata could be to read them from the program image. This is similar to how the AMDGPU plugin already reads general kernel metadata (readAMDGPUMetaDataFromImage).
However, this would require that the program image format accepted by liboffload is formalized, and that the OpenCL and Level-Zero plugins parse and read that format to extract the required metadata. While for many initial use cases, it may be enough to define the program image format to be SPIR-V for Level-Zero and OpenCL, it would not allow us to support creating programs from an existing implementation-specific binary. Such functionality will be required to support some SYCL features, such as kernel module interop (where the kernel is created from an existing backend binary), runtime compilation, and kernel caching.
The equivalent OpenCL API is clCreateProgramWithBinary, where the documentation states the following:
> The program binary can consist of either or both:
> - Device-specific code and/or,
> - Implementation-specific intermediate representation (IR) which
> will be converted to the device-specific code.
https://registry.khronos.org/OpenCL/sdk/3.0/docs/man/html/clCreateProgramWithBinary.html
Extracting kernel argument metadata from such binaries would require the generic OpenCL backend to parse vendor-specific binary formats, one per implementation it intends to support.
# Proposed Solution: Pointer-Based Kernel Argument Passing
This PR adds a new launch kernel API, olLaunchKernelWithPtrArgs, that accepts an array of pointers to arguments:
```
void *ArgPtrs[] = {&A, &B, &C};
size_t ArgSizes[] = {sizeof(A), sizeof(B), sizeof(C)};
olLaunchKernelWithPtrArgs(Queue, Device, Kernel, ArgPtrs, ArgSizes, &LaunchArgs);
```
However, our strong preference would be to change the existing olLaunchKernel API to accept an array of argument pointers, leaving this as the only method of kernel dispatch. Otherwise, the API with a packaged buffer will remain unimplementable or non-portable for some backends, including OpenCL and Level Zero.
The newly proposed interface is implementable by existing and anticipated backends, is familiar to CUDA programmers, eliminates the extraneous construction of a contiguous arguments buffer, replacing it with constructing an array of pointers, sidesteps the alignment requirements, does not require reading program image metadata where it's impractical, and enables a compliant SYCL implementation to be built on top of it.
The ArgSizes array is required to support OpenCL, which does not have native support for launching a kernel with an argument pointer array, or a reliable way of retrieving argument sizes for a kernel.
## Mapping the proposed API to backends
CUDA and Level-Zero both support accepting an array of pointers to kernel arguments, through `cuLaunchKernel`
(https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EXEC.html#group__CUDA__EXEC_1gb8f3dc3031b40da29d5f9a7139e52e15) and `zeCommandListAppendLaunchKernelWithArguments` (https://oneapi-src.github.io/level-zero-spec/level-zero/latest/core/api.html#zecommandlistappendlaunchkernelwitharguments) respectively.
For OpenCL, which requires the kernel arguments to be set separately from the kernel launch, a potential implementation can extract the number of arguments from the OpenCL API, and then iterate over the argument pointer and size arrays:
```
cl_uint num_args = 0;
cl_int err = clGetKernelInfo(kernel, CL_KERNEL_NUM_ARGS,
sizeof(num_args), &num_args, NULL);
for (cl_uint i = 0; i < num_args; ++i) {
clSetKernelArg(kernel, i, ArgSizes[i], ArgPtrs[i]);
}
```
The AMDGPU plugin needs to construct a contiguous buffer using the array of argument pointers. To do this conversion, we need to have offsets at which to place the arguments. Here, luckily, as mentioned before, the AMD plugin already reads kernel metadata from the program image. The implementation simply retrieves size and offset for each argument from the kernel image, and then uses it to populate a buffer.
## Supporting SYCL with the proposed API
SYCL 2020, and Intel's intel/llvm SYCL implementation, uses 6 fundamental kinds of arguments:
1. USM pointers
2. Buffers
3. Images
4. Samplers
5. Values
6. Local Arguments
Which map to 5 kinds of arguments in Unified Runtime:
```
typedef enum ur_exp_kernel_arg_type_t {
UR_EXP_KERNEL_ARG_TYPE_VALUE = 0,
UR_EXP_KERNEL_ARG_TYPE_POINTER = 1,
UR_EXP_KERNEL_ARG_TYPE_MEM_OBJ = 2,
UR_EXP_KERNEL_ARG_TYPE_LOCAL = 3,
UR_EXP_KERNEL_ARG_TYPE_SAMPLER = 4,
...
} ur_exp_kernel_arg_type_t;
```
The following SYCL 2020 program demonstrates their use:
```
#include <sycl/sycl.hpp>
#include <cstdio>
#include <cstdlib>
int main() {
sycl::queue q;
int *usm_ptr = sycl::malloc_host<int>(1, q);
*usm_ptr = -1;
int host_data[1] = {5};
sycl::buffer<int, 1> buf(host_data, sycl::range<1>(1));
sycl::image<2> img(sycl::image_channel_order::rgba,
sycl::image_channel_type::fp32,
sycl::range<2>(4, 4));
sycl::sampler samp(
sycl::coordinate_normalization_mode::unnormalized,
sycl::addressing_mode::clamp,
sycl::filtering_mode::nearest);
int val = 42;
q.submit([&](sycl::handler &h) {
auto buf_acc =
buf.get_access<sycl::access::mode::read_write>(h);
auto img_acc =
img.get_access<sycl::float4,
sycl::access::mode::read>(h);
sycl::local_accessor<int, 1> local_mem(
sycl::range<1>(64), h);
sycl::local_accessor<int, 1> local_mem2(
sycl::range<1>(64), h);
h.parallel_for(sycl::nd_range<1>(1, 1),
[=](sycl::nd_item<1> item) {
local_mem[0] = val;
local_mem2[0] = val + 1;
buf_acc[0] = buf_acc[0] + local_mem[0] + local_mem2[0];
usm_ptr[0] = buf_acc[0];
// just to keep the args
(void)img_acc;
(void)samp;
});
});
q.wait();
int expected = 5 + 42 + 43;
printf("usm_ptr[0] = %d (expected %d)\n", *usm_ptr, expected);
sycl::free(usm_ptr, q);
return 0;
}
```
The kernel launch uses the following UR call (simplified for legibility):
```
urEnqueueKernelLaunchWithArgsExp(
.hQueue = 0xca2f090,
.hKernel = 0xc7640f0,
.workDim = 1,
.pGlobalWorkOffset = nullptr,
.pGlobalWorkSize = 0xc6e1c38 (1),
.pLocalWorkSize = 0xc6e1c50 (1),
.numArgs = 8,
.pArgs = 0xc754710 {
{.type = UR_EXP_KERNEL_ARG_TYPE_LOCAL, .index = 0, .size = 256,
.value = (union ur_exp_kernel_arg_value_t){<unknown>}},
{.type = UR_EXP_KERNEL_ARG_TYPE_VALUE, .index = 1, .size = 4,
.value = (union ur_exp_kernel_arg_value_t){.value = 0xc6e23e8}},
{.type = UR_EXP_KERNEL_ARG_TYPE_LOCAL, .index = 2, .size = 256,
.value = (union ur_exp_kernel_arg_value_t){<unknown>}},
{.type = UR_EXP_KERNEL_ARG_TYPE_MEM_OBJ, .index = 3, .size = 8,
.value = (union ur_exp_kernel_arg_value_t){
.memObjTuple = (struct ur_exp_kernel_arg_mem_obj_tuple_t){
.hMem = 0xc6e60f0, .flags = UR_MEM_FLAG_READ_WRITE}}},
{.type = UR_EXP_KERNEL_ARG_TYPE_VALUE, .index = 4, .size = 8,
.value = (union ur_exp_kernel_arg_value_t){.value = 0xc6966f0}},
{.type = UR_EXP_KERNEL_ARG_TYPE_POINTER, .index = 5, .size = 8,
.value = (union ur_exp_kernel_arg_value_t){.pointer = ...}},
{.type = UR_EXP_KERNEL_ARG_TYPE_MEM_OBJ, .index = 6, .size = 8,
.value = (union ur_exp_kernel_arg_value_t){
.memObjTuple = (struct ur_exp_kernel_arg_mem_obj_tuple_t){
.hMem = 0xc6ebac0, .flags = UR_MEM_FLAG_READ_ONLY}}},
{.type = UR_EXP_KERNEL_ARG_TYPE_SAMPLER, .index = 7, .size = 8,
.value = (union ur_exp_kernel_arg_value_t){.sampler = 0xca50750}}
},
...
) -> UR_RESULT_SUCCESS;
```
In order to support a compliant SYCL 2020 specification, liboffload launch kernel API needs to be able to support all these kinds of arguments. The proposed API makes this straightforward. To launch the kernel above, the language runtime could use the liboffload API in the following way:
```
ol_kernel_launch_size_args_t LaunchArgs;
LaunchArgs.Dimensions = 1;
LaunchArgs.GroupSize = {1, 1, 1};
LaunchArgs.NumGroups = {1, 1, 1};
// CUDA, HSA, Level Zero, and OpenCL have a differing model of
// shared / local memory. The lowest common denominator is setting
// only a single shared memory block to contain all memory required
// by SYCL's local accessors, with the language runtime additionally
// setting offsets into that block as value arguments.
// Level Zero doesn't currently implement this feature.
// The SPIR-V kernel is expected to declare a single SLM argument
// at the last position when this field is set.
LaunchArgs.DynSharedMemory = 512;
SmallVector<void *, 8> ArgPtrs;
SmallVector<size_t, 8> ArgSizes;
// [0] local_mem: first local accessor, offset 0 into the shared
// memory block.
uint32_t LocalOffset0 = 0;
ArgPtrs.push_back(&LocalOffset0);
ArgSizes.push_back(sizeof(uint32_t));
// [1] val: plain value argument (int val = 42).
int Val = 42;
ArgPtrs.push_back(&Val);
ArgSizes.push_back(sizeof(int));
// [2] local_mem2: second local accessor, offset 256 into the shared
// memory block.
uint32_t LocalOffset1 = 256;
ArgPtrs.push_back(&LocalOffset1);
ArgSizes.push_back(sizeof(uint32_t));
// [3] buf_acc: buffer accessor. Buffers are not supported in
// liboffload. The language runtimes can use USM memory instead.
void *BufPtr = /* usm pointer obtained from olMemAlloc */
ArgPtrs.push_back(&BufPtr);
ArgSizes.push_back(sizeof(void *));
// [4] buffer accessor metadata, passed by value.
size_t buf_accessor_md = 0;
ArgPtrs.push_back(&buf_accessor_md);
ArgSizes.push_back(sizeof(size_t));
// [5] usm_ptr: USM pointer argument.
void *UsmPtr = /* usm pointer obtained from olMemAlloc */
ArgPtrs.push_back(&UsmPtr);
ArgSizes.push_back(sizeof(void *));
// All argument kinds are ultimately just pointers to values,
// including images and samplers.
// [6] img_acc: Images can be opaque handles in
// liboffload. This API doesn't exist yet.
ol_image_handle_t Image = olCreateImage(...);
ArgPtrs.push_back(olImageGetArgPtr(Image));
ArgSizes.push_back(olImageGetArgSize(Image));
// [7] sampler: Samplers can be opaque handles in liboffload.
// This API doesn't exist yet.
ol_sampler_handle_t Sampler = olCreateSampler(...);
ArgPtrs.push_back(olSamplerGetArgPtr(Sampler));
// Sampler size can be different depending on the platform
ArgSizes.push_back(olSamplerGetArgSize(Sampler));
olLaunchKernelWithPtrArgs(Queue, Device, Kernel, ArgPtrs.data(),
ArgSizes.data(), &LaunchArgs);
```
This API provides flexibility and target independence, while allowing efficient kernel dispatch from all backends we expect to support.
>From 95dfaea1a442a43cde39ef4cc0e2dc39307daba4 Mon Sep 17 00:00:00 2001
From: Piotr Balcer <piotr.balcer at intel.com>
Date: Mon, 20 Apr 2026 09:41:23 +0000
Subject: [PATCH] [offload] Add olLaunchKernelWithPtrArgs with an argument
pointer array
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
The existing olLaunchKernel function accepts arguments through a single
contiguous packaged buffer, with an unspecified, implementation-defined,
layout. In practice, the existing AMDGPU and CUDA backend plugins require
the layout to follow C/C++ ABI rules.
This makes for a simple API when the arguments are already packaged in
an existing structure:
```
struct {
char A;
int *B;
short C;
} Args{0, nullptr, 0};
olLaunchKernel(Queue, Device, Kernel, &Args, sizeof(Args), &LaunchArgs);
```
In practice, this has a number of hard to workaround downsides.
# Limitations of the buffer-based API
## Runtime argument buffer construction
The example above shows the simplest scenario, where the olLaunchKernel
function is invoked directly by a program. In practice, a language
runtime that uses liboffload may need to construct the argument buffer
at runtime. This may involve allocating a variably-sized buffer and
populating it correctly, accounting for alignment and padding,
with user-provided arguments.
Constructing such a buffer may be non-trivial, or even impossible,
in scenarios where the language runtime doesn't have full argument
metadata containing size or alignment information about arguments.
In addition to the above issue, constructing such a buffer, at runtime
during kernel launch, adds an otherwise avoidable host copy before the
plugin's, or driver's, own copy. Each existing (AMDGPU/HSA, CUDA, Level-Zero)
and anticipated (OpenCL) backend already needs to create its own
GPU-accessible copy of the kernel argument buffer, extending its lifetime
past the kernel launch function.
## Unspecified argument buffer ABI
Another issue with an argument buffer is that its layout is currently
implementation-defined. While they may be compatible in practice,
relying on C/C++ ABI rules, the AMDGPU kernarg and NVPTX .param are
two distinct ABIs.
Allowing the layout to be implementation-defined may require the caller
to construct the buffer differently based on the underlying backend.
In most scenarios, liboffload users should not need to be aware of the
choice of the backend, instead relying on the provided abstractions.
Similarily, the compiler can't optimize code that produces the buffer
if the layout can't be determined at compile-time.
A target independent API accepting a buffer would have to define its own
layout compatible with, or at least convertable to, all existing
and future backends. Documenting the layout format would be a non-trivial
endeavour, likely involving collaboration with various other entities,
such as the Khronos Group, if we wanted for that layout to be natively
supported by all the backends.
## Non-straightforward backend implementations
The only two backends that can natively implement the existing method of
passing arguments are CUDA and AMDGPU. For OpenCL and Level-Zero, the
plugins would need to internally translate the contiguous buffer into
either calls to clSetKernelArg / zeKernelSetArgumentValue or, in the case
of Level Zero, an array of pointers to arguments, for use in
zeCommandListAppendLaunchKernelWithArguments
(https://oneapi-src.github.io/level-zero-spec/level-zero/latest/core/api.html#zecommandlistappendlaunchkernelwitharguments).
Doing this translation is non-trivial, since it requires the knowledge
of size and alignment of arguments within the buffer. Information which
is not provided through the olLaunchKernel API. There's currently no API in
Level-Zero or OpenCL that can be reliably used to retrieve argument
metadata from a program. Previously, we've attempted to solve this
by adding explicit argument metadata to olLaunchKernel:
```
struct {
char A;
int *B;
short C;
} Args{0, nullptr, 0};
uint64_t ArgSizes[] = {sizeof(char), sizeof(int *), sizeof(short)};
ol_kernel_launch_prop_t Props[] = {
{OL_KERNEL_LAUNCH_PROP_TYPE_SIZE, ArgSizes},
OL_KERNEL_LAUNCH_PROP_END
};
olLaunchKernel(Queue, Device, Kernel, &Args, sizeof(Args), …, Props);
```
This makes the API harder to use, and, most importantly, is
insufficient if we want the API to be target independent. The API above,
with just an array of sizes for each argument, does not allow the plugin
to account for padding inside of the buffer. OpenCL and Level-Zero plugins
would need to see a tightly-packed buffer, while CUDA and AMDGPU plugins need
a C/C++ ABI-padded one.
## Difficulty of extracting kernel argument metadata from programs
One solution to retrieving kernel argument metadata could be to read
them from the program image. This is similar to how the AMDGPU plugin
already reads general kernel metadata (readAMDGPUMetaDataFromImage).
However, this would require that the program image format accepted by
liboffload is formalized, and that the OpenCL and Level-Zero plugins
parse and read that format to extract the required metadata. While for
many initial use cases, it may be enough to define the program image
format to be SPIR-V for Level-Zero and OpenCL, it would not allow us to
support creating programs from an existing implementation-specific binary.
Such functionality will be required to support some SYCL features,
such as kernel module interop (where the kernel is created from
an existing backend binary), runtime compilation, and kernel caching.
The equivalent OpenCL API is clCreateProgramWithBinary, where the
documentation states the following:
> The program binary can consist of either or both:
> - Device-specific code and/or,
> - Implementation-specific intermediate representation (IR) which
> will be converted to the device-specific code.
https://registry.khronos.org/OpenCL/sdk/3.0/docs/man/html/clCreateProgramWithBinary.html
Extracting kernel argument metadata from such binaries would require
the generic OpenCL backend to parse vendor-specific binary formats,
one per implementation it intends to support.
# Proposed Solution: Pointer-Based Kernel Argument Passing
This PR adds a new launch kernel API, olLaunchKernelWithPtrArgs, that
accepts an array of pointers to arguments:
```
void *ArgPtrs[] = {&A, &B, &C};
size_t ArgSizes[] = {sizeof(A), sizeof(B), sizeof(C)};
olLaunchKernelWithPtrArgs(Queue, Device, Kernel, ArgPtrs, ArgSizes, &LaunchArgs);
```
However, our strong preference would be to change the existing olLaunchKernel
API to accept an array of argument pointers, leaving this as the only
method of kernel dispatch. Otherwise, the API with a packaged buffer will remain unimplementable or non-portable for some backends, including OpenCL and Level Zero.
The newly proposed interface is implementable by existing and anticipated
backends, is familiar to CUDA programmers, eliminates the extraneous
construction of a contiguous arguments buffer, replacing it with constructing
an array of pointers, sidesteps the alignment requirements, does not
require reading program image metadata where it's impractical, and enables
a compliant SYCL implementation to be built on top of it.
The ArgSizes array is required to support OpenCL, which does not have
native support for launching a kernel with an argument pointer array, or
a reliable way of retrieving argument sizes for a kernel.
## Mapping the proposed API to backends
CUDA and Level-Zero both support accepting an array of pointers to
kernel arguments, through `cuLaunchKernel`
(https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EXEC.html#group__CUDA__EXEC_1gb8f3dc3031b40da29d5f9a7139e52e15)
and `zeCommandListAppendLaunchKernelWithArguments`
(https://oneapi-src.github.io/level-zero-spec/level-zero/latest/core/api.html#zecommandlistappendlaunchkernelwitharguments)
respectively.
For OpenCL, which requires the kernel arguments to be set separately
from the kernel launch, a potential implementation can extract the
number of arguments from the OpenCL API, and then iterate over the
argument pointer and size arrays:
```
cl_uint num_args = 0;
cl_int err = clGetKernelInfo(kernel, CL_KERNEL_NUM_ARGS,
sizeof(num_args), &num_args, NULL);
for (cl_uint i = 0; i < num_args; ++i) {
clSetKernelArg(kernel, i, ArgSizes[i], ArgPtrs[i]);
}
```
The AMDGPU plugin needs to construct a contiguous buffer using the array
of argument pointers. To do this conversion, we need to have offsets
at which to place the arguments. Here, luckily, as mentioned before,
the AMD plugin already reads kernel metadata from the program image.
The implementation simply retrieves size and offset for each argument
from the kernel image, and then uses it to populate a buffer.
## Supporting SYCL with the proposed API
SYCL 2020, and Intel's intel/llvm SYCL implementation, uses 6
fundamental kinds of arguments:
1. USM pointers
2. Buffers
3. Images
4. Samplers
5. Values
6. Local Arguments
Which map to 5 kinds of arguments in Unified Runtime:
```
typedef enum ur_exp_kernel_arg_type_t {
UR_EXP_KERNEL_ARG_TYPE_VALUE = 0,
UR_EXP_KERNEL_ARG_TYPE_POINTER = 1,
UR_EXP_KERNEL_ARG_TYPE_MEM_OBJ = 2,
UR_EXP_KERNEL_ARG_TYPE_LOCAL = 3,
UR_EXP_KERNEL_ARG_TYPE_SAMPLER = 4,
...
} ur_exp_kernel_arg_type_t;
```
The following SYCL 2020 program demonstrates their use:
```
#include <sycl/sycl.hpp>
#include <cstdio>
#include <cstdlib>
int main() {
sycl::queue q;
int *usm_ptr = sycl::malloc_host<int>(1, q);
*usm_ptr = -1;
int host_data[1] = {5};
sycl::buffer<int, 1> buf(host_data, sycl::range<1>(1));
sycl::image<2> img(sycl::image_channel_order::rgba,
sycl::image_channel_type::fp32,
sycl::range<2>(4, 4));
sycl::sampler samp(
sycl::coordinate_normalization_mode::unnormalized,
sycl::addressing_mode::clamp,
sycl::filtering_mode::nearest);
int val = 42;
q.submit([&](sycl::handler &h) {
auto buf_acc =
buf.get_access<sycl::access::mode::read_write>(h);
auto img_acc =
img.get_access<sycl::float4,
sycl::access::mode::read>(h);
sycl::local_accessor<int, 1> local_mem(
sycl::range<1>(64), h);
sycl::local_accessor<int, 1> local_mem2(
sycl::range<1>(64), h);
h.parallel_for(sycl::nd_range<1>(1, 1),
[=](sycl::nd_item<1> item) {
local_mem[0] = val;
local_mem2[0] = val + 1;
buf_acc[0] = buf_acc[0] + local_mem[0] + local_mem2[0];
usm_ptr[0] = buf_acc[0];
// just to keep the args
(void)img_acc;
(void)samp;
});
});
q.wait();
int expected = 5 + 42 + 43;
printf("usm_ptr[0] = %d (expected %d)\n", *usm_ptr, expected);
sycl::free(usm_ptr, q);
return 0;
}
```
The kernel launch uses the following UR call (simplified for
legibility):
```
urEnqueueKernelLaunchWithArgsExp(
.hQueue = 0xca2f090,
.hKernel = 0xc7640f0,
.workDim = 1,
.pGlobalWorkOffset = nullptr,
.pGlobalWorkSize = 0xc6e1c38 (1),
.pLocalWorkSize = 0xc6e1c50 (1),
.numArgs = 8,
.pArgs = 0xc754710 {
{.type = UR_EXP_KERNEL_ARG_TYPE_LOCAL, .index = 0, .size = 256,
.value = (union ur_exp_kernel_arg_value_t){<unknown>}},
{.type = UR_EXP_KERNEL_ARG_TYPE_VALUE, .index = 1, .size = 4,
.value = (union ur_exp_kernel_arg_value_t){.value = 0xc6e23e8}},
{.type = UR_EXP_KERNEL_ARG_TYPE_LOCAL, .index = 2, .size = 256,
.value = (union ur_exp_kernel_arg_value_t){<unknown>}},
{.type = UR_EXP_KERNEL_ARG_TYPE_MEM_OBJ, .index = 3, .size = 8,
.value = (union ur_exp_kernel_arg_value_t){
.memObjTuple = (struct ur_exp_kernel_arg_mem_obj_tuple_t){
.hMem = 0xc6e60f0, .flags = UR_MEM_FLAG_READ_WRITE}}},
{.type = UR_EXP_KERNEL_ARG_TYPE_VALUE, .index = 4, .size = 8,
.value = (union ur_exp_kernel_arg_value_t){.value = 0xc6966f0}},
{.type = UR_EXP_KERNEL_ARG_TYPE_POINTER, .index = 5, .size = 8,
.value = (union ur_exp_kernel_arg_value_t){.pointer = ...}},
{.type = UR_EXP_KERNEL_ARG_TYPE_MEM_OBJ, .index = 6, .size = 8,
.value = (union ur_exp_kernel_arg_value_t){
.memObjTuple = (struct ur_exp_kernel_arg_mem_obj_tuple_t){
.hMem = 0xc6ebac0, .flags = UR_MEM_FLAG_READ_ONLY}}},
{.type = UR_EXP_KERNEL_ARG_TYPE_SAMPLER, .index = 7, .size = 8,
.value = (union ur_exp_kernel_arg_value_t){.sampler = 0xca50750}}
},
...
) -> UR_RESULT_SUCCESS;
```
In order to support a compliant SYCL 2020 specification, liboffload
launch kernel API needs to be able to support all these kinds of
arguments. The proposed API makes this straightforward. To launch the
kernel above, the language runtime could use the liboffload API in the
following way:
```
ol_kernel_launch_size_args_t LaunchArgs;
LaunchArgs.Dimensions = 1;
LaunchArgs.GroupSize = {1, 1, 1};
LaunchArgs.NumGroups = {1, 1, 1};
// CUDA, HSA, Level Zero, and OpenCL have a differing model of
// shared / local memory. The lowest common denominator is setting
// only a single shared memory block to contain all memory required
// by SYCL's local accessors, with the language runtime additionally
// setting offsets into that block as value arguments.
// Level Zero doesn't currently implement this feature.
// The SPIR-V kernel is expected to declare a single SLM argument
// at the last position when this field is set.
LaunchArgs.DynSharedMemory = 512;
SmallVector<void *, 8> ArgPtrs;
SmallVector<size_t, 8> ArgSizes;
// [0] local_mem: first local accessor, offset 0 into the shared
// memory block.
uint32_t LocalOffset0 = 0;
ArgPtrs.push_back(&LocalOffset0);
ArgSizes.push_back(sizeof(uint32_t));
// [1] val: plain value argument (int val = 42).
int Val = 42;
ArgPtrs.push_back(&Val);
ArgSizes.push_back(sizeof(int));
// [2] local_mem2: second local accessor, offset 256 into the shared
// memory block.
uint32_t LocalOffset1 = 256;
ArgPtrs.push_back(&LocalOffset1);
ArgSizes.push_back(sizeof(uint32_t));
// [3] buf_acc: buffer accessor. Buffers are not supported in
// liboffload. The language runtimes can use USM memory instead.
void *BufPtr = /* usm pointer obtained from olMemAlloc */
ArgPtrs.push_back(&BufPtr);
ArgSizes.push_back(sizeof(void *));
// [4] buffer accessor metadata, passed by value.
size_t buf_accessor_md = 0;
ArgPtrs.push_back(&buf_accessor_md);
ArgSizes.push_back(sizeof(size_t));
// [5] usm_ptr: USM pointer argument.
void *UsmPtr = /* usm pointer obtained from olMemAlloc */
ArgPtrs.push_back(&UsmPtr);
ArgSizes.push_back(sizeof(void *));
// All argument kinds are ultimately just pointers to values,
// including images and samplers.
// [6] img_acc: Images can be opaque handles in
// liboffload. This API doesn't exist yet.
ol_image_handle_t Image = olCreateImage(...);
ArgPtrs.push_back(olImageGetArgPtr(Image));
ArgSizes.push_back(olImageGetArgSize(Image));
// [7] sampler: Samplers can be opaque handles in liboffload.
// This API doesn't exist yet.
ol_sampler_handle_t Sampler = olCreateSampler(...);
ArgPtrs.push_back(olSamplerGetArgPtr(Sampler));
// Sampler size can be different depending on the platform
ArgSizes.push_back(olSamplerGetArgSize(Sampler));
olLaunchKernelWithPtrArgs(Queue, Device, Kernel, ArgPtrs.data(),
ArgSizes.data(), &LaunchArgs);
```
This API provides flexibility and target independence, while allowing
efficient kernel dispatch from all backends we expect to support.
---
.../llvm/Frontend/Offloading/Utility.h | 14 ++
llvm/lib/Frontend/Offloading/Utility.cpp | 32 +++
offload/include/Shared/APITypes.h | 5 +-
offload/liboffload/API/Kernel.td | 23 ++
offload/liboffload/src/OffloadImpl.cpp | 49 ++--
offload/plugins-nextgen/amdgpu/src/rtl.cpp | 27 ++-
.../common/src/PluginInterface.cpp | 7 +-
offload/plugins-nextgen/cuda/src/rtl.cpp | 19 +-
.../level_zero/dynamic_l0/L0DynWrapper.cpp | 1 +
.../level_zero/dynamic_l0/level_zero/ze_api.h | 12 +
.../level_zero/src/L0Kernel.cpp | 107 ++++++---
offload/unittests/OffloadAPI/CMakeLists.txt | 3 +-
.../OffloadAPI/device_code/multiargs.cpp | 4 +-
.../OffloadAPI/kernel/olLaunchKernel.cpp | 12 +-
.../kernel/olLaunchKernelWithPtrArgs.cpp | 217 ++++++++++++++++++
15 files changed, 468 insertions(+), 64 deletions(-)
create mode 100644 offload/unittests/OffloadAPI/kernel/olLaunchKernelWithPtrArgs.cpp
diff --git a/llvm/include/llvm/Frontend/Offloading/Utility.h b/llvm/include/llvm/Frontend/Offloading/Utility.h
index eb08e7ec661e4..366c4665ea7dc 100644
--- a/llvm/include/llvm/Frontend/Offloading/Utility.h
+++ b/llvm/include/llvm/Frontend/Offloading/Utility.h
@@ -13,6 +13,7 @@
#include <cstdint>
#include <memory>
+#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/Module.h"
@@ -115,6 +116,16 @@ namespace amdgpu {
LLVM_ABI bool isImageCompatibleWithEnv(StringRef ImageArch, uint32_t ImageFlags,
StringRef EnvTargetID);
+/// Struct for holding AMDGPU Kernel Argument Metadata, see:
+/// https://llvm.org/docs/AMDGPUUsage.html#amdgpu-amdhsa-code-object-kernel-argument-metadata-map-table-v3
+struct AMDGPUKernelArgMetaData {
+ /// Kernel argument offset in bytes. The offset must be a multiple
+ /// of the alignment required by the argument.
+ uint32_t Offset = 0;
+ /// Kernel argument size in bytes.
+ uint32_t Size = 0;
+};
+
/// Struct for holding metadata related to AMDGPU kernels, for more information
/// about the metadata and its meaning see:
/// https://llvm.org/docs/AMDGPUUsage.html#code-object-v3
@@ -148,6 +159,9 @@ struct AMDGPUKernelMetaData {
uint32_t WavefrontSize = KInvalidValue;
/// Maximum flat work-group size supported by the kernel in work-items.
uint32_t MaxFlatWorkgroupSize = KInvalidValue;
+ /// Per-argument offset and size, read from the ".args" array in code object
+ /// metadata. Includes only explicit user arguments.
+ SmallVector<AMDGPUKernelArgMetaData, 8> ExplicitArgMDs;
};
/// Reads AMDGPU specific metadata from the ELF file and propagates the
diff --git a/llvm/lib/Frontend/Offloading/Utility.cpp b/llvm/lib/Frontend/Offloading/Utility.cpp
index 44cef91bac495..5d9b26a574aee 100644
--- a/llvm/lib/Frontend/Offloading/Utility.cpp
+++ b/llvm/lib/Frontend/Offloading/Utility.cpp
@@ -286,6 +286,38 @@ class KernelInfoReader {
KernelData.WavefrontSize = V.second.getUInt();
} else if (IsKey(V.first, ".max_flat_workgroup_size")) {
KernelData.MaxFlatWorkgroupSize = V.second.getUInt();
+ } else if (IsKey(V.first, ".args")) {
+ auto ArgsArray = V.second.getArray();
+ for (auto ArgIt = ArgsArray.begin(), ArgEnd = ArgsArray.end();
+ ArgIt != ArgEnd; ++ArgIt) {
+ auto ArgMap = ArgIt->getMap();
+
+ // Skip hidden arguments
+ auto VKIt = ArgMap.find(".value_kind");
+ if (VKIt != ArgMap.end() &&
+ VKIt->second.getString().starts_with("hidden_"))
+ continue;
+
+ auto OffsetIt = ArgMap.find(".offset");
+ // TODO: should these be asserts?
+ // if .offset or .size isn't found, that means the kernel
+ // is malformed.
+ if (OffsetIt == ArgMap.end())
+ return createStringError(
+ inconvertibleErrorCode(),
+ "Missing required .offset key in kernel argument metadata map");
+ auto SizeIt = ArgMap.find(".size");
+ if (SizeIt == ArgMap.end())
+ return createStringError(
+ inconvertibleErrorCode(),
+ "Missing required .size key in kernel argument metadata map");
+
+ amdgpu::AMDGPUKernelArgMetaData ArgMD;
+ ArgMD.Offset = OffsetIt->second.getUInt();
+ ArgMD.Size = SizeIt->second.getUInt();
+
+ KernelData.ExplicitArgMDs.push_back(ArgMD);
+ }
}
return Error::success();
diff --git a/offload/include/Shared/APITypes.h b/offload/include/Shared/APITypes.h
index 40824596c3b9b..3dd046ec5bf7d 100644
--- a/offload/include/Shared/APITypes.h
+++ b/offload/include/Shared/APITypes.h
@@ -104,8 +104,9 @@ struct KernelArgsTy {
uint64_t NoWait : 1; // Was this kernel spawned with a `nowait` clause.
uint64_t IsCUDA : 1; // Was this kernel spawned via CUDA.
uint64_t DynCGroupMemFallback : 2; // The fallback for dynamic cgroup mem.
- uint64_t Unused : 60;
- } Flags = {0, 0, 0, 0};
+ uint64_t IsPtrArgs : 1; // Arguments are laid out as an array of pointers.
+ uint64_t Unused : 59;
+ } Flags = {0, 0, 0, 0, 0};
// The number of teams (for x,y,z dimension).
uint32_t NumTeams[3] = {0, 0, 0};
// The number of threads (for x,y,z dimension).
diff --git a/offload/liboffload/API/Kernel.td b/offload/liboffload/API/Kernel.td
index 2f5692a19d712..e813e28a089f6 100644
--- a/offload/liboffload/API/Kernel.td
+++ b/offload/liboffload/API/Kernel.td
@@ -41,6 +41,29 @@ def olLaunchKernel : Function {
];
}
+def olLaunchKernelWithPtrArgs : Function {
+ let desc = "Enqueue a kernel launch with arguments specified as an array of pointers and sizes.";
+ let details = [
+ "If a queue is not specified, kernel execution happens synchronously",
+ "Each element of ArgPtrs points to the value of the corresponding kernel argument",
+ "Each element of ArgSizes specifies the size in bytes of the corresponding argument",
+ "ArgPtrs and ArgSizes must both be NULL (no arguments) or both be non-NULL"
+ ];
+ let params = [
+ Param<"ol_queue_handle_t", "Queue", "handle of the queue", PARAM_IN_OPTIONAL>,
+ Param<"ol_device_handle_t", "Device", "handle of the device to execute on", PARAM_IN>,
+ Param<"ol_symbol_handle_t", "Kernel", "handle of the kernel", PARAM_IN>,
+ Param<"void**", "ArgPtrs", "array of pointers, each pointing to an argument value", PARAM_IN_OPTIONAL>,
+ Param<"const size_t*", "ArgSizes", "array of argument sizes", PARAM_IN_OPTIONAL>,
+ Param<"const ol_kernel_launch_size_args_t*", "LaunchSizeArgs", "pointer to the struct containing launch size parameters", PARAM_IN>,
+ ];
+ let returns = [
+ Return<"OL_ERRC_INVALID_ARGUMENT", ["`(ArgPtrs == NULL) != (ArgSizes == NULL)`"]>,
+ Return<"OL_ERRC_INVALID_DEVICE", ["If Queue is non-null but does not belong to Device"]>,
+ Return<"OL_ERRC_SYMBOL_KIND", ["The provided symbol is not a kernel"]>,
+ ];
+}
+
def olCalculateOptimalOccupancy : Function {
let desc = "Given dynamic memory size, query the device for a workgroup size that will result in optimal occupancy.";
let details = [
diff --git a/offload/liboffload/src/OffloadImpl.cpp b/offload/liboffload/src/OffloadImpl.cpp
index 314788794842d..7f81073bde2be 100644
--- a/offload/liboffload/src/OffloadImpl.cpp
+++ b/offload/liboffload/src/OffloadImpl.cpp
@@ -1052,10 +1052,11 @@ Error olCalculateOptimalOccupancy_impl(ol_device_handle_t Device,
return Error::success();
}
-Error olLaunchKernel_impl(ol_queue_handle_t Queue, ol_device_handle_t Device,
- ol_symbol_handle_t Kernel, const void *ArgumentsData,
- size_t ArgumentsSize,
- const ol_kernel_launch_size_args_t *LaunchSizeArgs) {
+static Error
+launchKernelCommon(ol_queue_handle_t Queue, ol_device_handle_t Device,
+ ol_symbol_handle_t Kernel,
+ const ol_kernel_launch_size_args_t *LaunchSizeArgs,
+ KernelArgsTy &LaunchArgs) {
auto *DeviceImpl = Device->Device;
if (Queue && Device != Queue->Device) {
return createOffloadError(
@@ -1067,9 +1068,6 @@ Error olLaunchKernel_impl(ol_queue_handle_t Queue, ol_device_handle_t Device,
return createOffloadError(ErrorCode::SYMBOL_KIND,
"provided symbol is not a kernel");
- auto *QueueImpl = Queue ? Queue->AsyncInfo : nullptr;
- AsyncInfoWrapperTy AsyncInfoWrapper(*DeviceImpl, QueueImpl);
- KernelArgsTy LaunchArgs{};
LaunchArgs.NumTeams[0] = LaunchSizeArgs->NumGroups.x;
LaunchArgs.NumTeams[1] = LaunchSizeArgs->NumGroups.y;
LaunchArgs.NumTeams[2] = LaunchSizeArgs->NumGroups.z;
@@ -1078,12 +1076,8 @@ Error olLaunchKernel_impl(ol_queue_handle_t Queue, ol_device_handle_t Device,
LaunchArgs.ThreadLimit[2] = LaunchSizeArgs->GroupSize.z;
LaunchArgs.DynCGroupMem = LaunchSizeArgs->DynSharedMemory;
- KernelLaunchParamsTy Params;
- Params.Data = const_cast<void *>(ArgumentsData);
- Params.Size = ArgumentsSize;
- LaunchArgs.ArgPtrs = reinterpret_cast<void **>(&Params);
- // Don't do anything with pointer indirection; use arg data as-is
- LaunchArgs.Flags.IsCUDA = true;
+ auto *QueueImpl = Queue ? Queue->AsyncInfo : nullptr;
+ AsyncInfoWrapperTy AsyncInfoWrapper(*DeviceImpl, QueueImpl);
auto *KernelImpl = std::get<GenericKernelTy *>(Kernel->PluginImpl);
auto Err = KernelImpl->launch(*DeviceImpl, LaunchArgs.ArgPtrs, nullptr,
@@ -1096,6 +1090,35 @@ Error olLaunchKernel_impl(ol_queue_handle_t Queue, ol_device_handle_t Device,
return Error::success();
}
+Error olLaunchKernel_impl(ol_queue_handle_t Queue, ol_device_handle_t Device,
+ ol_symbol_handle_t Kernel, const void *ArgumentsData,
+ size_t ArgumentsSize,
+ const ol_kernel_launch_size_args_t *LaunchSizeArgs) {
+ KernelArgsTy LaunchArgs{};
+ KernelLaunchParamsTy Params;
+ Params.Data = const_cast<void *>(ArgumentsData);
+ Params.Size = ArgumentsSize;
+ LaunchArgs.ArgPtrs = reinterpret_cast<void **>(&Params);
+ // Don't do anything with pointer indirection; use arg data as-is
+ LaunchArgs.Flags.IsCUDA = true;
+
+ return launchKernelCommon(Queue, Device, Kernel, LaunchSizeArgs, LaunchArgs);
+}
+
+Error olLaunchKernelWithPtrArgs_impl(
+ ol_queue_handle_t Queue, ol_device_handle_t Device,
+ ol_symbol_handle_t Kernel, void **ArgPtrs, const size_t *ArgSizes,
+ const ol_kernel_launch_size_args_t *LaunchSizeArgs) {
+ KernelArgsTy LaunchArgs{};
+ LaunchArgs.ArgPtrs = ArgPtrs;
+ // TODO: Either change ArgSizes to const size_t * or add a new variable.
+ LaunchArgs.ArgSizes =
+ reinterpret_cast<int64_t *>(const_cast<size_t *>(ArgSizes));
+ LaunchArgs.Flags.IsPtrArgs = 1;
+
+ return launchKernelCommon(Queue, Device, Kernel, LaunchSizeArgs, LaunchArgs);
+}
+
Error olGetSymbol_impl(ol_program_handle_t Program, const char *Name,
ol_symbol_kind_t Kind, ol_symbol_handle_t *Symbol) {
auto &Device = Program->Image->getDevice();
diff --git a/offload/plugins-nextgen/amdgpu/src/rtl.cpp b/offload/plugins-nextgen/amdgpu/src/rtl.cpp
index e608c5d6ce666..a5b0b5ffef558 100644
--- a/offload/plugins-nextgen/amdgpu/src/rtl.cpp
+++ b/offload/plugins-nextgen/amdgpu/src/rtl.cpp
@@ -4130,11 +4130,24 @@ Error AMDGPUKernelTy::launchImpl(GenericDeviceTy &GenericDevice,
if (auto Err = GenericDevice.getDeviceStackSize(StackSize))
return Err;
- // Copy the explicit arguments.
- // TODO: We should expose the args memory manager alloc to the common part as
- // alternative to copying them twice.
- if (LaunchParams.Size)
- std::memcpy(AllArgs, LaunchParams.Data, LaunchParams.Size);
+ // Copy explicit arguments.
+ size_t ExplicitEnd = 0;
+ if (KernelArgs.Flags.IsPtrArgs) {
+ if (KernelArgs.ArgPtrs) { // may be null
+ const auto &ArgMDs = KernelInfo->ExplicitArgMDs;
+ for (size_t I = 0; I < ArgMDs.size(); I++)
+ std::memcpy(utils::advancePtr(AllArgs, ArgMDs[I].Offset),
+ KernelArgs.ArgPtrs[I], ArgMDs[I].Size);
+
+ ExplicitEnd = ArgMDs.back().Offset + ArgMDs.back().Size;
+ }
+ } else {
+ // TODO: We should expose the args memory manager alloc to the common part
+ // as alternative to copying them twice.
+ if (LaunchParams.Size)
+ std::memcpy(AllArgs, LaunchParams.Data, LaunchParams.Size);
+ ExplicitEnd = LaunchParams.Size;
+ }
AMDGPUDeviceTy &AMDGPUDevice = static_cast<AMDGPUDeviceTy &>(GenericDevice);
@@ -4142,8 +4155,8 @@ Error AMDGPUKernelTy::launchImpl(GenericDeviceTy &GenericDevice,
if (auto Err = AMDGPUDevice.getStream(AsyncInfoWrapper, Stream))
return Err;
- uint64_t ImplArgsOffset = utils::roundUp(
- LaunchParams.Size, alignof(hsa_utils::AMDGPUImplicitArgsTy));
+ uint64_t ImplArgsOffset =
+ utils::roundUp(ExplicitEnd, alignof(hsa_utils::AMDGPUImplicitArgsTy));
if (ArgsSize > ImplArgsOffset) {
hsa_utils::AMDGPUImplicitArgsTy *ImplArgs =
reinterpret_cast<hsa_utils::AMDGPUImplicitArgsTy *>(
diff --git a/offload/plugins-nextgen/common/src/PluginInterface.cpp b/offload/plugins-nextgen/common/src/PluginInterface.cpp
index c09b69cd46ba8..9d20b85cb8426 100644
--- a/offload/plugins-nextgen/common/src/PluginInterface.cpp
+++ b/offload/plugins-nextgen/common/src/PluginInterface.cpp
@@ -269,13 +269,14 @@ Error GenericKernelTy::launch(GenericDeviceTy &GenericDevice, void **ArgPtrs,
if (!KernelLaunchEnvOrErr)
return KernelLaunchEnvOrErr.takeError();
- KernelLaunchParamsTy LaunchParams;
-
// Kernel languages don't use indirection.
+ // IsPtrArgs bypasses LaunchParms entirely,
+ // plugins read KernelArgs.ArgPtrs/ArgSizes directly.
+ KernelLaunchParamsTy LaunchParams;
if (KernelArgs.Flags.IsCUDA) {
LaunchParams =
*reinterpret_cast<KernelLaunchParamsTy *>(KernelArgs.ArgPtrs);
- } else {
+ } else if (!KernelArgs.Flags.IsPtrArgs) {
LaunchParams =
prepareArgs(GenericDevice, ArgPtrs, ArgOffsets, KernelArgs.NumArgs,
Args, Ptrs, *KernelLaunchEnvOrErr, KernelArgs.Version);
diff --git a/offload/plugins-nextgen/cuda/src/rtl.cpp b/offload/plugins-nextgen/cuda/src/rtl.cpp
index 8a7c8a4ffd42d..1dc9bc9348a53 100644
--- a/offload/plugins-nextgen/cuda/src/rtl.cpp
+++ b/offload/plugins-nextgen/cuda/src/rtl.cpp
@@ -1436,17 +1436,23 @@ Error CUDAKernelTy::launchImpl(GenericDeviceTy &GenericDevice,
AsyncInfoWrapperTy &AsyncInfoWrapper) const {
CUDADeviceTy &CUDADevice = static_cast<CUDADeviceTy &>(GenericDevice);
- // The args size passed in LaunchParams may have tail padding, which is not
- // accepted by the CUDA driver.
- if (ArgsSize > LaunchParams.Size)
- return Plugin::error(ErrorCode::INVALID_ARGUMENT,
- "mismatch in kernel arguments");
+ void **KernelParams = nullptr;
+ if (KernelArgs.Flags.IsPtrArgs) {
+ KernelParams = KernelArgs.ArgPtrs;
+ } else {
+ // The args size passed in LaunchParams may have tail padding,
+ // which is not accepted by the CUDA driver.
+ if (ArgsSize > LaunchParams.Size)
+ return Plugin::error(ErrorCode::INVALID_ARGUMENT,
+ "mismatch in kernel arguments");
+ }
CUstream Stream;
if (auto Err = CUDADevice.getStream(AsyncInfoWrapper, Stream))
return Err;
size_t ConfigArgsSize = ArgsSize;
+ // valid for buffer passed through LaunchParams
void *Config[] = {CU_LAUNCH_PARAM_BUFFER_POINTER, LaunchParams.Data,
CU_LAUNCH_PARAM_BUFFER_SIZE,
reinterpret_cast<void *>(&ConfigArgsSize),
@@ -1470,7 +1476,8 @@ Error CUDAKernelTy::launchImpl(GenericDeviceTy &GenericDevice,
CUresult Res = cuLaunchKernel(Func, NumBlocks[0], NumBlocks[1], NumBlocks[2],
NumThreads[0], NumThreads[1], NumThreads[2],
- DynBlockMemSize, Stream, nullptr, Config);
+ DynBlockMemSize, Stream, KernelParams,
+ KernelParams ? nullptr : Config);
// Register a callback to indicate when the kernel is complete.
if (GenericDevice.getRPCServer())
diff --git a/offload/plugins-nextgen/level_zero/dynamic_l0/L0DynWrapper.cpp b/offload/plugins-nextgen/level_zero/dynamic_l0/L0DynWrapper.cpp
index e68bddd0047a1..3adfb59ef710a 100644
--- a/offload/plugins-nextgen/level_zero/dynamic_l0/L0DynWrapper.cpp
+++ b/offload/plugins-nextgen/level_zero/dynamic_l0/L0DynWrapper.cpp
@@ -29,6 +29,7 @@ DLWRAP(zeModuleDestroy, 1)
DLWRAP(zeCommandListAppendBarrier, 4)
DLWRAP(zeCommandListAppendLaunchKernel, 6)
DLWRAP(zeCommandListAppendLaunchCooperativeKernel, 6)
+DLWRAP(zeCommandListAppendLaunchKernelWithArguments, 9)
DLWRAP(zeCommandListAppendMemoryCopy, 7)
DLWRAP(zeCommandListAppendMemoryCopyRegion, 12)
DLWRAP(zeCommandListAppendMemoryFill, 8)
diff --git a/offload/plugins-nextgen/level_zero/dynamic_l0/level_zero/ze_api.h b/offload/plugins-nextgen/level_zero/dynamic_l0/level_zero/ze_api.h
index 6049bd2c83ad1..5b9188a6202c5 100644
--- a/offload/plugins-nextgen/level_zero/dynamic_l0/level_zero/ze_api.h
+++ b/offload/plugins-nextgen/level_zero/dynamic_l0/level_zero/ze_api.h
@@ -441,6 +441,12 @@ typedef struct _ze_group_count_t {
uint32_t groupCountZ;
} ze_group_count_t;
+typedef struct _ze_group_size_t {
+ uint32_t groupSizeX;
+ uint32_t groupSizeY;
+ uint32_t groupSizeZ;
+} ze_group_size_t;
+
/* Memory allocation properties */
typedef struct _ze_memory_allocation_properties_t {
ze_structure_type_t stype;
@@ -680,6 +686,12 @@ ZE_APIEXPORT ze_result_t ZE_APICALL zeCommandListAppendLaunchCooperativeKernel(
ze_command_list_handle_t hCommandList, ze_kernel_handle_t hKernel,
const ze_group_count_t *pLaunchFuncArgs, ze_event_handle_t hSignalEvent,
uint32_t numWaitEvents, ze_event_handle_t *phWaitEvents);
+ZE_APIEXPORT ze_result_t ZE_APICALL
+zeCommandListAppendLaunchKernelWithArguments(
+ ze_command_list_handle_t hCommandList, ze_kernel_handle_t hKernel,
+ const ze_group_count_t groupCounts, const ze_group_size_t groupSizes,
+ void **pArguments, const void *pNext, ze_event_handle_t hSignalEvent,
+ uint32_t numWaitEvents, ze_event_handle_t *phWaitEvents);
ZE_APIEXPORT ze_result_t ZE_APICALL zeCommandListAppendMemoryCopy(
ze_command_list_handle_t hCommandList, void *dstptr, const void *srcptr,
size_t size, ze_event_handle_t hSignalEvent, uint32_t numWaitEvents,
diff --git a/offload/plugins-nextgen/level_zero/src/L0Kernel.cpp b/offload/plugins-nextgen/level_zero/src/L0Kernel.cpp
index 380d25da1c4f4..feb6a5c6dfc3c 100644
--- a/offload/plugins-nextgen/level_zero/src/L0Kernel.cpp
+++ b/offload/plugins-nextgen/level_zero/src/L0Kernel.cpp
@@ -268,10 +268,15 @@ Error L0KernelTy::getGroupsShape(L0DeviceTy &Device, int32_t NumTeams,
return Plugin::success();
}
+using AppendLaunchFnTy = llvm::function_ref<ze_result_t(
+ ze_command_list_handle_t CmdList, ze_event_handle_t Event,
+ uint32_t NumWaitEvents, ze_event_handle_t *WaitEvents)>;
+
static Error launchKernelWithImmCmdList(L0DeviceTy &l0Device,
ze_kernel_handle_t zeKernel,
L0LaunchEnvTy &KEnv,
- CommandModeTy CommandMode) {
+ CommandModeTy CommandMode,
+ AppendLaunchFnTy AppendLaunch) {
const auto DeviceId = l0Device.getDeviceId();
auto *IdStr = l0Device.getZeIdCStr();
auto CmdListOrErr = l0Device.getImmCmdList();
@@ -302,9 +307,14 @@ static Error launchKernelWithImmCmdList(L0DeviceTy &l0Device,
"Kernel depends on %zu data copying events.\n", NumWaitEvents);
Error AllErrors = Error::success();
- CALL_ZE_ACCUM_ERROR(AllErrors, zeCommandListAppendLaunchKernel, CmdList,
- zeKernel, &KEnv.GroupCounts, Event, NumWaitEvents,
- WaitEvents);
+ ze_result_t rc = AppendLaunch(CmdList, Event, NumWaitEvents, WaitEvents);
+ if (rc != ZE_RESULT_SUCCESS) {
+ AllErrors = joinErrors(std::move(AllErrors),
+ Plugin::error(ErrorCode::UNKNOWN,
+ "append launch failed with error "
+ "%d, %s",
+ rc, getZeErrorName(rc)));
+ }
KEnv.Lock.unlock();
if (AllErrors) {
if (auto Err = l0Device.releaseEvent(Event))
@@ -334,7 +344,8 @@ static Error launchKernelWithImmCmdList(L0DeviceTy &l0Device,
static Error launchKernelWithCmdQueue(L0DeviceTy &l0Device,
ze_kernel_handle_t zeKernel,
- L0LaunchEnvTy &KEnv) {
+ L0LaunchEnvTy &KEnv,
+ AppendLaunchFnTy AppendLaunch) {
const auto DeviceId = l0Device.getDeviceId();
const auto *IdStr = l0Device.getZeIdCStr();
@@ -351,8 +362,13 @@ static Error launchKernelWithCmdQueue(L0DeviceTy &l0Device,
"Using regular command list for kernel submission.\n");
ze_event_handle_t Event = nullptr;
- CALL_ZE_RET_ERROR(zeCommandListAppendLaunchKernel, CmdList, zeKernel,
- &KEnv.GroupCounts, Event, 0, nullptr);
+
+ ze_result_t rc = AppendLaunch(CmdList, Event, 0, nullptr);
+ if (rc != ZE_RESULT_SUCCESS)
+ return Plugin::error(ErrorCode::UNKNOWN,
+ "append launch failed with error %d, %s", rc,
+ getZeErrorName(rc));
+
KEnv.Lock.unlock();
CALL_ZE_RET_ERROR(zeCommandListClose, CmdList);
@@ -484,41 +500,72 @@ Error L0KernelTy::launchImpl(GenericDeviceTy &GenericDevice,
// Protect from kernel preparation to submission as kernels are shared.
KEnv.Lock.lock();
- if (auto Err = setKernelGroups(l0Device, KEnv, NumThreads, NumBlocks))
- return Err;
-
- // Set kernel arguments.
- uint32_t NumKernelArgs = KernelPR.NumKernelArgs;
- if (NumKernelArgs > 0) {
- if (!KernelPR.ArgSizes)
- return Plugin::error(ErrorCode::INVALID_ARGUMENT,
- "level zero plugin requires kernel argument sizes.");
- // Use sizes from kernel properties.
- // TODO: This is temporary workaround it will not work if there is
- // padding/alignment between arguments.
- char *Arg = static_cast<char *>(LaunchParams.Data);
- for (uint32_t I = 0; I < NumKernelArgs; I++) {
- uint32_t ArgSize = KernelPR.ArgSizes[I];
- CALL_ZE_RET_ERROR(zeKernelSetArgumentValue, zeKernel, I, ArgSize, Arg);
+ // With pointer-array arguments, zeCommandListAppendLaunchKernelWithArguments
+ // folds group-size, per-argument set, and launch into a single call.
+ const bool IsPtrArgs = KernelArgs.Flags.IsPtrArgs;
+ ze_group_count_t PtrArgsGroupCounts{};
+ ze_group_size_t PtrArgsGroupSizes{};
+ if (IsPtrArgs) {
+ PtrArgsGroupCounts = {NumBlocks[0], NumBlocks[1], NumBlocks[2]};
+ PtrArgsGroupSizes = {NumThreads[0], NumThreads[1], NumThreads[2]};
+ INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
+ "Team sizes = {%" PRIu32 ", %" PRIu32 ", %" PRIu32 "}\n",
+ PtrArgsGroupSizes.groupSizeX, PtrArgsGroupSizes.groupSizeY,
+ PtrArgsGroupSizes.groupSizeZ);
+ INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
+ "Number of teams = {%" PRIu32 ", %" PRIu32 ", %" PRIu32 "}\n",
+ PtrArgsGroupCounts.groupCountX, PtrArgsGroupCounts.groupCountY,
+ PtrArgsGroupCounts.groupCountZ);
+ } else {
+ if (auto Err = setKernelGroups(l0Device, KEnv, NumThreads, NumBlocks))
+ return Err;
- INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
- "Kernel Pointer argument %" PRIu32 " (value: " DPxMOD
- ") was set successfully for device %s.\n",
- I, DPxPTR(Arg), IdStr);
- Arg += ArgSize;
+ // Set kernel arguments.
+ uint32_t NumKernelArgs = KernelPR.NumKernelArgs;
+ if (NumKernelArgs > 0) {
+ if (!KernelPR.ArgSizes)
+ return Plugin::error(
+ ErrorCode::INVALID_ARGUMENT,
+ "level zero plugin requires kernel argument sizes.");
+ // Use sizes from kernel properties.
+ // TODO: This is temporary workaround it will not work if there is
+ // padding/alignment between arguments.
+ char *Arg = static_cast<char *>(LaunchParams.Data);
+ for (uint32_t I = 0; I < NumKernelArgs; I++) {
+ uint32_t ArgSize = KernelPR.ArgSizes[I];
+ CALL_ZE_RET_ERROR(zeKernelSetArgumentValue, zeKernel, I, ArgSize, Arg);
+
+ INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
+ "Kernel Pointer argument %" PRIu32 " (value: " DPxMOD
+ ") was set successfully for device %s.\n",
+ I, DPxPTR(Arg), IdStr);
+ Arg += ArgSize;
+ }
}
}
if (auto Err = setIndirectFlags(l0Device, KEnv))
return Err;
+ auto AppendLaunch = [&](ze_command_list_handle_t CmdList,
+ ze_event_handle_t Event, uint32_t NumWaitEvents,
+ ze_event_handle_t *WaitEvents) {
+ if (IsPtrArgs)
+ return zeCommandListAppendLaunchKernelWithArguments(
+ CmdList, zeKernel, PtrArgsGroupCounts, PtrArgsGroupSizes,
+ KernelArgs.ArgPtrs, nullptr, Event, NumWaitEvents, WaitEvents);
+
+ return zeCommandListAppendLaunchKernel(CmdList, zeKernel, &KEnv.GroupCounts,
+ Event, NumWaitEvents, WaitEvents);
+ };
+
// The next calls should unlock the KernelLock internally.
const bool UseImmCmdList = l0Device.useImmForCompute();
if (UseImmCmdList)
return launchKernelWithImmCmdList(l0Device, zeKernel, KEnv,
- Options.CommandMode);
+ Options.CommandMode, AppendLaunch);
- return launchKernelWithCmdQueue(l0Device, zeKernel, KEnv);
+ return launchKernelWithCmdQueue(l0Device, zeKernel, KEnv, AppendLaunch);
}
} // namespace llvm::omp::target::plugin
diff --git a/offload/unittests/OffloadAPI/CMakeLists.txt b/offload/unittests/OffloadAPI/CMakeLists.txt
index 39863391f27d6..1443ee484e741 100644
--- a/offload/unittests/OffloadAPI/CMakeLists.txt
+++ b/offload/unittests/OffloadAPI/CMakeLists.txt
@@ -23,7 +23,8 @@ target_compile_definitions("init.unittests" PRIVATE DISABLE_WRAPPER)
add_offload_unittest("kernel"
kernel/olCalculateOptimalOccupancy.cpp
- kernel/olLaunchKernel.cpp)
+ kernel/olLaunchKernel.cpp
+ kernel/olLaunchKernelWithPtrArgs.cpp)
add_offload_unittest("memory"
memory/olMemAlloc.cpp
diff --git a/offload/unittests/OffloadAPI/device_code/multiargs.cpp b/offload/unittests/OffloadAPI/device_code/multiargs.cpp
index 265dad124e91e..712512b964d27 100644
--- a/offload/unittests/OffloadAPI/device_code/multiargs.cpp
+++ b/offload/unittests/OffloadAPI/device_code/multiargs.cpp
@@ -1,3 +1,5 @@
#include <gpuintrin.h>
-extern "C" __gpu_kernel void multiargs(char, int *, short) { (void)0; }
+extern "C" __gpu_kernel void multiargs(char A, int *B, short C) {
+ B[__gpu_thread_id(0)] = A + C + __gpu_thread_id(0);
+}
diff --git a/offload/unittests/OffloadAPI/kernel/olLaunchKernel.cpp b/offload/unittests/OffloadAPI/kernel/olLaunchKernel.cpp
index 166b8dabff0d8..224981d8531ec 100644
--- a/offload/unittests/OffloadAPI/kernel/olLaunchKernel.cpp
+++ b/offload/unittests/OffloadAPI/kernel/olLaunchKernel.cpp
@@ -137,16 +137,26 @@ TEST_P(olLaunchKernelNoArgsTest, Success) {
}
TEST_P(olLaunchKernelMultiArgsTest, Success) {
+ void *Mem;
+ ASSERT_SUCCESS(olMemAlloc(Device, OL_ALLOC_TYPE_MANAGED,
+ LaunchArgs.GroupSize.x * sizeof(int), &Mem));
+
struct {
char A;
int *B;
short C;
- } Args{0, nullptr, 0};
+ } Args{3, (int *)Mem, 5};
ASSERT_SUCCESS(
olLaunchKernel(Queue, Device, Kernel, &Args, sizeof(Args), &LaunchArgs));
ASSERT_SUCCESS(olSyncQueue(Queue));
+
+ int *Data = (int *)Mem;
+ for (uint32_t i = 0; i < LaunchArgs.GroupSize.x; i++)
+ ASSERT_EQ(Data[i], Args.A + Args.C + static_cast<int>(i));
+
+ ASSERT_SUCCESS(olMemFree(Mem));
}
TEST_P(olLaunchKernelFooTest, SuccessSynchronous) {
diff --git a/offload/unittests/OffloadAPI/kernel/olLaunchKernelWithPtrArgs.cpp b/offload/unittests/OffloadAPI/kernel/olLaunchKernelWithPtrArgs.cpp
new file mode 100644
index 0000000000000..e7a275a1451f9
--- /dev/null
+++ b/offload/unittests/OffloadAPI/kernel/olLaunchKernelWithPtrArgs.cpp
@@ -0,0 +1,217 @@
+//===------- Offload API tests - olLaunchKernelWithPtrArgs ---------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "../common/Fixtures.hpp"
+#include <OffloadAPI.h>
+#include <gtest/gtest.h>
+
+struct LaunchKernelPtrArgsTestBase : OffloadQueueTest {
+ void SetUpProgram(const char *program) {
+ RETURN_ON_FATAL_FAILURE(OffloadQueueTest::SetUp());
+ ASSERT_TRUE(TestEnvironment::loadDeviceBinary(program, Device, DeviceBin));
+ ASSERT_GE(DeviceBin->getBufferSize(), 0lu);
+ ASSERT_SUCCESS(olCreateProgram(Device, DeviceBin->getBufferStart(),
+ DeviceBin->getBufferSize(), &Program));
+
+ LaunchArgs.Dimensions = 1;
+ LaunchArgs.GroupSize = {64, 1, 1};
+ LaunchArgs.NumGroups = {1, 1, 1};
+
+ LaunchArgs.DynSharedMemory = 0;
+ }
+
+ void TearDown() override {
+ if (Program) {
+ olDestroyProgram(Program);
+ }
+ RETURN_ON_FATAL_FAILURE(OffloadQueueTest::TearDown());
+ }
+
+ std::unique_ptr<llvm::MemoryBuffer> DeviceBin;
+ ol_program_handle_t Program = nullptr;
+ ol_kernel_launch_size_args_t LaunchArgs{};
+};
+
+struct LaunchKernelPtrArgsSingleTestBase : LaunchKernelPtrArgsTestBase {
+ void SetUpKernel(const char *kernel) {
+ RETURN_ON_FATAL_FAILURE(SetUpProgram(kernel));
+ ASSERT_SUCCESS(
+ olGetSymbol(Program, kernel, OL_SYMBOL_KIND_KERNEL, &Kernel));
+ }
+
+ ol_symbol_handle_t Kernel = nullptr;
+};
+
+#define PTRARGS_KERNEL_TEST(NAME, KERNEL) \
+ struct olLaunchKernelWithPtrArgs##NAME##Test \
+ : LaunchKernelPtrArgsSingleTestBase { \
+ void SetUp() override { SetUpKernel(#KERNEL); } \
+ }; \
+ OFFLOAD_TESTS_INSTANTIATE_DEVICE_FIXTURE( \
+ olLaunchKernelWithPtrArgs##NAME##Test);
+
+PTRARGS_KERNEL_TEST(Foo, foo)
+PTRARGS_KERNEL_TEST(NoArgs, noargs)
+PTRARGS_KERNEL_TEST(MultiArgs, multiargs)
+PTRARGS_KERNEL_TEST(Byte, byte)
+PTRARGS_KERNEL_TEST(LocalMem, localmem)
+
+struct LaunchKernelPtrArgsMultipleTestBase : LaunchKernelPtrArgsTestBase {
+ void SetUpKernels(const char *program, std::vector<const char *> kernels) {
+ RETURN_ON_FATAL_FAILURE(SetUpProgram(program));
+
+ Kernels.resize(kernels.size());
+ size_t I = 0;
+ for (auto K : kernels)
+ ASSERT_SUCCESS(
+ olGetSymbol(Program, K, OL_SYMBOL_KIND_KERNEL, &Kernels[I++]));
+ }
+
+ std::vector<ol_symbol_handle_t> Kernels;
+};
+
+#define PTRARGS_KERNEL_MULTI_TEST(NAME, PROGRAM, ...) \
+ struct olLaunchKernelWithPtrArgs##NAME##Test \
+ : LaunchKernelPtrArgsMultipleTestBase { \
+ void SetUp() override { SetUpKernels(#PROGRAM, {__VA_ARGS__}); } \
+ }; \
+ OFFLOAD_TESTS_INSTANTIATE_DEVICE_FIXTURE( \
+ olLaunchKernelWithPtrArgs##NAME##Test);
+
+PTRARGS_KERNEL_MULTI_TEST(Global, global, "write", "read")
+
+TEST_P(olLaunchKernelWithPtrArgsFooTest, Success) {
+ void *Mem;
+ ASSERT_SUCCESS(olMemAlloc(Device, OL_ALLOC_TYPE_MANAGED,
+ LaunchArgs.GroupSize.x * sizeof(uint32_t), &Mem));
+
+ void *ArgPtrs[] = {&Mem};
+ size_t ArgSizes[] = {sizeof(Mem)};
+
+ ASSERT_SUCCESS(olLaunchKernelWithPtrArgs(Queue, Device, Kernel, ArgPtrs,
+ ArgSizes, &LaunchArgs));
+
+ ASSERT_SUCCESS(olSyncQueue(Queue));
+
+ uint32_t *Data = (uint32_t *)Mem;
+ for (uint32_t i = 0; i < 64; i++) {
+ ASSERT_EQ(Data[i], i);
+ }
+
+ ASSERT_SUCCESS(olMemFree(Mem));
+}
+
+TEST_P(olLaunchKernelWithPtrArgsFooTest, SuccessThreaded) {
+ threadify([&](size_t) {
+ void *Mem;
+ ASSERT_SUCCESS(olMemAlloc(Device, OL_ALLOC_TYPE_MANAGED,
+ LaunchArgs.GroupSize.x * sizeof(uint32_t), &Mem));
+
+ void *ArgPtrs[] = {&Mem};
+ size_t ArgSizes[] = {sizeof(Mem)};
+
+ ASSERT_SUCCESS(olLaunchKernelWithPtrArgs(Queue, Device, Kernel, ArgPtrs,
+ ArgSizes, &LaunchArgs));
+
+ ASSERT_SUCCESS(olSyncQueue(Queue));
+
+ uint32_t *Data = (uint32_t *)Mem;
+ for (uint32_t i = 0; i < 64; i++) {
+ ASSERT_EQ(Data[i], i);
+ }
+
+ ASSERT_SUCCESS(olMemFree(Mem));
+ });
+}
+
+TEST_P(olLaunchKernelWithPtrArgsNoArgsTest, Success) {
+ ASSERT_SUCCESS(olLaunchKernelWithPtrArgs(Queue, Device, Kernel, nullptr,
+ nullptr, &LaunchArgs));
+
+ ASSERT_SUCCESS(olSyncQueue(Queue));
+}
+
+TEST_P(olLaunchKernelWithPtrArgsMultiArgsTest, Success) {
+ void *Mem;
+ ASSERT_SUCCESS(olMemAlloc(Device, OL_ALLOC_TYPE_MANAGED,
+ LaunchArgs.GroupSize.x * sizeof(int), &Mem));
+
+ char A = 3;
+ int *B = (int *)Mem;
+ short C = 5;
+
+ void *ArgPtrs[] = {&A, &B, &C};
+ size_t ArgSizes[] = {sizeof(A), sizeof(B), sizeof(C)};
+
+ ASSERT_SUCCESS(olLaunchKernelWithPtrArgs(Queue, Device, Kernel, ArgPtrs,
+ ArgSizes, &LaunchArgs));
+
+ ASSERT_SUCCESS(olSyncQueue(Queue));
+
+ int *Data = (int *)Mem;
+ for (uint32_t i = 0; i < LaunchArgs.GroupSize.x; i++)
+ ASSERT_EQ(Data[i], A + C + static_cast<int>(i));
+
+ ASSERT_SUCCESS(olMemFree(Mem));
+}
+
+TEST_P(olLaunchKernelWithPtrArgsFooTest, SuccessSynchronous) {
+ void *Mem;
+ ASSERT_SUCCESS(olMemAlloc(Device, OL_ALLOC_TYPE_MANAGED,
+ LaunchArgs.GroupSize.x * sizeof(uint32_t), &Mem));
+
+ void *ArgPtrs[] = {&Mem};
+ size_t ArgSizes[] = {sizeof(Mem)};
+
+ ASSERT_SUCCESS(olLaunchKernelWithPtrArgs(nullptr, Device, Kernel, ArgPtrs,
+ ArgSizes, &LaunchArgs));
+
+ uint32_t *Data = (uint32_t *)Mem;
+ for (uint32_t i = 0; i < 64; i++) {
+ ASSERT_EQ(Data[i], i);
+ }
+
+ ASSERT_SUCCESS(olMemFree(Mem));
+}
+
+TEST_P(olLaunchKernelWithPtrArgsByteTest, Success) {
+ unsigned char C = 42;
+
+ void *ArgPtrs[] = {&C};
+ size_t ArgSizes[] = {sizeof(C)};
+
+ ASSERT_SUCCESS(olLaunchKernelWithPtrArgs(Queue, Device, Kernel, ArgPtrs,
+ ArgSizes, &LaunchArgs));
+
+ ASSERT_SUCCESS(olSyncQueue(Queue));
+}
+
+TEST_P(olLaunchKernelWithPtrArgsLocalMemTest, Success) {
+ LaunchArgs.NumGroups.x = 4;
+ LaunchArgs.DynSharedMemory = 64 * sizeof(uint32_t);
+
+ void *Mem;
+ ASSERT_SUCCESS(olMemAlloc(Device, OL_ALLOC_TYPE_MANAGED,
+ LaunchArgs.GroupSize.x * LaunchArgs.NumGroups.x *
+ sizeof(uint32_t),
+ &Mem));
+
+ void *ArgPtrs[] = {&Mem};
+ size_t ArgSizes[] = {sizeof(Mem)};
+
+ ASSERT_SUCCESS(olLaunchKernelWithPtrArgs(Queue, Device, Kernel, ArgPtrs,
+ ArgSizes, &LaunchArgs));
+
+ ASSERT_SUCCESS(olSyncQueue(Queue));
+
+ uint32_t *Data = (uint32_t *)Mem;
+ for (uint32_t i = 0; i < LaunchArgs.GroupSize.x * LaunchArgs.NumGroups.x; i++)
+ ASSERT_EQ(Data[i], (i % 64) * 2);
+
+ ASSERT_SUCCESS(olMemFree(Mem));
+}
More information about the llvm-commits
mailing list