nvrtc

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 16 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package nvrtc provides low-level Go bindings for NVIDIA Runtime Compilation (NVRTC).

NVRTC compiles CUDA C++ source code to PTX, cubin, or LTO-IR at runtime, enabling just-in-time kernel compilation without a separate nvcc invocation.

The central type is Program. Create one with CreateProgram, compile with Program.Compile, and retrieve output with Program.PTX or Program.CUBIN. Clean up with Program.Destroy.

This package provides bindings generated from nvrtc.h using github.com/ebitengine/purego for cgo-free dynamic loading of libnvrtc. Functions returning a C status report errors wrapping nvrtcResult with descriptive messages from nvrtcGetErrorString.

Load opens the path it is given. With an empty path it opens the path in NVRTC_LIB_PATH, if that is set. A path named either way is the only one tried: if it does not load, Load returns the error.

Otherwise Load, or the first call that needs the library, tries in order:

  1. the copy in the toolkit that CUDA_HOME names, then the one that CUDA_PATH names
  2. the system library names, which the dynamic loader resolves
  3. the copy in each installed /usr/local/cuda-N.M toolkit, newest first, then /usr/local/cuda
  4. the system library names in the directories pkg-config reports for nvrtc

A library whose version these bindings do not accept is skipped.

Name Expressions

Compilation

Program Management

Bundled Headers

Output Retrieval

Architecture Queries

Version Queries

  • Version: Version sets the output parameters major and minor with the CUDA Runtime Compilation version number.

Other

Example

Example compiles a CUDA kernel to PTX at runtime. It returns early when the NVRTC library is not available. The resulting PTX can be loaded and launched with the driver package. It has no Output comment, so it is compiled but not run: what it prints depends on the host's NVRTC.

package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/nvrtc"
)

func main() {
	major, minor, err := nvrtc.Version()
	if err != nil {
		fmt.Println("NVRTC unavailable:", err)
		return
	}

	const src = `
extern "C" __global__ void saxpy(float a, float *x, float *y, int n) {
	int i = blockIdx.x * blockDim.x + threadIdx.x;
	if (i < n) y[i] = a*x[i] + y[i];
}`
	prog, err := nvrtc.CreateProgram(src, "saxpy.cu")
	if err != nil {
		fmt.Println("create:", err)
		return
	}
	defer prog.Destroy()

	if err := prog.Compile("--gpu-architecture=compute_70"); err != nil {
		log, _ := prog.Log()
		fmt.Printf("compile: %v\n%s", err, log)
		return
	}
	ptx, err := prog.PTX()
	if err != nil {
		fmt.Println("ptx:", err)
		return
	}
	fmt.Printf("NVRTC %d.%d compiled %d bytes of PTX\n", major, minor, len(ptx))
}

Index

Examples

Constants

View Source
const (
	InstallHeadersForceOverwrite uint32 = 0x1
	InstallHeadersNoWait         uint32 = 0x2
	InstallHeadersSkipIfExists   uint32 = 0x0
)

Flags for InstallBundledHeaders.

View Source
const (
	// FlagGpuArchitecture selects --gpu-architecture.
	FlagGpuArchitecture = "--gpu-architecture"
	// FlagStd selects -std.
	FlagStd = "-std"
	// FlagUseFastMath selects --use_fast_math.
	FlagUseFastMath = "--use_fast_math"
	// FlagFtz selects -ftz.
	FlagFtz = "-ftz"
	// FlagPrecDiv selects -prec-div.
	FlagPrecDiv = "-prec-div"
	// FlagPrecSqrt selects -prec-sqrt.
	FlagPrecSqrt = "-prec-sqrt"
	// FlagFmad selects -fmad.
	FlagFmad = "-fmad"
	// FlagDeviceAsDefaultExecutionSpace selects --device-as-default-execution-space.
	FlagDeviceAsDefaultExecutionSpace = "--device-as-default-execution-space"
	// FlagDeviceDebug selects --device-debug.
	FlagDeviceDebug = "--device-debug"
	// FlagGenerateLineInfo selects --generate-line-info.
	FlagGenerateLineInfo = "--generate-line-info"
	// FlagRelocatableDeviceCode selects --relocatable-device-code.
	FlagRelocatableDeviceCode = "--relocatable-device-code"
	// FlagMaxrregcount selects --maxrregcount.
	FlagMaxrregcount = "--maxrregcount"
	// FlagExtraDeviceVectorization selects --extra-device-vectorization.
	FlagExtraDeviceVectorization = "--extra-device-vectorization"
	// FlagDisableWarnings selects -w.
	FlagDisableWarnings = "-w"
	// FlagWarningAsError selects --warning-as-error.
	FlagWarningAsError = "--warning-as-error"
	// FlagIncludePath selects --include-path.
	FlagIncludePath = "--include-path"
	// FlagDefineMacro selects -D.
	FlagDefineMacro = "-D"
	// FlagUndefineMacro selects -U.
	FlagUndefineMacro = "-U"
	// FlagPreInclude selects --pre-include.
	FlagPreInclude = "--pre-include"
	// FlagDLTO selects -dlto.
	FlagDLTO = "-dlto"
	// FlagTileOnly selects --tile-only.
	FlagTileOnly = "--tile-only"
	// FlagEnableTile selects --enable-tile.
	FlagEnableTile = "--enable-tile"
	// FlagOptiXIR selects --optix-ir.
	FlagOptiXIR = "--optix-ir"
	// FlagPCH selects -pch.
	FlagPCH = "-pch"
	// FlagCreatePCH selects --create-pch.
	FlagCreatePCH = "--create-pch"
	// FlagUsePCH selects --use-pch.
	FlagUsePCH = "--use-pch"
	// FlagOfastCompile selects --Ofast-compile.
	FlagOfastCompile = "--Ofast-compile"
	// FlagRandomSeed selects --frandom-seed.
	FlagRandomSeed = "--frandom-seed"
	// FlagExtensibleWholeProgram selects --extensible-whole-program.
	FlagExtensibleWholeProgram = "--extensible-whole-program"
	// FlagDeviceStackProtector selects --device-stack-protector.
	FlagDeviceStackProtector = "--device-stack-protector"
	// FlagTime selects --time.
	FlagTime = "--time"
	// FlagNoCache selects --no-cache.
	FlagNoCache = "--no-cache"
)

