singe_cuda/nvrtc/program.rs
1use std::{
2 cell::{RefCell, UnsafeCell},
3 ffi::{CStr, CString, c_char, c_void},
4 ptr, result,
5 sync::{
6 Arc,
7 atomic::{AtomicBool, Ordering},
8 },
9};
10
11use singe_core::report_cleanup_failure;
12use singe_cuda_sys::nvrtc as sys;
13
14use super::{CompileOptions, Status};
15use crate::{
16 error::{Error, Result},
17 module::ModuleImage,
18 try_nvrtc,
19 utility::{bytes_to_string, to_i32, to_usize},
20};
21
22/// Borrowed CUDA header source and the virtual include name used by NVRTC.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
24pub struct Header<'a> {
25 /// Header source text.
26 /// Program builders copy this text when the header is added.
27 pub source: &'a str,
28 /// Include name by which CUDA source refers to this header.
29 pub include_name: &'a str,
30}
31
32#[derive(Debug, Clone)]
33struct OwnedHeader {
34 source: String,
35 include_name: String,
36}
37
38/// Owned NVRTC program with copied source and virtual headers.
39/// The native program is created lazily on the first operation that needs its handle and destroyed when this wrapper is dropped.
40/// Builder changes made after materialization do not recreate the existing native program.
41#[derive(Debug)]
42pub struct Program {
43 source: String,
44 name: Option<String>,
45 headers: Vec<OwnedHeader>,
46 handle: UnsafeCell<sys::nvrtcProgram>,
47 // The flag a registered cancellation callback reads, kept until the callback is cleared or the program is destroyed.
48 cancel_flag: RefCell<Option<Arc<AtomicBool>>>,
49}
50
51/// Raw ownership of an NVRTC program, including the cancellation flag its flow callback may still read.
52///
53/// Keep `cancel_flag` alive until the handle is destroyed or re-adopted with [`Program::from_raw`].
54#[derive(Debug)]
55pub struct RawProgram {
56 /// Native program handle.
57 pub handle: sys::nvrtcProgram,
58 /// Flag passed to a flow callback that is still registered on the handle, if any.
59 pub cancel_flag: Option<Arc<AtomicBool>>,
60}
61
62impl Program {
63 /// Creates a lazy NVRTC program from CUDA source text.
64 ///
65 /// The raw NVRTC handle is created when the program is compiled or otherwise materialized.
66 #[must_use]
67 pub fn from_source(source: &str) -> Self {
68 Self {
69 source: source.to_string(),
70 name: None,
71 headers: Vec::new(),
72 handle: UnsafeCell::new(ptr::null_mut()),
73 cancel_flag: RefCell::new(None),
74 }
75 }
76
77 /// Copies the source filename used in diagnostics when the native program is first created.
78 /// An already materialized program keeps its existing name.
79 #[must_use]
80 pub fn with_name(mut self, name: &str) -> Self {
81 self.name = Some(name.to_string());
82 self
83 }
84
85 /// Copies a virtual header's source and include name for native program creation.
86 /// Add headers before materializing the program.
87 #[must_use]
88 pub fn with_header(mut self, header: Header<'_>) -> Self {
89 self.headers.push(OwnedHeader {
90 source: header.source.to_string(),
91 include_name: header.include_name.to_string(),
92 });
93 self
94 }
95
96 /// Copies virtual headers in slice order for native program creation.
97 /// Add headers before materializing the program.
98 #[must_use]
99 pub fn with_headers(mut self, headers: &[Header<'_>]) -> Self {
100 self.headers
101 .extend(headers.iter().map(|header| OwnedHeader {
102 source: header.source.to_string(),
103 include_name: header.include_name.to_string(),
104 }));
105 self
106 }
107
108 /// Takes ownership of a raw NVRTC program.
109 ///
110 /// # Safety
111 ///
112 /// `raw.handle` must be a valid NVRTC program that is not owned by any other wrapper.
113 /// Any flow callback registered on it must be NVRTC's default, a callback that reads no payload, or this crate's cancellation callback with `raw.cancel_flag` as its payload.
114 /// The returned wrapper destroys the handle on drop.
115 ///
116 /// # Errors
117 ///
118 /// Returns an error if `raw.handle` is null.
119 pub unsafe fn from_raw(raw: RawProgram) -> Result<Self> {
120 if raw.handle.is_null() {
121 return Err(Error::NullHandle);
122 }
123
124 Ok(Self {
125 source: String::new(),
126 name: None,
127 headers: Vec::new(),
128 handle: UnsafeCell::new(raw.handle),
129 cancel_flag: RefCell::new(raw.cancel_flag),
130 })
131 }
132
133 /// Renders `options` and compiles the program synchronously.
134 /// Call [`Self::log`] to inspect compiler diagnostics after a successful or failed compilation.
135 ///
136 /// With a flag set through [`CompileOptions::cancel_flag()`], another thread can cancel compilation by setting the flag to true.
137 /// The wrapper then registers its own native callback and attempts to replace it with a no-op callback after compilation, including failed attempts, and the program keeps a clone of the flag until that replacement succeeds.
138 ///
139 /// # Errors
140 ///
141 /// Returns an error if lazy program creation fails, an option contains an interior NUL, the option count does not fit an `i32`, or NVRTC rejects an option or fails compilation.
142 /// Compilation diagnostics remain available from [`Self::log`].
143 /// Errors from registering or clearing the cancellation callback are also returned.
144 /// A compilation error takes precedence over a later callback-clear error.
145 pub fn compile(&self, options: &CompileOptions<'_>) -> Result<()> {
146 let arguments = options.as_arguments();
147 let argument_refs = arguments.iter().map(String::as_str).collect::<Vec<_>>();
148 let Some(cancel) = &options.cancel_flag else {
149 return self.compile_raw(&argument_refs);
150 };
151
152 let cancel = Arc::clone(cancel);
153 // SAFETY: the program handle is live, and the payload points into `cancel`, which the program keeps below for as long as NVRTC can call the callback with it.
154 unsafe {
155 try_nvrtc!(sys::nvrtcSetFlowCallback(
156 self.handle()?,
157 Some(cancel_if_requested_callback),
158 Arc::as_ptr(&cancel).cast_mut().cast(),
159 ))?;
160 }
161
162 // NVRTC no longer references a previously kept flag, so dropping it here is sound.
163 *self.cancel_flag.borrow_mut() = Some(cancel);
164
165 let compile_result = self.compile_raw(&argument_refs);
166 let clear_result = self.clear_flow_callback();
167
168 match (compile_result, clear_result) {
169 (Err(error), _) | (Ok(()), Err(error)) => Err(error),
170 (Ok(()), Ok(())) => Ok(()),
171 }
172 }
173
174 /// Registers a name expression for a `__global__`, `__device__`, or `__constant__` symbol.
175 ///
176 /// The identical name expression string must be provided to [`Program::lowered_name`] after compilation.
177 ///
178 /// # Errors
179 ///
180 /// Returns an error if `name_expression` contains an interior NUL byte, if the program handle is invalid, or if NVRTC rejects the expression.
181 pub fn add_name_expression(&self, name_expression: &str) -> Result<()> {
182 let name_expression = CString::new(name_expression)?;
183 // SAFETY: `self` owns the live program, and `name_expression` is a NUL-terminated string borrowed for the call, which copies it.
184 unsafe {
185 try_nvrtc!(sys::nvrtcAddNameExpression(
186 self.handle()?,
187 name_expression.as_ptr(),
188 ))
189 }
190 }
191
192 /// Returns the lowered (mangled) name for a registered name expression.
193 ///
194 /// The identical name expression must have been previously provided to [`Program::add_name_expression`].
195 ///
196 /// # Errors
197 ///
198 /// Returns an error if `name_expression` contains an interior NUL byte, if the program handle is invalid, or if NVRTC cannot return the lowered name.
199 pub fn lowered_name(&self, name_expression: &str) -> Result<String> {
200 let name_expression = CString::new(name_expression)?;
201 let mut lowered_name = ptr::null();
202 // SAFETY: `self` owns the live program, the name is NUL-terminated, and on success NVRTC points `lowered_name` at a NUL-terminated string the program owns, copied out before `self` can drop.
203 unsafe {
204 try_nvrtc!(sys::nvrtcGetLoweredName(
205 self.handle()?,
206 name_expression.as_ptr(),
207 &raw mut lowered_name,
208 ))?;
209 Ok(CStr::from_ptr(lowered_name).to_string_lossy().into_owned())
210 }
211 }
212
213 /// Returns the PTX bytes produced by the last compilation, including the native trailing NUL byte.
214 ///
215 /// # Errors
216 ///
217 /// Returns an error if lazy program creation fails, NVRTC cannot query or copy the requested output, or the native output size cannot be represented as `usize`.
218 /// The requested code format must have been generated by the preceding compilation.
219 pub fn ptx(&self) -> Result<Vec<u8>> {
220 self.bytes(sys::nvrtcGetPTXSize, sys::nvrtcGetPTX)
221 }
222
223 /// Copies the last compilation's PTX bytes into an owned module image.
224 ///
225 /// # Errors
226 ///
227 /// Returns an error if lazy program creation fails, NVRTC cannot query or copy the requested output, the native output size cannot be represented as `usize`, or the output is empty.
228 /// The requested code format must have been generated by the preceding compilation.
229 pub fn ptx_image(&self) -> Result<ModuleImage<'static>> {
230 ModuleImage::from_compiler_output(self.ptx()?)
231 }
232
233 /// Returns the last compilation's PTX as a string, removing its trailing NUL and replacing invalid UTF-8 lossily.
234 ///
235 /// # Errors
236 ///
237 /// Returns an error if lazy program creation fails, NVRTC cannot query or copy the requested output, or the native output size cannot be represented as `usize`.
238 /// The requested code format must have been generated by the preceding compilation.
239 pub fn ptx_string(&self) -> Result<String> {
240 Ok(bytes_to_string(self.ptx()?))
241 }
242
243 /// Returns the GPU machine-code binary produced by the last compilation for a real GPU architecture target.
244 ///
245 /// # Errors
246 ///
247 /// Returns an error if lazy program creation fails, NVRTC cannot query or copy the requested output, or the native output size cannot be represented as `usize`.
248 /// The requested code format must have been generated by the preceding compilation.
249 pub fn cubin(&self) -> Result<Vec<u8>> {
250 self.bytes(sys::nvrtcGetCUBINSize, sys::nvrtcGetCUBIN)
251 }
252
253 /// Copies the last compilation's GPU machine-code binary into an owned module image.
254 ///
255 /// # Errors
256 ///
257 /// Returns an error if lazy program creation fails, NVRTC cannot query or copy the requested output, the native output size cannot be represented as `usize`, or the output is empty.
258 /// The requested code format must have been generated by the preceding compilation.
259 pub fn cubin_image(&self) -> Result<ModuleImage<'static>> {
260 ModuleImage::from_compiler_output(self.cubin()?)
261 }
262
263 /// Returns the `cuda_tile` IR generated by the previous compilation of this program.
264 ///
265 /// # Errors
266 ///
267 /// Returns an error if lazy program creation fails, NVRTC cannot query or copy the requested output, or the native output size cannot be represented as `usize`.
268 /// The requested code format must have been generated by the preceding compilation.
269 pub fn tile_ir(&self) -> Result<Vec<u8>> {
270 self.bytes(sys::nvrtcGetTileIRSize, sys::nvrtcGetTileIR)
271 }
272
273 /// Returns the device link-time intermediate representation produced by the last compilation.
274 ///
275 /// # Errors
276 ///
277 /// Returns an error if lazy program creation fails, NVRTC cannot query or copy the requested output, or the native output size cannot be represented as `usize`.
278 /// The requested code format must have been generated by the preceding compilation.
279 pub fn lto_ir(&self) -> Result<Vec<u8>> {
280 self.bytes(sys::nvrtcGetLTOIRSize, sys::nvrtcGetLTOIR)
281 }
282
283 /// Returns the `OptiX` intermediate representation produced by the last compilation.
284 ///
285 /// # Errors
286 ///
287 /// Returns an error if lazy program creation fails, NVRTC cannot query or copy the requested output, or the native output size cannot be represented as `usize`.
288 /// The requested code format must have been generated by the preceding compilation.
289 pub fn optix_ir(&self) -> Result<Vec<u8>> {
290 self.bytes(sys::nvrtcGetOptiXIRSize, sys::nvrtcGetOptiXIR)
291 }
292
293 /// Returns the program compilation log, removing its trailing NUL and replacing invalid UTF-8 lossily.
294 /// The log may contain diagnostics from either a successful or failed compilation.
295 ///
296 /// # Errors
297 ///
298 /// Returns an error if lazy program creation fails, NVRTC cannot query or copy the log, or the native log size cannot be represented as `usize`.
299 pub fn log(&self) -> Result<String> {
300 Ok(bytes_to_string(self.bytes(
301 sys::nvrtcGetProgramLogSize,
302 sys::nvrtcGetProgramLog,
303 )?))
304 }
305
306 /// Returns the PCH creation status.
307 ///
308 /// [`Status::Success`] indicates that the PCH was successfully created.
309 /// [`Status::NoPchCreateAttempted`] indicates that no PCH creation was attempted, either because PCH was not requested during the preceding compile call, or automatic PCH processing was requested, and the compiler chose not to create a PCH file.
310 /// [`Status::PchCreateHeapExhausted`] indicates that a PCH file could potentially have been created, but the compiler ran out space in the PCH heap.
311 /// In this scenario, use [`Program::pch_heap_size_required`] to query the required heap size, reallocate the heap with [`set_pch_heap_size`](super::set_pch_heap_size), and retry PCH creation by compiling a new [`Program`].
312 /// [`Status::PchCreate`] indicates that an error condition prevented the PCH file from being created.
313 ///
314 /// # Errors
315 ///
316 /// Returns an error if the program handle is invalid.
317 pub fn pch_create_status(&self) -> Result<Status> {
318 // SAFETY: `self` owns the live program.
319 unsafe { Ok(sys::nvrtcGetPCHCreateStatus(self.handle()?).into()) }
320 }
321
322 /// Returns the PCH heap size required to compile the given program.
323 ///
324 /// # Errors
325 ///
326 /// Returns an error if the program handle is invalid or if the returned size is not valid because [`Program::pch_create_status`] did not return [`Status::Success`] or [`Status::PchCreateHeapExhausted`].
327 pub fn pch_heap_size_required(&self) -> Result<usize> {
328 let mut size = 0;
329 // SAFETY: `self` owns the live program, and `size` is a local output.
330 unsafe {
331 try_nvrtc!(sys::nvrtcGetPCHHeapSizeRequired(
332 self.handle()?,
333 &raw mut size
334 ))?;
335 }
336 to_usize(size, "NVRTC output byte count")
337 }
338
339 /// Returns the raw NVRTC program handle, creating it first if needed.
340 ///
341 /// If the program has not been materialized yet, this creates the raw handle first.
342 ///
343 /// # Errors
344 ///
345 /// Returns an error if NVRTC cannot create the program handle.
346 pub fn materialize_raw(&self) -> Result<sys::nvrtcProgram> {
347 self.handle()
348 }
349
350 /// Returns the raw NVRTC program handle only if it has already been materialized.
351 pub const fn as_raw_if_materialized(&self) -> Option<sys::nvrtcProgram> {
352 // SAFETY: `Program` is not `Sync`, and no `&mut` to the cell is live while this shared borrow exists.
353 let handle = unsafe { *self.handle.get() };
354 if handle.is_null() { None } else { Some(handle) }
355 }
356
357 /// Transfers ownership of the raw NVRTC program to the caller.
358 ///
359 /// If the program has not been materialized yet, this creates the raw handle first.
360 /// The host copies of the source and headers are dropped, since NVRTC keeps its own.
361 /// The caller becomes responsible for destroying the returned handle.
362 ///
363 /// # Errors
364 ///
365 /// Returns an error if lazy program creation fails because source, filenames, or headers contain an interior NUL, the header count exceeds the native integer range, or NVRTC cannot create the program.
366 pub fn into_raw(mut self) -> Result<RawProgram> {
367 let handle = self.handle()?;
368 // A null handle makes `Drop` skip destruction, while the host strings drop normally.
369 *self.handle.get_mut() = ptr::null_mut();
370 Ok(RawProgram {
371 handle,
372 cancel_flag: self.cancel_flag.get_mut().take(),
373 })
374 }
375
376 fn compile_raw(&self, options: &[&str]) -> Result<()> {
377 let options = options
378 .iter()
379 .map(|option| CString::new(*option))
380 .collect::<result::Result<Vec<_>, _>>()?;
381 let option_ptrs = options
382 .iter()
383 .map(|value| value.as_ptr())
384 .collect::<Vec<_>>();
385
386 // SAFETY: `self` owns the live program, and `option_ptrs` holds the counted NUL-terminated options in `options`, which outlive the call.
387 unsafe {
388 try_nvrtc!(sys::nvrtcCompileProgram(
389 self.handle()?,
390 to_i32(option_ptrs.len(), "NVRTC option count")?,
391 if option_ptrs.is_empty() {
392 ptr::null()
393 } else {
394 option_ptrs.as_ptr()
395 },
396 ))
397 }
398 }
399
400 fn bytes(
401 &self,
402 get_size: unsafe extern "C" fn(sys::nvrtcProgram, *mut sys::size_t) -> sys::nvrtcResult,
403 get_data: unsafe extern "C" fn(sys::nvrtcProgram, *mut c_char) -> sys::nvrtcResult,
404 ) -> Result<Vec<u8>> {
405 let mut size = 0;
406 // SAFETY: `self` owns the live program, and `size` is a local output.
407 unsafe {
408 try_nvrtc!(get_size(self.handle()?, &raw mut size))?;
409 }
410
411 let mut bytes = vec![0u8; to_usize(size, "NVRTC output byte count")?];
412 if bytes.is_empty() {
413 return Ok(bytes);
414 }
415
416 // SAFETY: `bytes` holds the `size` bytes NVRTC reported for the same output of the live program.
417 unsafe {
418 try_nvrtc!(get_data(self.handle()?, bytes.as_mut_ptr().cast()))?;
419 }
420 Ok(bytes)
421 }
422
423 fn handle(&self) -> Result<sys::nvrtcProgram> {
424 // SAFETY: `Program` is not `Sync`, and no other reference into the cell is live during lazy creation.
425 unsafe {
426 let handle = self.handle.get();
427 if (*handle).is_null() {
428 *handle = self.create_handle()?;
429 }
430 Ok(*handle)
431 }
432 }
433
434 fn create_handle(&self) -> Result<sys::nvrtcProgram> {
435 let source = CString::new(self.source.as_str())?;
436 let name = self.name.as_deref().map(CString::new).transpose()?;
437 let header_sources = self
438 .headers
439 .iter()
440 .map(|header| CString::new(header.source.as_str()))
441 .collect::<result::Result<Vec<_>, _>>()?;
442 let include_names = self
443 .headers
444 .iter()
445 .map(|header| CString::new(header.include_name.as_str()))
446 .collect::<result::Result<Vec<_>, _>>()?;
447 let header_ptrs = header_sources
448 .iter()
449 .map(|value| value.as_ptr())
450 .collect::<Vec<_>>();
451 let include_name_ptrs = include_names
452 .iter()
453 .map(|value| value.as_ptr())
454 .collect::<Vec<_>>();
455
456 let mut handle = ptr::null_mut();
457 // SAFETY: `handle` is a local output, and the source, name, and the counted header and include-name arrays point at NUL-terminated strings that outlive the call.
458 unsafe {
459 try_nvrtc!(sys::nvrtcCreateProgram(
460 &raw mut handle,
461 source.as_ptr(),
462 name.as_ref().map_or(ptr::null(), |value| value.as_ptr()),
463 to_i32(self.headers.len(), "NVRTC header count")?,
464 if header_ptrs.is_empty() {
465 ptr::null()
466 } else {
467 header_ptrs.as_ptr()
468 },
469 if include_name_ptrs.is_empty() {
470 ptr::null()
471 } else {
472 include_name_ptrs.as_ptr()
473 },
474 ))?;
475 }
476
477 Ok(handle)
478 }
479}
480
481impl Drop for Program {
482 fn drop(&mut self) {
483 // SAFETY: `Program` is not `Sync`, so `&mut self` is the only access to the cell, and a non-null handle is owned by this wrapper.
484 unsafe {
485 let handle = self.handle.get();
486 if !(*handle).is_null()
487 && let Err(error) = try_nvrtc!(sys::nvrtcDestroyProgram(handle))
488 {
489 report_cleanup_failure("destroy", "nvrtc program", &error);
490 }
491 }
492 }
493}
494
495/// Owned NVRTC compilation output tagged with its code format.
496#[derive(Debug)]
497#[non_exhaustive]
498pub enum CompilationArtifact {
499 /// PTX assembly, requiring driver JIT compilation before execution.
500 Ptx(
501 /// Owned output image bytes.
502 ModuleImage<'static>,
503 ),
504 /// GPU machine code for a concrete GPU architecture.
505 Cubin(
506 /// Owned output image bytes.
507 ModuleImage<'static>,
508 ),
509 /// Device link-time intermediate representation, requiring linking before loading.
510 LtoIr(
511 /// Owned output bytes.
512 Vec<u8>,
513 ),
514 /// `OptiX` intermediate representation, which CUDA cannot load.
515 OptixIr(
516 /// Owned output bytes.
517 Vec<u8>,
518 ),
519 /// The `cuda_tile` IR generated by the previous compilation.
520 TileIr(
521 /// Owned output image bytes.
522 ModuleImage<'static>,
523 ),
524}
525
526impl CompilationArtifact {
527 /// Borrows the output bytes regardless of their compilation format.
528 #[must_use]
529 pub fn as_bytes(&self) -> &[u8] {
530 match self {
531 Self::Ptx(image) | Self::Cubin(image) | Self::TileIr(image) => image.as_bytes(),
532 Self::LtoIr(bytes) | Self::OptixIr(bytes) => bytes.as_slice(),
533 }
534 }
535
536 /// Consumes the artifact and returns its module image, or `Err(self)` for LTO IR and `OptiX` IR, which CUDA cannot load.
537 ///
538 /// # Errors
539 ///
540 /// Returns the artifact itself if it is LTO IR or `OptiX` IR.
541 pub fn into_image(self) -> result::Result<ModuleImage<'static>, Self> {
542 match self {
543 Self::Ptx(image) | Self::Cubin(image) | Self::TileIr(image) => Ok(image),
544 Self::LtoIr(_) | Self::OptixIr(_) => Err(self),
545 }
546 }
547}
548
549/// Compilation output format requested from an NVRTC program.
550#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
551#[non_exhaustive]
552pub enum OutputKind {
553 /// PTX assembly, requiring driver JIT compilation before execution.
554 Ptx,
555 /// GPU machine code for a concrete GPU architecture.
556 Cubin,
557 /// Device link-time intermediate representation, requiring linking before loading.
558 LtoIr,
559 /// `OptiX` intermediate representation.
560 OptixIr,
561 /// The `cuda_tile` IR generated by the previous compilation.
562 TileIr,
563}
564
565impl Program {
566 /// Returns the requested compilation output as an owned, format-tagged artifact.
567 ///
568 /// # Errors
569 ///
570 /// Returns an error if the selected output cannot be retrieved or is empty.
571 pub fn artifact(&self, kind: OutputKind) -> Result<CompilationArtifact> {
572 fn nonempty_output(bytes: Vec<u8>) -> Result<Vec<u8>> {
573 if bytes.is_empty() {
574 return Err(Error::empty("nvrtc output"));
575 }
576 Ok(bytes)
577 }
578
579 Ok(match kind {
580 OutputKind::Ptx => CompilationArtifact::Ptx(self.ptx_image()?),
581 OutputKind::Cubin => CompilationArtifact::Cubin(self.cubin_image()?),
582 OutputKind::LtoIr => CompilationArtifact::LtoIr(nonempty_output(self.lto_ir()?)?),
583 OutputKind::OptixIr => CompilationArtifact::OptixIr(nonempty_output(self.optix_ir()?)?),
584 OutputKind::TileIr => {
585 CompilationArtifact::TileIr(ModuleImage::from_compiler_output(self.tile_ir()?)?)
586 }
587 })
588 }
589}
590
591unsafe extern "C" fn noop_compile_callback(payload: *mut c_void, reserved: *mut c_void) -> i32 {
592 let _ = payload;
593 let _ = reserved;
594 0
595}
596
597unsafe extern "C" fn cancel_if_requested_callback(
598 payload: *mut c_void,
599 reserved: *mut c_void,
600) -> i32 {
601 let _ = reserved;
602 if payload.is_null() {
603 return 0;
604 }
605
606 // SAFETY: the payload is the cancellation flag registered with this callback, which its program keeps alive while the callback is registered.
607 let cancel = unsafe { &*payload.cast::<AtomicBool>() };
608 i32::from(cancel.load(Ordering::Relaxed))
609}
610
611impl Program {
612 // Replaces a cancellation callback with a no-op callback, then releases the flag it read.
613 pub(crate) fn clear_flow_callback(&self) -> Result<()> {
614 // SAFETY: the program handle is live, and the no-op callback reads no payload.
615 unsafe {
616 try_nvrtc!(sys::nvrtcSetFlowCallback(
617 self.handle()?,
618 Some(noop_compile_callback),
619 ptr::null_mut(),
620 ))?;
621 }
622
623 *self.cancel_flag.borrow_mut() = None;
624 Ok(())
625 }
626}