Skip to main content

singe_cuda/
nvvm.rs

1//! NVVM IR compilation and compiler options.
2
3use std::{
4    ffi::{CString, c_char},
5    mem, ptr, result,
6};
7
8use singe_core::{LibraryVersion, impl_enum_display, report_cleanup_failure};
9use singe_cuda_sys::nvvm as sys;
10
11use crate::{
12    architecture::GpuArchitecture,
13    error::{Error, Result},
14    module::ModuleImage,
15    try_nvvm,
16    utility::{bytes_to_string, to_c_ulong, to_i32, to_usize},
17};
18
19/// NVVM IR and debug metadata versions supported by the loaded compiler.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub struct IrVersion {
22    /// Major supported NVVM IR version.
23    pub major: i32,
24    /// Minor supported NVVM IR version.
25    pub minor: i32,
26    /// Major supported debug metadata version.
27    pub debug_major: i32,
28    /// Minor supported debug metadata version.
29    pub debug_minor: i32,
30}
31
32singe_core::wrapper_status! {
33    library = "nvvm",
34    error = Error::Nvvm,
35    raw = sys::nvvmResult,
36    success = NVVM_SUCCESS,
37    absence = singe_cuda_sys::take_absence,
38    check = check_nvvm,
39    unknown = "UNKNOWN_NVVM_STATUS",
40    description = sys::nvvmGetErrorString,
41    /// NVVM result code returned by compiler operations.
42    pub enum Status: u32 {
43        /// The operation completed successfully.
44        Success = NVVM_SUCCESS,
45        /// NVVM could not allocate the required memory.
46        OutOfMemory = NVVM_ERROR_OUT_OF_MEMORY,
47        /// NVVM could not create the program.
48        ProgramCreationFailure = NVVM_ERROR_PROGRAM_CREATION_FAILURE,
49        /// The input IR version is incompatible with the NVVM library.
50        IrVersionMismatch = NVVM_ERROR_IR_VERSION_MISMATCH,
51        /// An input argument is invalid.
52        InvalidInput = NVVM_ERROR_INVALID_INPUT,
53        /// The program handle is invalid.
54        InvalidProgram = NVVM_ERROR_INVALID_PROGRAM,
55        /// The input NVVM IR is invalid.
56        InvalidIr = NVVM_ERROR_INVALID_IR,
57        /// A compilation option is invalid.
58        InvalidOption = NVVM_ERROR_INVALID_OPTION,
59        /// The program contains no IR modules.
60        NoModuleInProgram = NVVM_ERROR_NO_MODULE_IN_PROGRAM,
61        /// NVVM compilation failed; the program log contains diagnostics.
62        Compilation = NVVM_ERROR_COMPILATION,
63        /// The operation was cancelled.
64        Cancelled = NVVM_ERROR_CANCELLED,
65    }
66}
67
68/// Native optimization level for NVVM IR compilation.
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
70#[non_exhaustive]
71pub enum OptimizationLevel {
72    /// Disables compiler optimizations.
73    Zero,
74    /// Enables the native default optimization level.
75    Three,
76}
77
78impl_enum_display!(OptimizationLevel, {
79    Self::Zero => "0",
80    Self::Three => "3",
81});
82
83/// Typed NVVM compiler options.
84/// Unset optional values leave native defaults in effect; raw options are appended after typed options.
85/// Typed compilation and verification reject concrete GPU architecture targets.
86#[derive(Debug, Clone, Default)]
87pub struct CompileOptions<'a> {
88    /// Whether to emit full device debug information.
89    /// Native full debug support requires optimization level zero and IR debug metadata.
90    pub device_debug: bool,
91    /// Optimization effort applied to the input IR.
92    pub optimization_level: Option<OptimizationLevel>,
93    /// Virtual GPU architecture target.
94    /// Typed compilation and verification reject a concrete architecture.
95    pub gpu_architecture: Option<GpuArchitecture>,
96    /// Whether single-precision denormal values are flushed to zero.
97    pub flush_to_zero: Option<bool>,
98    /// Whether single-precision square roots use the precise native implementation.
99    pub precise_square_root: Option<bool>,
100    /// Whether single-precision division uses the precise native implementation.
101    pub precise_division: Option<bool>,
102    /// Whether floating-point multiply and add operations may be contracted.
103    pub fma: Option<bool>,
104    /// Switch case-density threshold, in percent, from zero through 101.
105    /// The builder clamps larger values to 101.
106    pub jump_table_density: Option<u8>,
107    /// Whether to generate link-time intermediate representation instead of PTX.
108    pub generate_lto: bool,
109    /// Additional native options appended after the typed options.
110    pub raw_options: Vec<&'a str>,
111}
112
113impl<'a> CompileOptions<'a> {
114    /// Creates an empty compiler option set that leaves native defaults in effect.
115    #[must_use]
116    pub const fn new() -> Self {
117        Self {
118            device_debug: false,
119            optimization_level: None,
120            gpu_architecture: None,
121            flush_to_zero: None,
122            precise_square_root: None,
123            precise_division: None,
124            fma: None,
125            jump_table_density: None,
126            generate_lto: false,
127            raw_options: Vec::new(),
128        }
129    }
130
131    /// Enables or disables full device debug information.
132    /// Native full debug support requires optimization level zero and IR debug metadata.
133    #[must_use]
134    pub fn device_debug(mut self, value: bool) -> Self {
135        self.device_debug = value;
136        self
137    }
138
139    /// Sets the native optimization level.
140    #[must_use]
141    pub fn optimization_level(mut self, value: OptimizationLevel) -> Self {
142        self.optimization_level = Some(value);
143        self
144    }
145
146    /// Sets the virtual GPU architecture target.
147    /// Concrete targets are rejected when typed options are compiled or verified.
148    #[must_use]
149    pub fn gpu_architecture(mut self, value: GpuArchitecture) -> Self {
150        self.gpu_architecture = Some(value);
151        self
152    }
153
154    /// Controls whether single-precision denormal values are flushed to zero.
155    #[must_use]
156    pub fn flush_to_zero(mut self, value: bool) -> Self {
157        self.flush_to_zero = Some(value);
158        self
159    }
160
161    /// Selects precise or approximate single-precision square roots.
162    #[must_use]
163    pub fn precise_square_root(mut self, value: bool) -> Self {
164        self.precise_square_root = Some(value);
165        self
166    }
167
168    /// Selects precise or approximate single-precision division.
169    #[must_use]
170    pub fn precise_division(mut self, value: bool) -> Self {
171        self.precise_division = Some(value);
172        self
173    }
174
175    /// Controls contraction of floating-point multiply and add operations.
176    #[must_use]
177    pub fn fma(mut self, value: bool) -> Self {
178        self.fma = Some(value);
179        self
180    }
181
182    /// Sets the switch case-density percentage threshold, clamping values above 101 to 101.
183    #[must_use]
184    pub fn jump_table_density(mut self, value: u8) -> Self {
185        self.jump_table_density = Some(value.min(101));
186        self
187    }
188
189    /// Selects link-time intermediate representation generation instead of PTX.
190    #[must_use]
191    pub fn generate_lto(mut self, value: bool) -> Self {
192        self.generate_lto = value;
193        self
194    }
195
196    /// Appends a native option string after the typed options.
197    #[must_use]
198    pub fn raw_option(mut self, value: &'a str) -> Self {
199        self.raw_options.push(value);
200        self
201    }
202
203    /// Renders compiler settings as owned native option strings without validating or compiling them.
204    #[must_use]
205    pub fn as_arguments(&self) -> Vec<String> {
206        let mut arguments = Vec::new();
207        if self.device_debug {
208            arguments.push(String::from("-g"));
209        }
210
211        if let Some(value) = self.optimization_level {
212            arguments.push(format!("-opt={value}"));
213        }
214
215        if let Some(value) = self.gpu_architecture {
216            arguments.push(format!("-arch={value}"));
217        }
218
219        if let Some(value) = self.flush_to_zero {
220            arguments.push(format!("-ftz={}", flag_bit(value)));
221        }
222
223        if let Some(value) = self.precise_square_root {
224            arguments.push(format!("-prec-sqrt={}", flag_bit(value)));
225        }
226
227        if let Some(value) = self.precise_division {
228            arguments.push(format!("-prec-div={}", flag_bit(value)));
229        }
230
231        if let Some(value) = self.fma {
232            arguments.push(format!("-fma={}", flag_bit(value)));
233        }
234
235        if let Some(value) = self.jump_table_density {
236            arguments.push(format!("-jump-table-density={value}"));
237        }
238
239        if self.generate_lto {
240            arguments.push(String::from("-gen-lto"));
241        }
242
243        arguments.extend(self.raw_options.iter().map(|value| (*value).to_string()));
244        arguments
245    }
246
247    fn validate(&self) -> Result<()> {
248        if let Some(architecture) = self.gpu_architecture
249            && !architecture.is_virtual()
250        {
251            return Err(Error::UnsupportedArchitecture {
252                target: architecture.to_string(),
253            });
254        }
255        Ok(())
256    }
257}
258
259/// Borrowed NVVM IR bytes and a module name for addition to a compiler program.
260#[derive(Debug, Clone, Copy)]
261pub struct Module<'a> {
262    /// NVVM IR bytes in the representation accepted by the selected module-addition API.
263    pub ir: &'a [u8],
264    /// Module name used in compiler diagnostics.
265    /// Interior NUL bytes are rejected when adding it.
266    pub name: &'a str,
267}
268
269/// Owned NVVM program containing IR modules to link, verify, and compile.
270/// The native program is destroyed when this wrapper is dropped.
271#[derive(Debug)]
272pub struct Program {
273    handle: sys::nvvmProgram,
274}
275
276/// Raw ownership of an NVVM program.
277///
278/// Destroy `handle` with NVVM, or re-adopt the value with [`Program::from_raw`].
279#[derive(Debug)]
280pub struct RawProgram {
281    /// Native program handle.
282    pub handle: sys::nvvmProgram,
283}
284
285impl Program {
286    /// Creates an empty native NVVM compiler program.
287    ///
288    /// # Errors
289    ///
290    /// Returns an error if NVVM cannot create the program or returns a null handle.
291    pub fn create() -> Result<Self> {
292        let mut handle = ptr::null_mut();
293        // SAFETY: `handle` is a local output.
294        unsafe {
295            try_nvvm!(sys::nvvmCreateProgram(&raw mut handle))?;
296        }
297
298        if handle.is_null() {
299            return Err(Error::NullHandle);
300        }
301        Ok(Self { handle })
302    }
303
304    /// Takes ownership of a raw NVVM program.
305    ///
306    /// # Safety
307    ///
308    /// `raw.handle` must be a valid NVVM program that is not owned by any other wrapper.
309    /// The returned wrapper destroys it on drop.
310    ///
311    /// # Errors
312    ///
313    /// Returns an error if `raw.handle` is null.
314    #[expect(
315        clippy::needless_pass_by_value,
316        reason = "taking the raw owner by value transfers ownership of its handle"
317    )]
318    pub unsafe fn from_raw(raw: RawProgram) -> Result<Self> {
319        if raw.handle.is_null() {
320            return Err(Error::NullHandle);
321        }
322
323        Ok(Self { handle: raw.handle })
324    }
325
326    /// Adds an NVVM IR module in text or bitcode form to the program.
327    ///
328    /// # Errors
329    ///
330    /// Returns an error if the IR byte slice is empty, the module name contains an interior NUL, or NVVM rejects the module or program.
331    pub fn add_module(&mut self, module: Module<'_>) -> Result<()> {
332        self.add_module_raw(&module, false)
333    }
334
335    /// Adds a bitcode module whose symbols are loaded only as required by eagerly added modules.
336    /// A program must contain at least one eagerly added module.
337    ///
338    /// # Errors
339    ///
340    /// Returns an error if the IR byte slice is empty, the module name contains an interior NUL, or NVVM rejects the module or program.
341    pub fn lazy_add_module(&mut self, module: Module<'_>) -> Result<()> {
342        self.add_module_raw(&module, true)
343    }
344
345    /// Validates `options`, links the added IR modules, and compiles the program.
346    /// Output is PTX unless link-time IR generation is requested.
347    ///
348    /// # Errors
349    ///
350    /// Returns an error if `options.gpu_architecture` is a concrete GPU target, an option contains an interior NUL, the option count does not fit an `i32`, or NVVM rejects the options or fails compilation.
351    /// Compiler diagnostics are available from [`Self::log`].
352    pub fn compile(&self, options: &CompileOptions<'_>) -> Result<()> {
353        options.validate()?;
354        let arguments = options.as_arguments();
355        let argument_refs = arguments.iter().map(String::as_str).collect::<Vec<_>>();
356        self.compile_raw(sys::nvvmCompileProgram, &argument_refs)
357    }
358
359    /// Validates `options` and verifies the added NVVM IR modules.
360    ///
361    /// # Errors
362    ///
363    /// Returns an error if `options.gpu_architecture` is a concrete GPU target, an option contains an interior NUL, the option count does not fit an `i32`, or NVVM rejects the options or finds invalid IR.
364    /// Verification diagnostics are available from [`Self::log`].
365    pub fn verify(&self, options: &CompileOptions<'_>) -> Result<()> {
366        options.validate()?;
367        let arguments = options.as_arguments();
368        let argument_refs = arguments.iter().map(String::as_str).collect::<Vec<_>>();
369        self.compile_raw(sys::nvvmVerifyProgram, &argument_refs)
370    }
371
372    /// Returns owned bytes of the last compiled PTX or link-time IR output.
373    /// Native PTX output includes its trailing NUL byte.
374    ///
375    /// # Errors
376    ///
377    /// Returns an error if NVVM cannot query or copy the requested output, or the returned byte count cannot be represented as `usize`.
378    pub fn compiled_result(&self) -> Result<Vec<u8>> {
379        self.bytes(sys::nvvmGetCompiledResultSize, sys::nvvmGetCompiledResult)
380    }
381
382    /// Copies the last compiled PTX output into an owned module image.
383    ///
384    /// # Errors
385    ///
386    /// Returns an error if NVVM cannot query or copy the requested output, the returned byte count cannot be represented as `usize`, or the output is empty.
387    /// Returns `Error::InteriorNul` if the output contains a NUL byte before its end, which rejects binary link-time IR.
388    pub fn compiled_image(&self) -> Result<ModuleImage<'static>> {
389        ModuleImage::from_ptx(self.compiled_result()?)
390    }
391
392    /// Interprets the last compiled output as text, removing a trailing NUL and replacing invalid UTF-8 lossily.
393    /// Intended for PTX output.
394    ///
395    /// # Errors
396    ///
397    /// Returns an error if NVVM cannot query or copy the requested output, or the returned byte count cannot be represented as `usize`.
398    pub fn compiled_string(&self) -> Result<String> {
399        Ok(bytes_to_string(self.compiled_result()?))
400    }
401
402    /// Returns the compiler or verification log, removing a trailing NUL and replacing invalid UTF-8 lossily.
403    ///
404    /// # Errors
405    ///
406    /// Returns an error if NVVM cannot query or copy the requested output, or the returned byte count cannot be represented as `usize`.
407    pub fn log(&self) -> Result<String> {
408        Ok(bytes_to_string(self.bytes(
409            sys::nvvmGetProgramLogSize,
410            sys::nvvmGetProgramLog,
411        )?))
412    }
413
414    /// Borrows the native program handle without transferring ownership.
415    /// It remains valid until the wrapper is dropped or converted with [`Self::into_raw`].
416    #[must_use]
417    pub const fn as_raw(&self) -> sys::nvvmProgram {
418        self.handle
419    }
420
421    /// Transfers ownership of the NVVM program to the caller.
422    ///
423    /// The caller becomes responsible for destroying it.
424    #[must_use]
425    pub fn into_raw(self) -> RawProgram {
426        let handle = self.handle;
427        mem::forget(self);
428        RawProgram { handle }
429    }
430
431    fn add_module_raw(&mut self, module: &Module<'_>, lazy: bool) -> Result<()> {
432        if module.ir.is_empty() {
433            return Err(Error::empty("nvvm module ir"));
434        }
435
436        let name = CString::new(module.name)?;
437        let function = if lazy {
438            sys::nvvmLazyAddModuleToProgram
439        } else {
440            sys::nvvmAddModuleToProgram
441        };
442
443        let size = to_c_ulong(module.ir.len(), "nvvm module size")?;
444        // SAFETY: `self` owns the live program exclusively, and the counted IR bytes and NUL-terminated name are borrowed for the call.
445        unsafe {
446            try_nvvm!(function(
447                self.handle,
448                module.ir.as_ptr().cast(),
449                size,
450                name.as_ptr(),
451            ))
452        }
453    }
454
455    fn compile_raw(
456        &self,
457        function: unsafe extern "C" fn(
458            sys::nvvmProgram,
459            i32,
460            *mut *const c_char,
461        ) -> sys::nvvmResult,
462        options: &[&str],
463    ) -> Result<()> {
464        let options = options
465            .iter()
466            .map(|option| CString::new(*option))
467            .collect::<result::Result<Vec<_>, _>>()?;
468        let mut option_ptrs = options
469            .iter()
470            .map(|value| value.as_ptr())
471            .collect::<Vec<_>>();
472
473        // SAFETY: `self` owns the live program, and `option_ptrs` holds the counted NUL-terminated options in `options`, which outlive the call.
474        unsafe {
475            try_nvvm!(function(
476                self.handle,
477                to_i32(option_ptrs.len(), "NVVM option count")?,
478                if option_ptrs.is_empty() {
479                    ptr::null_mut()
480                } else {
481                    option_ptrs.as_mut_ptr()
482                },
483            ))
484        }
485    }
486
487    fn bytes(
488        &self,
489        get_size: unsafe extern "C" fn(sys::nvvmProgram, *mut u64) -> sys::nvvmResult,
490        get_data: unsafe extern "C" fn(sys::nvvmProgram, *mut c_char) -> sys::nvvmResult,
491    ) -> Result<Vec<u8>> {
492        let mut size = 0;
493        // SAFETY: `self` owns the live program, and `size` is a local output.
494        unsafe {
495            try_nvvm!(get_size(self.handle, &raw mut size))?;
496        }
497
498        let mut bytes = vec![0u8; to_usize(size, "NVVM output byte count")?];
499        if bytes.is_empty() {
500            return Ok(bytes);
501        }
502
503        // SAFETY: `bytes` holds the `size` bytes NVVM reported for the same output of the live program.
504        unsafe {
505            try_nvvm!(get_data(self.handle, bytes.as_mut_ptr().cast()))?;
506        }
507        Ok(bytes)
508    }
509}
510
511impl Drop for Program {
512    fn drop(&mut self) {
513        // SAFETY: this wrapper owns the non-null program, and NVVM nulls the handle field it destroys.
514        unsafe {
515            if !self.handle.is_null()
516                && let Err(error) = try_nvvm!(sys::nvvmDestroyProgram(&raw mut self.handle))
517            {
518                report_cleanup_failure("destroy", "nvvm program", &error);
519            }
520        }
521    }
522}
523
524/// Returns the loaded NVVM compiler library version.
525///
526/// # Errors
527///
528/// Returns an error if NVVM cannot report its library version.
529pub fn version() -> Result<LibraryVersion> {
530    let mut major = 0;
531    let mut minor = 0;
532    // SAFETY: `major` and `minor` are local outputs.
533    unsafe {
534        try_nvvm!(sys::nvvmVersion(&raw mut major, &raw mut minor))?;
535    }
536    LibraryVersion::from_properties(major, minor, 0)
537        .ok_or_else(|| Error::out_of_range("nvvm version"))
538}
539
540/// Returns the NVVM IR and debug metadata versions supported by the loaded compiler.
541///
542/// # Errors
543///
544/// Returns an error if NVVM cannot report its supported IR versions.
545pub fn ir_version() -> Result<IrVersion> {
546    let mut major = 0;
547    let mut minor = 0;
548    let mut debug_major = 0;
549    let mut debug_minor = 0;
550    // SAFETY: the four versions are local outputs.
551    unsafe {
552        try_nvvm!(sys::nvvmIRVersion(
553            &raw mut major,
554            &raw mut minor,
555            &raw mut debug_major,
556            &raw mut debug_minor,
557        ))?;
558    }
559    Ok(IrVersion {
560        major,
561        minor,
562        debug_major,
563        debug_minor,
564    })
565}
566
567/// Returns the LLVM major version supported for a virtual GPU architecture.
568///
569/// # Errors
570///
571/// Returns an error if `architecture` is a concrete target or NVVM cannot report the version.
572pub fn llvm_version(architecture: GpuArchitecture) -> Result<i32> {
573    if !architecture.is_virtual() {
574        return Err(Error::UnsupportedArchitecture {
575            target: architecture.to_string(),
576        });
577    }
578    llvm_version_for_architecture(&architecture.to_string())
579}
580
581/// Returns the LLVM major version supported for the supplied native architecture string.
582///
583/// # Errors
584///
585/// Returns an error if `architecture` contains an interior NUL or NVVM rejects the architecture or version query.
586pub fn llvm_version_for_architecture(architecture: &str) -> Result<i32> {
587    let architecture = CString::new(architecture)?;
588    let mut major = 0;
589    // SAFETY: `architecture` is a NUL-terminated string borrowed for the call, and `major` is a local output.
590    unsafe {
591        try_nvvm!(sys::nvvmLLVMVersion(architecture.as_ptr(), &raw mut major,))?;
592    }
593    Ok(major)
594}
595
596fn flag_bit(value: bool) -> u8 {
597    u8::from(value)
598}
599
600#[cfg(test)]
601mod tests {
602    use super::*;
603
604    #[test]
605    fn test_compile_options_build_expected_arguments() {
606        let options = CompileOptions::new()
607            .device_debug(true)
608            .optimization_level(OptimizationLevel::Zero)
609            .gpu_architecture(GpuArchitecture::Compute90)
610            .flush_to_zero(true)
611            .precise_square_root(false)
612            .precise_division(true)
613            .fma(false)
614            .jump_table_density(200)
615            .generate_lto(true)
616            .raw_option("-custom");
617
618        assert_eq!(
619            options.as_arguments(),
620            vec![
621                "-g",
622                "-opt=0",
623                "-arch=compute_90",
624                "-ftz=1",
625                "-prec-sqrt=0",
626                "-prec-div=1",
627                "-fma=0",
628                "-jump-table-density=101",
629                "-gen-lto",
630                "-custom",
631            ]
632        );
633    }
634
635    #[test]
636    fn test_version_queries_are_available() {
637        let version = version().unwrap();
638        assert!(version.major() > 0);
639
640        let ir_version = ir_version().unwrap();
641        assert!(ir_version.major > 0);
642
643        let llvm_version = llvm_version(GpuArchitecture::Compute90).unwrap();
644        assert!(llvm_version > 0);
645    }
646
647    #[test]
648    fn test_real_architecture_is_rejected_for_nvvm_options() {
649        let options = CompileOptions::new().gpu_architecture(GpuArchitecture::Sm90);
650        assert!(matches!(
651            options.validate(),
652            Err(Error::UnsupportedArchitecture { .. })
653        ));
654        assert!(matches!(
655            llvm_version(GpuArchitecture::Sm90),
656            Err(Error::UnsupportedArchitecture { .. })
657        ));
658    }
659}