Standard compiler flag constants accepted by NVRTC.

View Source
const (
	StdCXX03 = "c++03"
	StdCXX11 = "c++11"
	StdCXX14 = "c++14"
	StdCXX17 = "c++17"
	StdCXX20 = "c++20"
	// StdCXX23 selects -std=c++23.
	StdCXX23 = "c++23"
)

C++ language standards accepted by NVRTC -std flag.

View Source
const (
	FastCompile0   = "0"
	FastCompileMin = "min"
	FastCompileMid = "mid"
	FastCompileMax = "max"
)

Fast compilation levels accepted by NVRTC --Ofast-compile flag.

Variables

View Source
var SupportedOptions = []OptionDef{
	{Name: "--gpu-architecture", Short: "-arch", Arity: "value", Default: "", Values: []string{"all", "all-major", "compute_100", "compute_100a", "compute_100f", "compute_103", "compute_103a", "compute_103f", "compute_107", "compute_107a", "compute_107f", "compute_110", "compute_110a", "compute_110f", "compute_120", "compute_120a", "compute_120f", "compute_121", "compute_121a", "compute_121f", "compute_75", "compute_80", "compute_86", "compute_87", "compute_88", "compute_89", "compute_90", "compute_90a", "lto_100", "lto_100a", "lto_100f", "lto_103", "lto_103a", "lto_103f", "lto_107", "lto_107a", "lto_107f", "lto_110", "lto_110a", "lto_110f", "lto_120", "lto_120a", "lto_120f", "lto_121", "lto_121a", "lto_121f", "lto_75", "lto_80", "lto_86", "lto_87", "lto_88", "lto_89", "lto_90", "lto_90a", "native", "sm_100", "sm_100a", "sm_100f", "sm_103", "sm_103a", "sm_103f", "sm_107", "sm_107a", "sm_107f", "sm_110", "sm_110a", "sm_110f", "sm_120", "sm_120a", "sm_120f", "sm_121", "sm_121a", "sm_121f", "sm_75", "sm_80", "sm_86", "sm_87", "sm_88", "sm_89", "sm_90", "sm_90a"}},
	{Name: "-std", Short: "--std", Arity: "value", Default: "", Values: []string{"c++03", "c++11", "c++14", "c++17", "c++20", "c++23"}},
	{Name: "--use_fast_math", Short: "-use_fast_math", Arity: "bare", Default: ""},
	{Name: "-ftz", Short: "--ftz", Arity: "value", Default: "false", Values: []string{"true", "false"}},
	{Name: "-prec-div", Short: "--prec-div", Arity: "value", Default: "true", Values: []string{"true", "false"}},
	{Name: "-prec-sqrt", Short: "--prec-sqrt", Arity: "value", Default: "true", Values: []string{"true", "false"}},
	{Name: "-fmad", Short: "--fmad", Arity: "value", Default: "true", Values: []string{"true", "false"}},
	{Name: "--device-as-default-execution-space", Short: "-default-device", Arity: "bare", Default: ""},
	{Name: "--device-debug", Short: "-G", Arity: "bare", Default: ""},
	{Name: "--generate-line-info", Short: "-lineinfo", Arity: "bare", Default: ""},
	{Name: "--relocatable-device-code", Short: "-rdc", Arity: "value", Default: "false", Values: []string{"true", "false"}},
	{Name: "--maxrregcount", Short: "-maxrregcount", Arity: "value", Default: ""},
	{Name: "--extra-device-vectorization", Short: "-extra-device-vectorization", Arity: "bare", Default: ""},
	{Name: "-w", Short: "--disable-warnings", Arity: "bare", Default: ""},
	{Name: "--warning-as-error", Short: "-Werror", Arity: "value", Default: "", Separator: ",", Values: []string{"all-warnings", "conversion"}},
	{Name: "--include-path", Short: "-I", Arity: "value", Default: ""},
	{Name: "-D", Short: "--define-macro", Arity: "value", Default: ""},
	{Name: "-U", Short: "--undefine-macro", Arity: "value", Default: ""},
	{Name: "--pre-include", Short: "-include", Arity: "value", Default: ""},
	{Name: "-dlto", Short: "--dlink-time-opt", Arity: "bare", Default: ""},
	{Name: "--tile-only", Short: "-tile-only", Arity: "bare", Default: ""},
	{Name: "--enable-tile", Short: "-enable-tile", Arity: "bare", Default: ""},
	{Name: "--optix-ir", Short: "-optix-ir", Arity: "bare", Default: ""},
	{Name: "-pch", Short: "--pch", Arity: "bare", Default: ""},
	{Name: "--create-pch", Short: "-create-pch", Arity: "value", Default: ""},
	{Name: "--use-pch", Short: "-use-pch", Arity: "value", Default: ""},
	{Name: "--Ofast-compile", Short: "-Ofc", Arity: "value", Default: "", Values: []string{"0", "max", "mid", "min"}},
	{Name: "--frandom-seed", Short: "-frandom-seed", Arity: "value", Default: ""},
	{Name: "--extensible-whole-program", Short: "-ewp", Arity: "bare", Default: ""},
	{Name: "--device-stack-protector", Short: "-device-stack-protector", Arity: "value", Default: "false", Values: []string{"true", "false"}},
	{Name: "--time", Short: "-time", Arity: "value", Default: ""},
	{Name: "--no-cache", Short: "-no-cache", Arity: "bare", Default: ""},
}

