Skip to main content

singe_cuda/nvrtc/
mod.rs

1//! Runtime compilation of CUDA source and retrieval of compilation artifacts.
2
3mod cache;
4mod context;
5mod library;
6mod options;
7mod program;
8
9use singe_core::LibraryVersion;
10use singe_cuda_sys::nvrtc as sys;
11
12pub use self::{
13    cache::{CompiledModule, ModuleSource, compile_cached},
14    library::library_path,
15    options::{
16        CompileOptions, CppDialect, FastCompileLevel, MacroDefinition, OptimizationInfoKind,
17        TileCompilation, WarningAsErrorKind,
18    },
19    program::{CompilationArtifact, Header, OutputKind, Program, RawProgram},
20};
21use crate::{
22    error::{Error, Result},
23    try_nvrtc,
24    utility::{to_c_ulong, to_usize},
25};
26
27singe_core::wrapper_status! {
28    library = "nvrtc",
29    error = Error::Nvrtc,
30    raw = sys::nvrtcResult,
31    success = NVRTC_SUCCESS,
32    absence = singe_cuda_sys::take_absence,
33    check = check_nvrtc,
34    unknown = "UNKNOWN_NVRTC_STATUS",
35    description = sys::nvrtcGetErrorString,
36    /// NVRTC result code returned by compiler operations.
37    pub enum Status: u32 {
38        /// The operation completed successfully.
39        Success = NVRTC_SUCCESS,
40        /// NVRTC could not allocate the required memory.
41        OutOfMemory = NVRTC_ERROR_OUT_OF_MEMORY,
42        /// NVRTC could not create the program.
43        ProgramCreationFailure = NVRTC_ERROR_PROGRAM_CREATION_FAILURE,
44        /// An input argument is invalid.
45        InvalidInput = NVRTC_ERROR_INVALID_INPUT,
46        /// The program handle is invalid.
47        InvalidProgram = NVRTC_ERROR_INVALID_PROGRAM,
48        /// A compilation option is invalid.
49        InvalidOption = NVRTC_ERROR_INVALID_OPTION,
50        /// CUDA source compilation failed; the program log contains diagnostics.
51        Compilation = NVRTC_ERROR_COMPILATION,
52        /// An NVRTC built-in operation failed.
53        BuiltinOperationFailure = NVRTC_ERROR_BUILTIN_OPERATION_FAILURE,
54        /// A name expression cannot be added after compilation.
55        NoNameExpressionsAfterCompilation = NVRTC_ERROR_NO_NAME_EXPRESSIONS_AFTER_COMPILATION,
56        /// A lowered name was requested before compiling the program.
57        NoLoweredNamesBeforeCompilation = NVRTC_ERROR_NO_LOWERED_NAMES_BEFORE_COMPILATION,
58        /// The name expression is invalid.
59        NameExpressionNotValid = NVRTC_ERROR_NAME_EXPRESSION_NOT_VALID,
60        /// An internal NVRTC error occurred.
61        InternalError = NVRTC_ERROR_INTERNAL_ERROR,
62        /// NVRTC could not write its compilation timing file.
63        TimeFileWriteFailed = NVRTC_ERROR_TIME_FILE_WRITE_FAILED,
64        /// No precompiled-header creation was attempted.
65        /// PCH processing may not have been requested, or automatic PCH processing chose not to create a file.
66        NoPchCreateAttempted = NVRTC_ERROR_NO_PCH_CREATE_ATTEMPTED,
67        /// The precompiled-header heap was exhausted.
68        /// Query the required size and enlarge the heap before retrying compilation with a new program.
69        PchCreateHeapExhausted = NVRTC_ERROR_PCH_CREATE_HEAP_EXHAUSTED,
70        /// An error prevented the precompiled-header file from being created.
71        PchCreate = NVRTC_ERROR_PCH_CREATE,
72        /// The operation was cancelled.
73        Cancelled = NVRTC_ERROR_CANCELLED,
74        /// NVRTC could not write its compilation time-trace file.
75        TimeTraceFileWriteFailed = NVRTC_ERROR_TIME_TRACE_FILE_WRITE_FAILED,
76    }
77}
78
79/// Returns the CUDA Runtime Compilation version.
80///
81/// # Errors
82///
83/// Returns an error if NVRTC cannot report its version.
84pub fn version() -> Result<LibraryVersion> {
85    let mut major = 0;
86    let mut minor = 0;
87    // SAFETY: `major` and `minor` are local outputs.
88    unsafe {
89        try_nvrtc!(sys::nvrtcVersion(&raw mut major, &raw mut minor))?;
90    }
91    LibraryVersion::from_properties(major, minor, 0)
92        .ok_or_else(|| Error::out_of_range("nvrtc version"))
93}
94
95/// Returns the GPU architecture numbers supported by the loaded NVRTC library.
96///
97/// # Errors
98///
99/// Returns an error if NVRTC cannot report the supported architecture count or fill the architecture list.
100pub fn supported_architectures() -> Result<Vec<i32>> {
101    let mut count = 0;
102    // SAFETY: `count` is a local output.
103    unsafe {
104        try_nvrtc!(sys::nvrtcGetNumSupportedArchs(&raw mut count))?;
105    }
106
107    let mut architectures = vec![0; to_usize(count, "NVRTC supported architecture count")?];
108    if architectures.is_empty() {
109        return Ok(Vec::new());
110    }
111
112    // SAFETY: `architectures` holds the `count` entries NVRTC reported.
113    unsafe {
114        try_nvrtc!(sys::nvrtcGetSupportedArchs(architectures.as_mut_ptr()))?;
115    }
116    Ok(architectures)
117}
118
119/// Returns the current size of the PCH heap.
120///
121/// # Errors
122///
123/// Returns an error if NVRTC cannot report the PCH heap size.
124pub fn pch_heap_size() -> Result<usize> {
125    let mut size = 0;
126    // SAFETY: `size` is a local output.
127    unsafe {
128        try_nvrtc!(sys::nvrtcGetPCHHeapSize(&raw mut size))?;
129    }
130    to_usize(size, "NVRTC output byte count")
131}
132
133/// Sets the size of the PCH heap.
134///
135/// The requested size may be rounded up to a platform-dependent alignment, such as the page size.
136/// If the PCH heap has already been allocated, NVRTC frees it and allocates a new heap.
137///
138/// # Errors
139///
140/// Returns an error if NVRTC rejects the requested PCH heap size.
141pub fn set_pch_heap_size(size: usize) -> Result<()> {
142    let size = to_c_ulong(size, "PCH heap size")?;
143    // SAFETY: `nvrtcSetPCHHeapSize` takes only the size and reallocates NVRTC's own heap.
144    unsafe { try_nvrtc!(sys::nvrtcSetPCHHeapSize(size)) }
145}
146
147#[cfg(all(test, feature = "testing"))]
148mod tests {
149    use std::sync::{Arc, atomic::AtomicBool};
150
151    use super::*;
152    use crate::{
153        architecture::GpuArchitecture, device::Device, error::Result, jit::JitOptions,
154        memory::DeviceMemory, module::LaunchConfig, stream::StreamOptions, testing,
155    };
156
157    fn current_device_sm_architecture() -> Result<GpuArchitecture> {
158        let properties = Device::current()?.properties()?;
159        Ok(match (properties.major, properties.minor) {
160            (7, 5) => GpuArchitecture::Sm75,
161            (8, 0) => GpuArchitecture::Sm80,
162            (8, 6) => GpuArchitecture::Sm86,
163            (8, 7) => GpuArchitecture::Sm87,
164            (8, 9) => GpuArchitecture::Sm89,
165            (9, 0) => GpuArchitecture::Sm90,
166            (10, 0) => GpuArchitecture::Sm100,
167            (10, 1) => GpuArchitecture::Sm101,
168            (10, 3) => GpuArchitecture::Sm103,
169            (12, 0) => GpuArchitecture::Sm120,
170            (12, 1) => GpuArchitecture::Sm121,
171            (major, minor) => panic!("unsupported device architecture sm_{major}{minor}"),
172        })
173    }
174
175    #[test]
176    fn test_version_is_available() {
177        let version = version().unwrap();
178        assert_ne!(version.major(), 0);
179    }
180
181    #[test]
182    fn test_supported_architectures_are_sorted() {
183        let architectures = supported_architectures().unwrap();
184        assert!(!architectures.is_empty());
185        assert!(
186            architectures
187                .windows(2)
188                .all(|window| window[0] <= window[1])
189        );
190    }
191
192    #[test]
193    fn test_compile_options_build_expected_arguments() {
194        let arguments = CompileOptions::new()
195            .gpu_architecture(GpuArchitecture::Compute80)
196            .device_debug(true)
197            .generate_line_info(true)
198            .define_macro(MacroDefinition::WithValue {
199                name: "FOO",
200                value: "42",
201            })
202            .include_path("include")
203            .cpp_dialect(CppDialect::Cpp20)
204            .warning_as_error(WarningAsErrorKind::Reorder)
205            .diag_suppress(177)
206            .raw_option("--custom-flag")
207            .as_arguments();
208
209        assert_eq!(
210            arguments,
211            vec![
212                "--gpu-architecture=compute_80",
213                "--device-debug",
214                "--generate-line-info",
215                "--define-macro=FOO=42",
216                "--include-path=include",
217                "--std=c++20",
218                "--warning-as-error=reorder",
219                "--diag-suppress=177",
220                "--custom-flag",
221            ]
222        );
223    }
224
225    #[test]
226    fn test_compiles_to_ptx() {
227        let program = Program::from_source(
228            r#"
229            extern "C" __global__ void saxpy(float a, const float* x, const float* y, float* out, size_t n) {
230                size_t tid = blockIdx.x * blockDim.x + threadIdx.x;
231                if (tid < n) {
232                    out[tid] = a * x[tid] + y[tid];
233                }
234            }
235            "#,
236        )
237        .with_name("saxpy.cu");
238        let options = CompileOptions::new()
239            .gpu_architecture(GpuArchitecture::Compute80)
240            .generate_line_info(true);
241        program.compile(&options).unwrap();
242
243        let ptx = program.ptx_string().unwrap();
244        assert!(ptx.contains(".visible .entry saxpy"));
245    }
246
247    #[test]
248    fn test_compile_with_cancel_flag_succeeds_when_not_cancelled() {
249        let _device = testing::bootstrap().unwrap();
250        let cancel = Arc::new(AtomicBool::new(false));
251        let program = Program::from_source(
252            r#"
253            extern "C" __global__ void noop() {}
254            "#,
255        )
256        .with_name("noop.cu");
257        let options = CompileOptions::new()
258            .gpu_architecture(GpuArchitecture::Compute80)
259            .cancel_flag(cancel);
260
261        program.compile(&options).unwrap();
262        assert!(program.ptx_string().unwrap().contains("noop"));
263    }
264
265    #[test]
266    fn test_clear_flow_callback_is_allowed_before_compilation() {
267        let program =
268            Program::from_source("extern \"C\" __global__ void noop() {}").with_name("noop.cu");
269        program.clear_flow_callback().unwrap();
270    }
271
272    #[test]
273    fn test_cubin_artifact_loads_as_module() {
274        let test_device = testing::bootstrap().unwrap();
275        let context = Arc::clone(test_device.context());
276        let program = Program::from_source(
277            r#"
278            extern "C" __global__ void saxpy(float a, const float* x, const float* y, float* out, size_t n) {
279                size_t tid = blockIdx.x * blockDim.x + threadIdx.x;
280                if (tid < n) {
281                    out[tid] = a * x[tid] + y[tid];
282                }
283            }
284            "#,
285        )
286        .with_name("saxpy_module.cu");
287        let architecture = current_device_sm_architecture().unwrap();
288        let options = CompileOptions::new().gpu_architecture(architecture);
289        program.compile(&options).unwrap();
290
291        let module = context
292            .load_nvrtc_module(&program, OutputKind::Cubin, JitOptions::default())
293            .unwrap();
294        assert!(module.function("saxpy").is_ok());
295    }
296
297    #[test]
298    fn test_cubin_artifact_loads_as_module_with_jit_options() {
299        let test_device = testing::bootstrap().unwrap();
300        let context = Arc::clone(test_device.context());
301        let program = Program::from_source(
302            r#"
303            extern "C" __global__ void noop() {}
304            "#,
305        )
306        .with_name("noop_module_jit.cu");
307        let architecture = current_device_sm_architecture().unwrap();
308        let options = CompileOptions::new().gpu_architecture(architecture);
309        program.compile(&options).unwrap();
310
311        let mut info_log = [0u8; 1024];
312        let mut error_log = [0u8; 1024];
313        let jit_options = JitOptions::default()
314            .with_generate_line_info(true)
315            .with_info_log(&mut info_log)
316            .with_error_log(&mut error_log);
317
318        let module = context
319            .load_nvrtc_module(&program, OutputKind::Cubin, jit_options)
320            .unwrap();
321        assert!(module.function("noop").is_ok());
322    }
323
324    #[test]
325    fn test_compiles_loads_launches_and_reads_back_results() {
326        let test_device = testing::bootstrap().unwrap();
327        let context = Arc::clone(test_device.context());
328
329        let input = vec![1.0f32, 2.0, 3.5, -4.0, 8.25];
330        let mut output = vec![0.0f32; input.len()];
331        let scalar = 2.5f32;
332        let input_device = DeviceMemory::from_slice(&context, &input).unwrap();
333        let output_device = DeviceMemory::<f32>::zeroed(&context, output.len()).unwrap();
334        let length = input.len();
335
336        let program = Program::from_source(
337            r#"
338            extern "C" __global__ void scale_add(const float* input, float* output, float alpha, size_t len) {
339                size_t i = blockIdx.x * blockDim.x + threadIdx.x;
340                if (i < len) {
341                    output[i] = input[i] * alpha + 1.0f;
342                }
343            }
344            "#,
345        )
346        .with_name("scale_add.cu");
347        let architecture = current_device_sm_architecture().unwrap();
348        let compile_options = CompileOptions::new().gpu_architecture(architecture);
349        program.compile(&compile_options).unwrap();
350
351        let module = context
352            .load_nvrtc_module(&program, OutputKind::Cubin, JitOptions::default())
353            .unwrap();
354        let function = module.function("scale_add").unwrap();
355
356        let config = LaunchConfig::for_1d_grid(input.len(), 128);
357        let input_ptr = input_device.as_ptr();
358        let mut output_ptr = output_device.as_mut_ptr();
359
360        let stream = context.create_stream(StreamOptions::default()).unwrap();
361        // SAFETY: the compiled declaration matches these arguments, both allocations cover `length` elements, and they stay exclusively available until the stream synchronizes.
362        unsafe {
363            function.launch_async(
364                &config,
365                (&input_ptr, &mut output_ptr, &scalar, &length),
366                &stream,
367            )
368        }
369        .unwrap();
370        stream.synchronize().unwrap();
371        output_device.copy_to_host(&mut output).unwrap();
372
373        let expected = input
374            .iter()
375            .map(|value| value * scalar + 1.0)
376            .collect::<Vec<_>>();
377        assert_eq!(output, expected);
378    }
379
380    #[test]
381    fn test_cubin_artifact_loads_as_library() {
382        let test_device = testing::bootstrap().unwrap();
383        let context = Arc::clone(test_device.context());
384        let program = Program::from_source(
385            r#"
386            extern "C" __global__ void noop() {}
387            "#,
388        )
389        .with_name("noop_library.cu");
390        let architecture = current_device_sm_architecture().unwrap();
391        let options = CompileOptions::new().gpu_architecture(architecture);
392        program.compile(&options).unwrap();
393
394        let library = context
395            .load_nvrtc_library(&program, OutputKind::Cubin, JitOptions::default())
396            .unwrap();
397        assert!(library.kernel_count().unwrap() >= 1);
398    }
399
400    #[test]
401    fn test_lto_ir_artifact_is_available_when_requested() {
402        let program = Program::from_source(
403            r#"
404            extern "C" __global__ void noop() {}
405            "#,
406        )
407        .with_name("noop_lto.cu");
408        let options = CompileOptions::new().dlink_time_optimization(true);
409        program.compile(&options).unwrap();
410
411        let artifact = program.artifact(OutputKind::LtoIr).unwrap();
412        assert!(!artifact.as_bytes().is_empty());
413        let ptx = program.artifact(OutputKind::Ptx).unwrap();
414        assert!(!ptx.as_bytes().is_empty());
415    }
416
417    #[test]
418    fn test_optix_ir_artifact_is_available_when_requested() {
419        let program = Program::from_source(
420            r#"
421            extern "C" __global__ void noop() {}
422            "#,
423        )
424        .with_name("noop_optix.cu");
425        let options = CompileOptions::new().optix_ir(true);
426        program.compile(&options).unwrap();
427
428        let artifact = program.artifact(OutputKind::OptixIr).unwrap();
429        assert!(!artifact.as_bytes().is_empty());
430        let ptx = program.artifact(OutputKind::Ptx).unwrap();
431        assert!(!ptx.as_bytes().is_empty());
432    }
433
434    #[test]
435    fn test_cubin_artifact_requires_real_architecture() {
436        let program = Program::from_source(
437            r#"
438            extern "C" __global__ void noop() {}
439            "#,
440        )
441        .with_name("noop_cubin.cu");
442        let options = CompileOptions::new().gpu_architecture(GpuArchitecture::Compute80);
443        program.compile(&options).unwrap();
444
445        assert!(program.artifact(OutputKind::Cubin).is_err());
446    }
447}