nvvm

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: 12 Imported by: ? modules, 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 nvvm lowers NVVM IR modules and compiles them to PTX via libnvvm, including address-space def-use specialization passes.

This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AddrSpace

type AddrSpace int

AddrSpace represents an LLVM/NVVM memory address space.

const (
	// AddrSpaceGeneric is the generic address space (0).
	AddrSpaceGeneric AddrSpace = 0

	// AddrSpaceGlobal is global device memory (1).
	AddrSpaceGlobal AddrSpace = 1

	// AddrSpaceShared is CTA-local shared memory (3).
	AddrSpaceShared AddrSpace = 3

	// AddrSpaceConstant is device constant memory (4).
	AddrSpaceConstant AddrSpace = 4

	// AddrSpaceLocal is thread-local stack memory (5).
	AddrSpaceLocal AddrSpace = 5

	// AddrSpaceCluster is cluster-mapped shared memory (7).
	// Cluster pointers are distinct from CTA-local shared pointers and must
	// not be inferred into AddrSpaceShared.
	AddrSpaceCluster AddrSpace = 7
)

type CompilationProvenance

type CompilationProvenance struct {
	PTXSHA256 string
	Inputs    []InferredInput
}

CompilationProvenance contains inference from a successful PTX compilation. It does not attest native execution or the correctness of supplied debug info.

Example
var provenance CompilationProvenance
fmt.Println(len(provenance.Inputs))
Output:
0

type InferenceReport

type InferenceReport struct {
	Slots          map[string]SlotInfo
	Iterations     int
	RewrittenSlots []string
	// contains filtered or unexported fields
}

InferenceReport summarizes the findings of the address-space inference pass.

func InferAddressSpaces

func InferAddressSpaces(ir []byte) ([]byte, *InferenceReport, error)

InferAddressSpaces pre-scans an NVVM IR module, determines for each local slot whether every value written into it is a shared-memory address, and declares that slot in addrspace(3) instead of the generic default.

An explicit source declaration always wins over inference. Cluster-mapped pointers (addrspace 7) are never inferred to CTA-local shared memory.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/compile/nvvm"
)

func main() {
	ir := `
@smem = internal addrspace(3) global [16 x float] undef, align 4

define void @example() {
entry:
  %slot = alloca ptr, align 8
  store ptr addrspace(3) @smem, ptr %slot, align 8
  ret void
}
`
	_, report, err := nvvm.InferAddressSpaces([]byte(ir))
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	info := report.Slots["@example/%slot"]
	fmt.Printf("%s: state=%s effective=addrspace(%d)\n", info.Name, info.State, info.Effective)
}
Output:
%slot: state=shared effective=addrspace(3)

func (*InferenceReport) Provenance

func (r *InferenceReport) Provenance() (*SlotProvenance, error)

Provenance returns an owned snapshot from the actual inference pass. The zero or a modified report is invalid; caller-built slot labels are not provenance.

Example
_, report, _ := InferAddressSpaces([]byte(transportIR))
provenance, _ := report.Provenance()
fmt.Println(provenance.Slots[0].Slot, provenance.Slots[0].Uses[0].Value)
Output:
@kernel/%slot %p

type InferredInput

type InferredInput struct {
	Name       string
	Provenance SlotProvenance
}

InferredInput binds one named compiler input to its original and prepared IR.

Example
input := InferredInput{Name: "kernel.ll"}
fmt.Println(input.Name, len(input.Provenance.Slots))
Output:
kernel.ll 0

type Input

type Input struct {
	Name string
	Data []byte
	Lazy bool
}

Input is a named NVVM IR module. Lazy inputs must contain bitcode and are loaded only for symbols required by non-lazy inputs. Compile copies Data; callers must not change it concurrently with Compile.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/compile/nvvm"
)

func main() {
	input := nvvm.Input{Name: "libdevice", Data: []byte{1, 2, 3}, Lazy: true}
	fmt.Println(input.Name, input.Lazy)
}
Output:
libdevice true

type LatticeState

type LatticeState int

LatticeState represents the state of a local slot in address-space inference. A bounded reachability phase seeds the states before dependency refinement. During refinement, StateShared may become StateUnconstrained or StateGenericRequired, and StateUnconstrained may become StateGenericRequired. No state becomes StateShared again, and StateGenericRequired is absorbing. With N slots, refinement therefore makes at most 2*N state changes and terminates in at most 2*N + 1 passes. Reachability takes at most N + 1 passes; reported iteration counts are the maximum of the two phase counts.

const (
	// StateUnconstrained indicates no writes to the slot have been observed.
	StateUnconstrained LatticeState = iota

	// StateShared indicates every write observed is a CTA-local shared address (addrspace 3).
	StateShared

	// StateGenericRequired indicates at least one write is not CTA-local shared memory.
	// This state is absorbing.
	StateGenericRequired
)

func (LatticeState) String

func (s LatticeState) String() string

type Option

type Option func(*compileOptions) error

Option configures an NVVM compilation. The zero value is invalid.

func WithAddressSpaceInference

func WithAddressSpaceInference() Option

WithAddressSpaceInference enables the address-space inference pass on input IR.

func WithArch

func WithArch(arch string) Option

WithArch selects a virtual target architecture such as compute_80 or compute_90a.

func WithDebug

func WithDebug() Option

WithDebug enables generation of full debugging information (-g). Note: per NVVM specification, debug support is only valid with -opt=0.