SupportedOptions records all compiler options recognized by NVRTC.

Functions

func Close

func Close() error

Close unloads the library and clears all bound function pointers.

The function pointers are package-level state, so Close must not be called concurrently with any other call into this package: doing so is a use-after-free. It is intended for test teardown, not for reclaiming a live library.

func ComputeArch

func ComputeArch(major, minor int) string

ComputeArch returns the virtual compute architecture string for major.minor (e.g., "compute_80" for 8, 0).

func GetNumSupportedArchs

func GetNumSupportedArchs() (int32, error)

GetNumSupportedArchs sets the output parameter numArchs with the number of architectures supported by NVRTC.

This can then be used to pass an array to GetSupportedArchs to get the supported architectures. see GetSupportedArchs

Errors:

Wraps nvrtcGetNumSupportedArchs.

func GetPCHHeapSize

func GetPCHHeapSize() (uint, error)

GetPCHHeapSize retrieves the current size of the PCH Heap.

Requires CUDA 12.8 or later; see HasGetPCHHeapSize.

Errors:

Wraps nvrtcGetPCHHeapSize.

func GetSupportedArchs

func GetSupportedArchs(supportedArchs *int32) error

GetSupportedArchs populates the array passed via the output parameter supportedArchs with the architectures supported by NVRTC.

The array is sorted in the ascending order. The size of the array to be passed can be determined using GetNumSupportedArchs. see GetNumSupportedArchs

  • supportedArchs: sorted array of supported architectures

Errors:

Wraps nvrtcGetSupportedArchs.

func Has

func Has(symbol string) bool

Has reports whether the named C symbol resolved in the loaded library, loading it first if necessary. It returns false if the library failed to load. Use it to gate on capabilities before calling into them.

func HasAddNameExpression

func HasAddNameExpression() bool

HasAddNameExpression reports whether nvrtcAddNameExpression resolved in the loaded library.

func HasCompileProgram

func HasCompileProgram() bool

HasCompileProgram reports whether nvrtcCompileProgram resolved in the loaded library.

func HasCreateProgram

func HasCreateProgram() bool

HasCreateProgram reports whether nvrtcCreateProgram resolved in the loaded library.

func HasDestroyProgram

func HasDestroyProgram() bool

HasDestroyProgram reports whether nvrtcDestroyProgram resolved in the loaded library.

func HasGetBundledHeadersInfo

func HasGetBundledHeadersInfo() bool

HasGetBundledHeadersInfo reports whether nvrtcGetBundledHeadersInfo resolved in the loaded library.

func HasGetCUBIN

func HasGetCUBIN() bool

HasGetCUBIN reports whether nvrtcGetCUBIN resolved in the loaded library.

func HasGetCUBINSize

func HasGetCUBINSize() bool

HasGetCUBINSize reports whether nvrtcGetCUBINSize resolved in the loaded library.

