1use std::{
2 fmt::{self, Formatter},
3 marker::PhantomData,
4 mem::{MaybeUninit, align_of, size_of},
5 ptr,
6};
7
8use crate::{
9 memory::{DeviceMemory, ManagedMemory},
10 view::{DeviceInputView, DeviceRange, DeviceRepr, DeviceSliceMut, DeviceView, DeviceViewMut},
11};
12
13pub struct KernelParameters<'a> {
34 arguments: Vec<KernelParameter<'a>>,
35}
36
37const INLINE_KERNEL_ARGUMENTS: usize = 16;
38const INLINE_KERNEL_ARGUMENT_BYTES: usize = 16;
39
40mod private {
41 #[expect(
42 unnameable_types,
43 reason = "sealed supertrait that other crates must not name or implement"
44 )]
45 pub trait Sealed {}
46}
47
48pub trait PushKernelArg {
52 fn push_to(self, params: &mut KernelParameters<'_>);
54}
55
56pub trait KernelLaunchArgs<'a>: private::Sealed {
60 #[doc(hidden)]
61 fn with_encoded_arguments<R>(self, f: impl FnOnce(EncodedKernelArgs<'_>) -> R) -> R;
62}
63
64#[derive(Debug)]
69#[doc(hidden)]
70pub struct EncodedKernelArgs<'a> {
71 pointers: &'a mut [*mut ()],
72}
73
74trait KernelTupleArgument<'a> {
75 fn into_kernel_argument_ptr(self) -> *mut ();
76}
77
78enum KernelParameter<'a> {
79 Borrowed {
80 ptr: *mut (),
81 _marker: PhantomData<&'a ()>,
82 },
83 Owned(OwnedKernelArgument),
84}
85
86impl fmt::Debug for KernelParameter<'_> {
87 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
88 match self {
89 Self::Borrowed { ptr, .. } => f.debug_tuple("Borrowed").field(ptr).finish(),
90 Self::Owned(value) => f.debug_tuple("Owned").field(value).finish(),
91 }
92 }
93}
94
95enum OwnedKernelArgument {
96 Inline(InlineKernelArgument),
97 Boxed(Box<dyn KernelArgumentStorage>),
98}
99
100impl fmt::Debug for OwnedKernelArgument {
101 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
102 match self {
103 Self::Inline(value) => f.debug_tuple("Inline").field(value).finish(),
104 Self::Boxed(_) => f.debug_tuple("Boxed").finish_non_exhaustive(),
105 }
106 }
107}
108
109trait KernelArgumentStorage {
110 fn as_mut_ptr(&mut self) -> *mut ();
111}
112
113impl<T> KernelArgumentStorage for T {
114 fn as_mut_ptr(&mut self) -> *mut () {
115 ptr::from_mut(self).cast()
116 }
117}
118
119#[derive(Clone, Copy)]
120#[repr(C, align(16))]
121struct InlineKernelArgument {
122 bytes: [MaybeUninit<u8>; INLINE_KERNEL_ARGUMENT_BYTES],
123}
124
125impl fmt::Debug for InlineKernelArgument {
126 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
127 f.debug_struct("InlineKernelArgument")
128 .finish_non_exhaustive()
129 }
130}
131
132impl fmt::Debug for KernelParameters<'_> {
133 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
134 f.debug_struct("KernelParameters")
135 .field("arguments", &self.arguments.len())
136 .finish()
137 }
138}
139
140impl<'a> KernelParameters<'a> {
141 #[must_use]
143 pub const fn new() -> Self {
144 Self {
145 arguments: Vec::new(),
146 }
147 }
148
149 pub fn arg<T: 'a>(&mut self, value: &'a T) -> &mut Self {
154 self.arguments.push(KernelParameter::Borrowed {
155 ptr: ptr::from_ref(value).cast_mut().cast::<()>(),
156 _marker: PhantomData,
157 });
158 self
159 }
160
161 pub fn arg_mut<T: 'a>(&mut self, value: &'a mut T) -> &mut Self {
166 self.arguments.push(KernelParameter::Borrowed {
167 ptr: ptr::from_mut(value).cast::<()>(),
168 _marker: PhantomData,
169 });
170 self
171 }
172
173 pub fn owned_arg<T: Copy + 'static>(&mut self, value: T) -> &mut Self {
178 let value = OwnedKernelArgument::from_value(value);
179 self.arguments.push(KernelParameter::Owned(value));
180 self
181 }
182
183 pub fn push<A: PushKernelArg>(&mut self, arg: A) -> &mut Self {
185 arg.push_to(self);
186 self
187 }
188
189 pub fn device_input<T: DeviceRepr, S: DeviceRange<T> + ?Sized>(
194 &mut self,
195 slice: &S,
196 ) -> &mut Self {
197 self.owned_arg(slice.as_device_ptr())
200 }
201
202 pub fn device_slice_mut<T: DeviceRepr, S: DeviceSliceMut<T> + ?Sized>(
207 &mut self,
208 slice: &mut S,
209 ) -> &mut Self {
210 self.owned_arg(slice.as_mut_ptr())
211 }
212
213 fn raw_pointers(&mut self) -> RawKernelPointers {
214 RawKernelPointers::from_parameters(self.arguments.as_mut_slice())
215 }
216}
217
218impl KernelParameter<'_> {
219 fn as_mut_ptr(&mut self) -> *mut () {
220 match self {
221 Self::Borrowed { ptr, .. } => *ptr,
222 Self::Owned(value) => value.as_mut_ptr(),
223 }
224 }
225}
226
227impl OwnedKernelArgument {
228 fn from_value<T: Copy + 'static>(value: T) -> Self {
229 InlineKernelArgument::from_value(value)
230 .map_or_else(|| Self::Boxed(Box::new(value)), Self::Inline)
231 }
232
233 fn as_mut_ptr(&mut self) -> *mut () {
234 match self {
235 Self::Inline(value) => value.as_mut_ptr(),
236 Self::Boxed(value) => value.as_mut().as_mut_ptr(),
237 }
238 }
239}
240
241impl InlineKernelArgument {
242 fn from_value<T: Copy>(value: T) -> Option<Self> {
244 if size_of::<T>() > INLINE_KERNEL_ARGUMENT_BYTES || align_of::<T>() > align_of::<Self>() {
245 return None;
246 }
247
248 let mut storage = Self {
249 bytes: [MaybeUninit::uninit(); INLINE_KERNEL_ARGUMENT_BYTES],
250 };
251 unsafe {
253 ptr::write(storage.as_mut_ptr().cast::<T>(), value);
254 }
255 Some(storage)
256 }
257
258 fn as_mut_ptr(&mut self) -> *mut () {
259 self.bytes.as_mut_ptr().cast()
260 }
261}
262
263enum RawKernelPointers {
264 Inline {
265 pointers: [*mut (); INLINE_KERNEL_ARGUMENTS],
266 len: usize,
267 },
268 Heap(Vec<*mut ()>),
269}
270
271impl RawKernelPointers {
272 fn from_parameters(parameters: &mut [KernelParameter<'_>]) -> Self {
273 if parameters.len() <= INLINE_KERNEL_ARGUMENTS {
274 let mut pointers = [ptr::null_mut(); INLINE_KERNEL_ARGUMENTS];
275 for (dst, parameter) in pointers.iter_mut().zip(&mut *parameters) {
276 *dst = parameter.as_mut_ptr();
277 }
278 Self::Inline {
279 pointers,
280 len: parameters.len(),
281 }
282 } else {
283 Self::Heap(
284 parameters
285 .iter_mut()
286 .map(KernelParameter::as_mut_ptr)
287 .collect(),
288 )
289 }
290 }
291
292 fn as_mut_slice(&mut self) -> &mut [*mut ()] {
293 match self {
294 Self::Inline { pointers, len } => &mut pointers[..*len],
295 Self::Heap(pointers) => pointers.as_mut_slice(),
296 }
297 }
298}
299
300impl EncodedKernelArgs<'_> {
301 pub(crate) fn as_mut_ptr(&mut self) -> *mut *mut () {
302 self.pointers.as_mut_ptr()
303 }
304}
305
306impl<'a> KernelLaunchArgs<'a> for KernelParameters<'a> {
307 fn with_encoded_arguments<R>(mut self, f: impl FnOnce(EncodedKernelArgs<'_>) -> R) -> R {
308 let mut pointers = self.raw_pointers();
309 f(EncodedKernelArgs {
310 pointers: pointers.as_mut_slice(),
311 })
312 }
313}
314
315impl private::Sealed for KernelParameters<'_> {}
316
317impl<'a> KernelLaunchArgs<'a> for &mut KernelParameters<'a> {
318 fn with_encoded_arguments<R>(self, f: impl FnOnce(EncodedKernelArgs<'_>) -> R) -> R {
319 let mut pointers = self.raw_pointers();
320 f(EncodedKernelArgs {
321 pointers: pointers.as_mut_slice(),
322 })
323 }
324}
325
326impl private::Sealed for &mut KernelParameters<'_> {}
327
328impl KernelLaunchArgs<'_> for () {
329 fn with_encoded_arguments<R>(self, f: impl FnOnce(EncodedKernelArgs<'_>) -> R) -> R {
330 let mut pointers: [*mut (); 0] = [];
331 f(EncodedKernelArgs {
332 pointers: &mut pointers,
333 })
334 }
335}
336
337impl private::Sealed for () {}
338
339macro_rules! impl_kernel_arguments_for_tuple {
340 ($($arg:ident),+ $(,)?) => {
341 impl<'a, $($arg),+> private::Sealed for ($($arg,)+)
342 where
343 $($arg: KernelTupleArgument<'a>,)+
344 {
345 }
346
347 impl<'a, $($arg),+> KernelLaunchArgs<'a> for ($($arg,)+)
348 where
349 $($arg: KernelTupleArgument<'a>,)+
350 {
351 fn with_encoded_arguments<R>(self, f: impl FnOnce(EncodedKernelArgs<'_>) -> R) -> R {
352 #[allow(non_snake_case, reason = "tuple fields are bound to the macro's uppercase type parameter names")]
353 let ($($arg,)+) = self;
354 let mut pointers = [
355 $($arg.into_kernel_argument_ptr(),)+
356 ];
357 f(EncodedKernelArgs {
358 pointers: &mut pointers,
359 })
360 }
361 }
362 };
363}
364
365impl<'a, T: 'a> KernelTupleArgument<'a> for &'a T {
366 fn into_kernel_argument_ptr(self) -> *mut () {
367 ptr::from_ref(self).cast_mut().cast()
368 }
369}
370
371impl<'a, T: 'a> KernelTupleArgument<'a> for &'a mut T {
372 fn into_kernel_argument_ptr(self) -> *mut () {
373 ptr::from_mut(self).cast()
374 }
375}
376
377impl_kernel_arguments_for_tuple!(A);
378
379impl_kernel_arguments_for_tuple!(A, B);
380
381impl_kernel_arguments_for_tuple!(A, B, C);
382
383impl_kernel_arguments_for_tuple!(A, B, C, D);
384
385impl_kernel_arguments_for_tuple!(A, B, C, D, E);
386
387impl_kernel_arguments_for_tuple!(A, B, C, D, E, F);
388
389impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G);
390
391impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H);
392
393impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H, I);
394
395impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H, I, J);
396
397impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H, I, J, K);
398
399impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L);
400
401impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M);
402
403impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
404
405impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
406
407impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
408
409macro_rules! impl_push_scalar {
410 ($($ty:ty),* $(,)?) => {
411 $(
412 impl PushKernelArg for $ty {
413 fn push_to(self, params: &mut KernelParameters<'_>) {
414 params.owned_arg(self);
415 }
416 }
417 )*
418 };
419}
420
421impl_push_scalar!(
422 u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64,
423);
424
425impl<T: DeviceRepr> PushKernelArg for &DeviceMemory<T> {
426 fn push_to(self, params: &mut KernelParameters<'_>) {
427 params.device_input(self);
428 }
429}
430
431impl<T: DeviceRepr> PushKernelArg for &mut DeviceMemory<T> {
432 fn push_to(self, params: &mut KernelParameters<'_>) {
433 params.device_slice_mut(self);
434 }
435}
436
437impl<T: DeviceRepr> PushKernelArg for &ManagedMemory<T> {
438 fn push_to(self, params: &mut KernelParameters<'_>) {
439 params.device_input(self);
440 }
441}
442
443impl<T: DeviceRepr> PushKernelArg for &mut ManagedMemory<T> {
444 fn push_to(self, params: &mut KernelParameters<'_>) {
445 params.device_slice_mut(self);
446 }
447}
448
449impl<T: DeviceRepr> PushKernelArg for DeviceInputView<'_, T> {
450 fn push_to(self, params: &mut KernelParameters<'_>) {
451 params.device_input(&self);
452 }
453}
454
455impl<T: DeviceRepr> PushKernelArg for &DeviceInputView<'_, T> {
456 fn push_to(self, params: &mut KernelParameters<'_>) {
457 params.device_input(self);
458 }
459}
460
461impl<T: DeviceRepr> PushKernelArg for DeviceView<'_, T> {
462 fn push_to(self, params: &mut KernelParameters<'_>) {
463 params.owned_arg(self.as_ptr());
464 }
465}
466
467impl<T: DeviceRepr> PushKernelArg for &DeviceView<'_, T> {
468 fn push_to(self, params: &mut KernelParameters<'_>) {
469 params.owned_arg(self.as_ptr());
470 }
471}
472
473impl<T: DeviceRepr> PushKernelArg for &DeviceViewMut<'_, T> {
474 fn push_to(self, params: &mut KernelParameters<'_>) {
475 params.owned_arg(self.as_ptr());
476 }
477}
478
479impl<T: DeviceRepr> PushKernelArg for &mut DeviceViewMut<'_, T> {
480 fn push_to(self, params: &mut KernelParameters<'_>) {
481 params.owned_arg(self.as_mut_ptr());
482 }
483}
484
485impl Default for KernelParameters<'_> {
486 fn default() -> Self {
487 Self::new()
488 }
489}
490
491#[cfg(test)]
492mod tests {
493 use super::*;
494
495 #[derive(Clone, Copy)]
496 #[repr(C)]
497 struct LargeArgument {
498 words: [u64; 3],
499 }
500
501 #[test]
502 fn test_boxed_owned_kernel_argument_points_to_inner_value() {
503 let mut argument = OwnedKernelArgument::from_value(LargeArgument { words: [1, 2, 3] });
504 assert!(matches!(argument, OwnedKernelArgument::Boxed(_)));
505
506 let expected = match &mut argument {
507 OwnedKernelArgument::Boxed(value) => value.as_mut().as_mut_ptr(),
508 OwnedKernelArgument::Inline(_) => unreachable!(),
509 };
510
511 assert_eq!(argument.as_mut_ptr(), expected);
512 }
513}