func WithFMA

func WithFMA(enable bool) Option

WithFMA controls contraction of floating-point multiply-add operations.

func WithFTZ

func WithFTZ(flush bool) Option

WithFTZ controls flushing of denormals to zero in single-precision floating-point operations.

func WithFlag

func WithFlag(flag string) Option

WithFlag adds a documented NVVM compiler option after validating it.

func WithGenLTO

func WithGenLTO() Option

WithGenLTO requests generation of LTO IR instead of PTX.

func WithJumpTableDensity

func WithJumpTableDensity(density int) Option

WithJumpTableDensity specifies the minimal switch case density percentage (0 to 101).

func WithOpt

func WithOpt(level int) Option

WithOpt sets optimization level: 0 to disable optimizations, 3 to enable optimizations.

func WithPrecDiv

func WithPrecDiv(ieee bool) Option

WithPrecDiv controls whether IEEE round-to-nearest mode (true, default) or a faster approximation (false) is used for single-precision division.

func WithPrecSqrt

func WithPrecSqrt(ieee bool) Option

WithPrecSqrt controls whether IEEE round-to-nearest mode (true, default) or a faster approximation (false) is used for single-precision square root.

type Result

type Result struct {
	PTX, LTOIR []byte
	Log        string
	// contains filtered or unexported fields
}

Result contains copied compiler output and diagnostics. Exactly one of PTX and LTOIR is set on success. Output must not be used if Compile returns an error. A non-nil result accompanying an error retains available diagnostics.

func Compile

func Compile(inputs []Input, options ...string) (*Result, error)

Compile synchronously compiles inputs using native NVVM options. At least one input must be non-lazy. The -gen-lto option selects LTOIR instead of PTX; unsupported IR and options are diagnosed by the loaded library. No library installation, implicit libdevice lookup, or caching is performed.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/compile/nvvm"
)

func main() {
	// Input validation does not require the native library.
	_, err := nvvm.Compile(nil)
	fmt.Println(err)
}
Output:
nvvmx: no inputs

func CompileWithOptions

func CompileWithOptions(inputs []Input, opts ...Option) (*Result, error)

CompileWithOptions compiles inputs using validated NVVM options. Compile remains available for callers that pass native option strings.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/compile/nvvm"
)

func main() {
	// Options are validated before native library calls.
	_, err := nvvm.CompileWithOptions(nil, nvvm.WithArch("compute_80"), nvvm.WithOpt(3))
	fmt.Println(err)
}
Output:
nvvmx: no inputs

func (*Result) AddressSpaceProvenance

func (r *Result) AddressSpaceProvenance() (*CompilationProvenance, error)

AddressSpaceProvenance returns owned inference metadata bound to the current copied PTX output. Failed compilation, LTOIR, disabled inference, modified PTX, and the zero Result have no usable PTX provenance.

Example
var result Result
_, err := result.AddressSpaceProvenance()
fmt.Println(err != nil)
Output:
true

func (*Result) Close

func (r *Result) Close() error

Close retries failed native destruction. Successful Compile already released its resources. Close is nil-safe, idempotent, and safe for concurrent calls. When destruction fails, the result retains the program and input pins until a later Close succeeds.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/compile/nvvm"
)

func main() {
	var result nvvm.Result
	fmt.Println(result.Close())
}
Output:
<nil>

type SlotInfo

type SlotInfo struct {
	Name           string       // Register name, e.g. "%slot"
	Declared       AddrSpace    // Declared address space of the allocated pointer type
	Explicit       bool         // True if the source IR explicitly declared an address space
	State          LatticeState // Inferred lattice state
	Effective      AddrSpace    // Effective address space after inference
	IterationCount int          // Iterations to reach fixed point
}

SlotInfo records analysis results for a local stack slot.

type SlotOrigin

type SlotOrigin struct {
	Slot            string
	DeclarationLine int
	Uses            []SlotUse
	Reason          string
}

SlotOrigin retains the actual inference pass's use sites. Reason is nonempty when attribution is unavailable, including dependent or unused slots.

Example
origin := SlotOrigin{Slot: "@kernel/%slot", Reason: "no terminal memory use"}
fmt.Println(origin.Reason)
Output:
no terminal memory use

type SlotProvenance

type SlotProvenance struct {
	OriginalSHA256, PreparedSHA256 string
	Slots                          []SlotOrigin
}

SlotProvenance identifies original/prepared IR and its inferred slot origins. It describes source analysis, not successful compilation or native execution.

Example
_, report, _ := InferAddressSpaces([]byte(transportIR))
provenance, _ := report.Provenance()
fmt.Println(provenance.OriginalSHA256 != provenance.PreparedSHA256)
Output:
true

type SlotUse

type SlotUse struct {
	IRLine           int
	Value, Operation string
	Location         SourceLocation
}

SlotUse is a terminal memory use of a pointer loaded from a slot.

Example
use := SlotUse{IRLine: 6, Value: "%p", Operation: "load"}
fmt.Println(use.Value, use.Operation)
Output:
%p load

type SourceLocation

type SourceLocation struct {
	Function, File string
	Line, Column   int
}

SourceLocation is a direct compiler debug location resolved in the input IR. A zero location is unavailable; it is never the physical IR line number.

Example
var location SourceLocation
fmt.Println(location.Line, location.Column)
Output:
0 0

Jump to

Keyboard shortcuts

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