func HasGetErrorString

func HasGetErrorString() bool

HasGetErrorString reports whether nvrtcGetErrorString resolved in the loaded library.

func HasGetLTOIR

func HasGetLTOIR() bool

HasGetLTOIR reports whether nvrtcGetLTOIR resolved in the loaded library.

func HasGetLTOIRSize

func HasGetLTOIRSize() bool

HasGetLTOIRSize reports whether nvrtcGetLTOIRSize resolved in the loaded library.

func HasGetLoweredName

func HasGetLoweredName() bool

HasGetLoweredName reports whether nvrtcGetLoweredName resolved in the loaded library.

func HasGetNVVM

func HasGetNVVM() bool

HasGetNVVM reports whether nvrtcGetNVVM resolved in the loaded library.

func HasGetNVVMSize

func HasGetNVVMSize() bool

HasGetNVVMSize reports whether nvrtcGetNVVMSize resolved in the loaded library.

func HasGetNumSupportedArchs

func HasGetNumSupportedArchs() bool

HasGetNumSupportedArchs reports whether nvrtcGetNumSupportedArchs resolved in the loaded library.

func HasGetOptiXIR

func HasGetOptiXIR() bool

HasGetOptiXIR reports whether nvrtcGetOptiXIR resolved in the loaded library.

func HasGetOptiXIRSize

func HasGetOptiXIRSize() bool

HasGetOptiXIRSize reports whether nvrtcGetOptiXIRSize resolved in the loaded library.

func HasGetPCHCreateStatus

func HasGetPCHCreateStatus() bool

HasGetPCHCreateStatus reports whether nvrtcGetPCHCreateStatus resolved in the loaded library.

func HasGetPCHHeapSize

func HasGetPCHHeapSize() bool

HasGetPCHHeapSize reports whether nvrtcGetPCHHeapSize resolved in the loaded library.

func HasGetPCHHeapSizeRequired

func HasGetPCHHeapSizeRequired() bool

HasGetPCHHeapSizeRequired reports whether nvrtcGetPCHHeapSizeRequired resolved in the loaded library.

func HasGetPTX

func HasGetPTX() bool

HasGetPTX reports whether nvrtcGetPTX resolved in the loaded library.

func HasGetPTXSize

func HasGetPTXSize() bool

HasGetPTXSize reports whether nvrtcGetPTXSize resolved in the loaded library.

func HasGetProgramLog

func HasGetProgramLog() bool

HasGetProgramLog reports whether nvrtcGetProgramLog resolved in the loaded library.

func HasGetProgramLogSize

func HasGetProgramLogSize() bool

HasGetProgramLogSize reports whether nvrtcGetProgramLogSize resolved in the loaded library.

func HasGetSupportedArchs

func HasGetSupportedArchs() bool

HasGetSupportedArchs reports whether nvrtcGetSupportedArchs resolved in the loaded library.

func HasGetTileIR

func HasGetTileIR() bool

HasGetTileIR reports whether nvrtcGetTileIR resolved in the loaded library.

func HasGetTileIRSize

func HasGetTileIRSize() bool

HasGetTileIRSize reports whether nvrtcGetTileIRSize resolved in the loaded library.

func HasInstallBundledHeaders

func HasInstallBundledHeaders() bool

HasInstallBundledHeaders reports whether nvrtcInstallBundledHeaders resolved in the loaded library.

func HasRemoveBundledHeaders

func HasRemoveBundledHeaders() bool

HasRemoveBundledHeaders reports whether nvrtcRemoveBundledHeaders resolved in the loaded library.

func HasSetFlowCallback

func HasSetFlowCallback() bool

HasSetFlowCallback reports whether nvrtcSetFlowCallback resolved in the loaded library.

func HasSetPCHHeapSize

func HasSetPCHHeapSize() bool

HasSetPCHHeapSize reports whether nvrtcSetPCHHeapSize resolved in the loaded library.

func HasVersion

func HasVersion() bool

HasVersion reports whether nvrtcVersion resolved in the loaded library.

func InstallBundledHeaders

func InstallBundledHeaders(installPath string, flags uint32) error

InstallBundledHeaders extracts CUDA headers bundled with NVRTC to a specified directory for use during compilation.

NVRTC bundles a set of CUDA Toolkit headers and CUDA C++ Core Libraries (CCCL) within libnvrtc-builtins. This function extracts these headers to the specified directory, allowing NVRTC programs to compile without requiring a separate CUDA Toolkit installation. The bundled headers match those available in the CUDA Toolkit plus CCCL libraries. After extraction, users can compile kernels by passing appropriate include paths (such as “-I” and “-I/cccl”) to Program.Compile. A version marker file (.nvrtc_headers_version) is created in the installation directory to track the installed version. This function is thread-safe and process-safe. Concurrent calls from multiple threads or processes will be serialized using file locking. By default, the function waits for the lock; use NVRTC_INSTALL_HEADERS_NO_WAIT to return immediately with ErrBusy if another process holds the lock.

Note: Use NVRTC_INSTALL_HEADERS_SKIP_IF_EXISTS to avoid reinstalling if headers already exist. Use NVRTC_INSTALL_HEADERS_FORCE_OVERWRITE to guarantee consistency by clearing the directory first.

See also: Program.Compile

Requires CUDA 13.3 or later; see HasInstallBundledHeaders.

  • installPath: Path where headers should be extracted (UTF-8 encoded). The directory will be created if it doesn’t exist
  • flags: NVRTC_INSTALL_HEADERS_* flags:0 (SKIP_IF_EXISTS): Skip if version marker exists and version matches. This is the default.NVRTC_INSTALL_HEADERS_FORCE_OVERWRITE: Clear directory first, then install. Guarantees consistency.NVRTC_INSTALL_HEADERS_NO_WAIT: Return ErrBusy immediately if lock cannot be acquired. NO_WAIT can be combined with FORCE_OVERWRITE

Errors:

  • ErrBuiltinOperationFailure: extraction failed or version mismatch
  • ErrBusy: lock held by another process and NVRTC_INSTALL_HEADERS_NO_WAIT was specified
  • ErrInvalidInput: invalid path or conflicting flags like SKIP_IF_EXISTS | FORCE_OVERWRITE

Wraps nvrtcInstallBundledHeaders.

func Load

func Load(path string) error

Load opens the shared library from path, or from the default search list when path is empty, and binds all symbols. Callers that need to direct loading should call Load before any other function; otherwise the first call loads from the default search list.

Load is idempotent: calling it again with the same path, or with an empty path, returns nil. Calling it with a different path after a successful load returns *LibraryConflictError rather than replacing the library. After a failed load, Load retries.

func Loaded

func Loaded() bool

Loaded reports whether the library is currently loaded. It does not trigger a load.

func Path

func Path() string

Path returns the path or name the loaded library was opened from, or the empty string if no library is loaded.

func RemoveBundledHeaders

func RemoveBundledHeaders(installPath string) error

RemoveBundledHeaders removes previously installed bundled headers.

This function removes the headers installed by InstallBundledHeaders, helping users manage disk space. It recursively removes all files and subdirectories within the installation directory.

Note: This function will remove ALL contents of the specified directory, not just files installed by NVRTC. Use with caution.

Requires CUDA 13.3 or later; see HasRemoveBundledHeaders.

  • installPath: Path where headers were previously installed. Must be the same path used with InstallBundledHeaders

Errors:

Wraps nvrtcRemoveBundledHeaders.

func SetPCHHeapSize

func SetPCHHeapSize(size uint) error

SetPCHHeapSize sets the size of the PCH Heap.

The requested size may be rounded up to a platform dependent alignment (e.g. page size). If the PCH Heap has already been allocated, the heap memory will be freed and a new PCH Heap will be allocated.

Requires CUDA 12.8 or later; see HasSetPCHHeapSize.

  • size: requested size of the PCH Heap, in bytes

Wraps nvrtcSetPCHHeapSize.

func SmArch

func SmArch(major, minor int) string

SmArch returns the physical GPU architecture string for major.minor (e.g., "sm_80" for 8, 0).

func ValidateOption

func ValidateOption(flag string) error

ValidateOption checks the spelling and value of a recognized NVRTC option.

func Version

func Version() (major int32, minor int32, err error)

Version sets the output parameters major and minor with the CUDA Runtime Compilation version number.

  • major: CUDA Runtime Compilation major version number
  • minor: CUDA Runtime Compilation minor version number

Errors:

Wraps nvrtcVersion.

Types

type BindFailure

type BindFailure struct {
	Symbol string
	Err    error
}

BindFailure names a symbol the loaded library exports but that could not be bound, and why.

func BindFailures

func BindFailures() []BindFailure

BindFailures returns the symbols the loaded library exports that could not be bound, sorted by symbol name, or nil if every exported symbol bound. Calling one of these reports *SymbolError with the same Err.

A load that reports no error can still leave symbols unbound: the library is fine and the signatures are not representable here. Call this after Load to find that out at once rather than one call site at a time. It does not trigger a load, and returns nil if none has happened.

type BundledHeadersInfo

type BundledHeadersInfo struct {
	// Non-zero if bundled headers are available
	Available int32
	// Size of compressed archive in bytes
	CompressedSize uint
	// Estimated size when extracted in bytes
	UncompressedSize uint
	// CUDA major version of bundled headers
	CudaVersionMajor int32
	// CUDA minor version of bundled headers
	CudaVersionMinor int32
	// Number of header files in the bundle
	NumFiles uint32
}

BundledHeadersInfo contains information about bundled headers.

func GetBundledHeadersInfo

func GetBundledHeadersInfo() (BundledHeadersInfo, error)

GetBundledHeadersInfo queries information about the bundled headers without extracting them.

This function allows users to determine if bundled headers are available and get size estimates before calling InstallBundledHeaders.

Requires CUDA 13.3 or later; see HasGetBundledHeadersInfo.

Errors:

Wraps nvrtcGetBundledHeadersInfo.

type CallError

type CallError struct {
	Func   string // the C symbol called
	Result Result
}

CallError reports that a library call returned a failure result.

Unwrap returns Result, so errors.Is(err, c) reports whether the call returned the Result constant c, and errors.As(err, &r) with r of type Result recovers the code.

func (*CallError) Error

func (e *CallError) Error() string

Error reports the C symbol called and the result it returned.

func (*CallError) Unwrap

func (e *CallError) Unwrap() error

Unwrap returns the result the call reported.

type Header struct {
	// Name is the name the program's #include directive uses.
	Name string
	// Source is the contents of the header.
	Source string
}

A Header is a header a program can include by name. It is passed to CreateProgram.

type LibraryAttempt

type LibraryAttempt struct {
	Name string // path or soname passed to dlopen
	Err  error
}

LibraryAttempt records one failed attempt to open the shared library.

type LibraryConflictError

type LibraryConflictError struct {
	Loaded    string
	Requested string

	// Implicit reports that the loaded library was opened lazily and no
	// successful Load has since acknowledged it. A
	// caller that sees this called some
	// other function first, and that call took the default search list.
	Implicit bool
}

LibraryConflictError reports a Load call naming a different library than the one already loaded. Only one library is loaded per process.

func (*LibraryConflictError) Error

func (e *LibraryConflictError) Error() string

Error reports the conflicting library paths, and whether the library that is already loaded got there without a Load call.

type LibraryError

type LibraryError struct {
	Library  string
	Env      string
	Path     string
	Attempts []LibraryAttempt
	Hint     string
}

LibraryError reports that libnvrtc could not be opened. Attempts lists every name tried in order. Path is set when an explicit path, from Load or NVRTC_LIB_PATH, was requested and failed. Hint reports pkg-config discovery results and query failures, when discovery ran.

func (*LibraryError) Error

func (e *LibraryError) Error() string

Error describes the library load attempts and their errors.

func (*LibraryError) Unwrap

func (e *LibraryError) Unwrap() []error

Unwrap returns the error from each attempt.

type OptionDef

type OptionDef struct {
	Name      string
	Short     string
	Arity     string // "bare" or "value"
	Default   string
	Values    []string
	Separator string
}

OptionDef describes a compiler option recognized by NVRTC.

type Program

type Program uintptr

Program is an opaque handle for nvrtcProgram.

func CreateProgram

func CreateProgram(src string, name string, headers ...Header) (Program, error)

CreateProgram creates an instance of Program with the given input parameters, and sets the output parameter prog with it.

See also: Program.Destroy

  • src: CUDA program source
  • name: CUDA program name. name can be NULL; "default_program" is used when name is NULL or “”

Errors:

Wraps nvrtcCreateProgram.

func (Program) AddNameExpression

func (p Program) AddNameExpression(nameExpression *byte) error

AddNameExpression notes the given name expression denoting the address of a global function or device/__constant__ variable.

The identical name expression string must be provided on a subsequent call to Program.LoweredName to extract the lowered name.

See also: Program.LoweredName

  • nameExpression: constant expression denoting the address of a global function or device/__constant__ variable

Errors:

Wraps nvrtcAddNameExpression.

func (Program) CUBIN

func (p Program) CUBIN() ([]byte, error)

CUBIN returns the cubin generated by the previous compilation of prog.

No cubin is available if the value specified to -arch is a virtual architecture instead of an actual architecture. The cubin does not contain code for the Tile functions ( __tile__ / __tile_global__) or variables ( __tile__); use Program.TileIR to extract the cuda_tile IR generated for Tile code.

See also: Program.CUBINSize

Errors:

Wraps nvrtcGetCUBIN.

func (Program) CUBINSize

func (p Program) CUBINSize() (uint, error)

CUBINSize returns the size of the cubin generated by the previous compilation of prog.

The result is 0 if the value specified to -arch is a virtual architecture instead of an actual architecture.

See also: Program.CUBIN

Errors:

Wraps nvrtcGetCUBINSize.

func (Program) Compile

func (p Program) Compile(options ...string) error

Compile compiles the given program.

It supports compile options listed in Supported Compile Options.

  • options: Compiler options in the form of C string array. options can be NULL when numOptions is 0

Errors:

Wraps nvrtcCompileProgram.

func (*Program) Destroy

func (p *Program) Destroy() error

Destroy destroys the given program.

See also: CreateProgram

Errors:

It is not named Close because it takes a pointer to the handle.

Wraps nvrtcDestroyProgram.

func (Program) LTOIR

func (p Program) LTOIR() ([]byte, error)

LTOIR returns the LTO IR generated by the previous compilation of prog.

No LTO IR is available if the program was compiled without -dlto.

See also: Program.LTOIRSize

Errors:

Wraps nvrtcGetLTOIR.

func (Program) LTOIRSize

func (p Program) LTOIRSize() (uint, error)

LTOIRSize returns the size of the LTO IR generated by the previous compilation of prog.

The result is 0 if the program was not compiled with -dlto.

See also: Program.LTOIR

Errors:

Wraps nvrtcGetLTOIRSize.

func (Program) Log

func (p Program) Log() (string, error)

Log returns the log generated by the previous compilation of prog.

See also: Program.LogSize

Errors:

Wraps nvrtcGetProgramLog.

func (Program) LogSize

func (p Program) LogSize() (uint, error)

LogSize returns the size of the log generated by the previous compilation of prog (including the trailing NULL).

Note that compilation log may be generated with warnings and informative messages, even when the compilation of prog succeeds.

See also: Program.Log

Errors:

The size counts the terminating NUL that Program.Log drops, so it is one more than the length of that result.

Wraps nvrtcGetProgramLogSize.

func (Program) LoweredName

func (p Program) LoweredName(nameExpression *byte, loweredName **byte) error

LoweredName extracts the lowered (mangled) name for a global function or device/__constant__ variable, and updates *loweredName to point to it.

The memory containing the name is released when the NVRTC program is destroyed by Program.Destroy. The identical name expression must have been previously provided to Program.AddNameExpression.

See also: Program.AddNameExpression

  • nameExpression: constant expression denoting the address of a global function or device/__constant__ variable
  • loweredName: initialized by the function to point to a C string containing the lowered (mangled) name corresponding to the provided name expression

Errors:

Wraps nvrtcGetLoweredName.

func (Program) NVVM deprecated

func (p Program) NVVM() ([]byte, error)

NVVM wraps nvrtcGetNVVM.

Deprecated: Deprecated in CUDA 12.0. Use Program.LTOIR instead. NVIDIA removed this function in CUDA 13.0.

func (Program) NVVMSize deprecated

func (p Program) NVVMSize() (uint, error)

NVVMSize wraps nvrtcGetNVVMSize.

Deprecated: Deprecated in CUDA 12.0. Use Program.LTOIRSize instead. NVIDIA removed this function in CUDA 13.0.

func (Program) OptiXIR

func (p Program) OptiXIR() ([]byte, error)

OptiXIR returns the OptiX IR generated by the previous compilation of prog.

No OptiX IR is available if the program was compiled with options incompatible with OptiX IR generation.

See also: Program.OptiXIRSize

Errors:

Wraps nvrtcGetOptiXIR.

func (Program) OptiXIRSize

func (p Program) OptiXIRSize() (uint, error)

OptiXIRSize returns the size of the OptiX IR generated by the previous compilation of prog.

The value of Program.OptiXIRSize is set to 0 if the program was compiled with options incompatible with OptiX IR generation.

See also: Program.OptiXIR

Errors:

Wraps nvrtcGetOptiXIRSize.

func (Program) PCHCreateStatus

func (p Program) PCHCreateStatus() error

PCHCreateStatus returns the PCH creation status.

Success indicates that the PCH was successfully created. ErrNoPchCreateAttempted indicates that no PCH creation was attempted, either because PCH functionality was not requested during the preceding Program.Compile call, or automatic PCH processing was requested, and compiler chose not to create a PCH file. ErrPchCreateHeapExhausted indicates that a PCH file could potentially have been created, but the compiler ran out space in the PCH heap. In this scenario, the Program.PCHHeapSizeRequired can be used to query the required heap size, the heap can be reallocated for this size with SetPCHHeapSize and PCH creation may be reattempted again invoking Program.Compile with a new NVRTC program instance. ErrPchCreate indicates that an error condition prevented the PCH file from being created.

Requires CUDA 12.8 or later; see HasGetPCHCreateStatus.

Errors:

Wraps nvrtcGetPCHCreateStatus.

func (Program) PCHHeapSizeRequired

func (p Program) PCHHeapSizeRequired() (uint, error)

PCHHeapSizeRequired retrieves the required size of the PCH heap required to compile the given program.

Requires CUDA 12.8 or later; see HasGetPCHHeapSizeRequired.

Errors:

Wraps nvrtcGetPCHHeapSizeRequired.

func (Program) PTX

func (p Program) PTX() ([]byte, error)

PTX returns the PTX generated by the previous compilation of prog.

See also: Program.PTXSize

Errors:

The result does not include the C string's terminating NUL.

Wraps nvrtcGetPTX.

func (Program) PTXSize

func (p Program) PTXSize() (uint, error)

PTXSize returns the size of the PTX generated by the previous compilation of prog (including the trailing NULL).

See also: Program.PTX

Errors:

The size counts the terminating NUL that Program.PTX drops, so it is one more than the length of that result.

Wraps nvrtcGetPTXSize.

func (Program) SetFlowCallback

func (p Program) SetFlowCallback(callback uintptr, payload uintptr) error

SetFlowCallback registers a callback function that the compiler will invoke at different points during a call to Program.Compile, and the callback function can decide whether to cancel compilation by returning specific values.

The callback function must satisfy the following constraints:

When invoking the callback, the compiler will always pass payload to param1 so that the callback may make decisions based on payload . It’ll always pass NULL to param2 for now which is reserved for future extensions. (2) It must return 1 to cancel compilation or 0 to continue. Other return values are reserved for future use. (3) It must return consistent values. Once it returns 1 at one point, it must return 1 in all following invocations during the current Program.Compile call in progress. (4) It must be thread-safe. (5) It must not invoke any nvrtc/libnvvm/ptx APIs.

Requires CUDA 12.8 or later; see HasSetFlowCallback.

  • callback: the callback that issues cancellation signal
  • payload: to be passed as a parameter when invoking the callback

Errors:

Wraps nvrtcSetFlowCallback.

func (Program) TileIR

func (p Program) TileIR() ([]byte, error)

TileIR returns the cuda_tile IR generated by the previous compilation of prog.

See also: Program.TileIRSize

Requires CUDA 13.2 or later; see HasGetTileIR.

Errors:

Wraps nvrtcGetTileIR.

func (Program) TileIRSize

func (p Program) TileIRSize() (uint, error)

TileIRSize returns the size of the cuda_tile IR generated by the previous compilation of prog.

See also: Program.TileIR

Requires CUDA 13.2 or later; see HasGetTileIRSize.

Errors:

Wraps nvrtcGetTileIRSize.

type Result

type Result int32

Result represents a nvrtc API error code (nvrtcResult).

When the library is loaded, Result.Error returns rich messages from GetErrorString. When the library is not loaded, it falls back to the numeric error code and Go-defined name.

const (
	Success                              Result = 0
	ErrOutOfMemory                       Result = 1
	ErrProgramCreationFailure            Result = 2
	ErrInvalidInput                      Result = 3
	ErrInvalidProgram                    Result = 4
	ErrInvalidOption                     Result = 5
	ErrCompilation                       Result = 6
	ErrBuiltinOperationFailure           Result = 7
	ErrNoNameExpressionsAfterCompilation Result = 8
	ErrNoLoweredNamesBeforeCompilation   Result = 9
	ErrNameExpressionNotValid            Result = 10
	ErrInternalError                     Result = 11
	ErrTimeFileWriteFailed               Result = 12
	ErrNoPchCreateAttempted              Result = 13
	ErrPchCreateHeapExhausted            Result = 14
	ErrPchCreate                         Result = 15
	ErrCancelled                         Result = 16
	ErrTimeTraceFileWriteFailed          Result = 17
	ErrBusy                              Result = 18
)

nvrtc error codes from nvrtc.h.

func (Result) Code

func (r Result) Code() int32

Code returns the underlying result code for programmatic error handling.

func (Result) Error

func (r Result) Error() string

Error implements the error interface. When the library is loaded, it returns the error description from GetErrorString. Otherwise it returns a fallback string with the Go constant name and numeric code.

func (Result) String

func (r Result) String() string

String returns the Go constant name of the result.

type SymbolError

type SymbolError struct {
	Symbol string
	Err    error
}

SymbolError reports that a symbol is not callable.

Err distinguishes the two ways that happens. A nil Err means the loaded library does not export the symbol, which is what an installation older than the symbol looks like. A non-nil Err means the library does export it and the binding itself failed; the library is not at fault.

func (*SymbolError) Error

func (e *SymbolError) Error() string

Error reports the uncallable library symbol and, when the symbol was present but could not be bound, why.

func (*SymbolError) Unwrap

func (e *SymbolError) Unwrap() error

Unwrap returns the reason the symbol could not be bound, or nil when the loaded library does not export it.

type VersionMismatchError

type VersionMismatchError struct {
	Path string // the library that was opened
	Want int    // major version these bindings were generated for
	Got  int    // major version the library reports
	Raw  int    // the version value the library reported, undecoded
}

VersionMismatchError reports that the shared library that opened is not from the version train nvrtc was generated for. dlsym matches on name alone, so a library from a neighbouring train opens and resolves nearly every symbol; asking it its own version is what tells the two apart.

func (*VersionMismatchError) Error

func (e *VersionMismatchError) Error() string

Error reports which library was opened and the two majors that disagree.

A decoder is only a decoder for the version schemes it was measured against, and a library from a train that predates the scheme can report a value it does not decode. Naming a major of 0 in that case would attribute to the library a claim it never made, so the raw value is reported instead.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL