一键导入
rust-workspace
// Rust workspace architecture, IR data structures, compiler transforms, CPU backend, FFI integration with C++, and crate dependencies in LuisaCompute
// Rust workspace architecture, IR data structures, compiler transforms, CPU backend, FFI integration with C++, and crate dependencies in LuisaCompute
Backend plugin architecture, DeviceInterface API, dynamic loading, command encoding, and backend registration patterns in LuisaCompute
IR and XIR compiler pipeline, AST translation, SSA-based IR, instruction set, optimization passes, and control flow representation in LuisaCompute
Comprehensive project structure and architecture reference for the LuisaCompute codebase
Manual AST construction API for building kernels and callables without DSL syntax sugar
| name | rust_workspace |
| description | Rust workspace architecture, IR data structures, compiler transforms, CPU backend, FFI integration with C++, and crate dependencies in LuisaCompute |
The Rust workspace (src/rust/) implements the legacy IR, compiler optimization passes, and the CPU/Remote backends. It integrates with C++ via FFI using cbindgen for header generation and static libraries for linking.
src/rust/
├── Cargo.toml (workspace root)
├── luisa_compute_ir/ # Core IR data structures and transforms
├── luisa_compute_ir_staticlib/ # Static library wrapper for C++ linking
├── luisa_compute_ir_v2/ # IR v2 bindings
├── luisa_compute_api_types/ # Shared C++/Rust API types
├── luisa_compute_cpu_kernel_defs/ # CPU kernel runtime definitions
├── luisa_compute_backend/ # Backend trait definitions
└── luisa_compute_backend_impl/ # Backend implementations (CPU, Remote)
luisa_compute_api_types (base)
↑
├── luisa_compute_ir
│ ├── luisa_compute_ir_staticlib
│ ├── luisa_compute_ir_v2
│ └── luisa_compute_backend
│ └── luisa_compute_backend_impl
│ └── (uses luisa_compute_cpu_kernel_defs)
│
└── luisa_compute_cpu_kernel_defs
luisa_compute_api_typesPurpose: Defines shared types between C++ and Rust via FFI.
staticlib + rlibBuffer, Texture, Stream, Device, Shader, Accel, MeshBufferUploadCommand, ShaderDispatchCommand, AccelBuildCommandPixelStorage, PixelFormat (28 variants including BC compression)SamplerFilter, SamplerAddressAccelOption, AccelBuildModification, CurveBasisDeviceInterface (vtable of function pointers)cbindgen to generate api_types.hpp and api_types.h for C++luisa_compute_irPurpose: Core IR data structures and compiler transforms.
rlibluisa_compute_api_types, half, serde, bincode, indexmapCore Data Structures (src/ir.rs):
pub enum Type {
Void, Primitive(Primitive), Vector(VectorType), Matrix(MatrixType),
Struct(StructType), Array(ArrayType), Opaque(CBoxedSlice<u8>)
}
pub struct Node {
pub type_: CArc<Type>,
pub next: NodeRef,
pub prev: NodeRef,
pub instruction: CArc<Instruction>,
}
pub enum Instruction {
Local { init: NodeRef },
Update { var: NodeRef, value: NodeRef },
Call(Func, CBoxedSlice<NodeRef>),
Phi(CBoxedSlice<PhiIncoming>),
If { cond: NodeRef, true_branch: Pooled<BasicBlock>, false_branch: Pooled<BasicBlock> },
Loop { body: Pooled<BasicBlock>, cond: NodeRef },
GenericLoop { prepare, cond, body, update: Pooled<BasicBlock> },
Switch { value: NodeRef, default: Pooled<BasicBlock>, cases: CBoxedSlice<SwitchCase> },
AdScope { body: Pooled<BasicBlock>, forward: bool, n_forward_grads: usize },
RayQuery { ray_query: NodeRef, on_triangle_hit: Pooled<BasicBlock>, on_procedural_hit: Pooled<BasicBlock> },
// ... 20+ more variants
}
pub enum Func {
// 180+ variants including arithmetic, math, memory, atomic, warp, ray tracing, AD
}
Memory Management:
CArc<T>: C-compatible atomic reference countingCBoxedSlice<T>: C-compatible boxed slicePool<T>: Chunked memory pool for nodesModulePools: Separate pools for nodes and basic blocksluisa_compute_ir_staticlibPurpose: Static library wrapper for C++ linking.
staticlibluisa_compute_ir symbols as static libraryluisa_compute_ir_v2Purpose: IR v2 dynamic loading support.
libloading, luisa_compute_irluisa_compute_cpu_kernel_defsPurpose: Runtime type definitions for CPU kernels.
KernelFnArgs: Arguments passed to CPU kernel functionsBufferView, Texture, Accel: Runtime resource wrappersRay, Hit, RayQuery: Ray tracing structuresCpuCustomOp: Custom CPU operation callbackluisa_compute_backendPurpose: Backend trait abstraction.
Backend trait: Core interface with 20+ methods for resource managementContext: Loads backend DLLs (luisa-api.dll/libluisa-api.so)ProxyBackend: Dynamic dispatch wrapperluisa_compute_backend_implPurpose: Concrete backend implementations.
cdylibcpu, remoteCPU Backend (cpu/):
RustBackend: Main CPU backend using Rayon thread poolshader.rs: JIT compilation via Clang/LLVMcodegen/cpp.rs: C++ code generation from IRaccel.rs: Embree ray tracing integrationstream.rs: Command queue managementtexture.rs, resource.rs: Resource managementsrc/ir.rs)pub enum Type {
Void,
Primitive(Primitive),
Vector(VectorType),
Matrix(MatrixType),
Struct(StructType),
Array(ArrayType),
Opaque(CBoxedSlice<u8>),
}
pub enum Primitive {
Bool,
Int8, Int16, Int32, Int64,
Uint8, Uint16, Uint32, Uint64,
Float16, Float32, Float64,
}
Intrusive doubly-linked list for cache-friendly traversal:
pub struct Node {
pub type_: CArc<Type>,
pub next: NodeRef,
pub prev: NodeRef,
pub instruction: CArc<Instruction>,
}
pub enum Instruction {
Local { init: NodeRef },
Update { var: NodeRef, value: NodeRef },
Call(Func, CBoxedSlice<NodeRef>),
Phi(CBoxedSlice<PhiIncoming>),
If { cond: NodeRef, true_branch: Pooled<BasicBlock>, false_branch: Pooled<BasicBlock> },
Loop { body: Pooled<BasicBlock>, cond: NodeRef },
GenericLoop { prepare, cond, body, update: Pooled<BasicBlock> },
Switch { value: NodeRef, default: Pooled<BasicBlock>, cases: CBoxedSlice<SwitchCase> },
AdScope { body: Pooled<BasicBlock>, forward: bool, n_forward_grads: usize },
RayQuery { ray_query: NodeRef, on_triangle_hit: Pooled<BasicBlock>, on_procedural_hit: Pooled<BasicBlock> },
// ...
}
Func enum)180+ built-in functions:
Add, Mul, Sin, Cos, Exp, Log, SqrtCross, Dot, Determinant, Inverse, TransposeBufferRead, BufferWrite, Texture2dReadAtomicExchange, AtomicFetchAdd, etc.WarpActiveSum, WarpPrefixSum, etc.RayTracingTraceClosest, RayQueryCommitTriangleRequiresGradient, Backward, PropagateGradsrc/ffi.rs)pub struct CArc<T> {
pub ptr: *mut T,
pub inner: *mut CArcInner,
}
pub struct CBox<T> {
pub ptr: *mut T,
pub drop: extern "C" fn(*mut T),
}
pub struct CBoxedSlice<T> {
pub ptr: *mut T,
pub len: usize,
pub drop: extern "C" fn(*mut T, usize),
}
src/transform/mod.rs)| Transform | Purpose |
|---|---|
ssa::ToSSA | Converts imperative Update instructions to SSA form with Phi nodes |
autodiff::Autodiff | Reverse-mode automatic differentiation |
fwd_autodiff::FwdAutodiff | Forward-mode automatic differentiation |
dce::Dce | Dead code elimination |
inliner::inline_callable | Function inlining |
canonicalize_control_flow::CanonicalizeControlFlow | Normalizes control flow |
ref2ret::Ref2Ret | Converts reference returns to value returns |
reg2mem::Reg2Mem | Register to memory conversion |
src/transform/autodiff.rs)Reverse-mode AD implementation:
RequiresGradientSupported gradient rules:
src/transform/ssa.rs)Local variables to SSA valuesUpdate instructions by tracking current value in stored mapPhi nodes at merge points (if/then/else, loops)ExtractElement/InsertElement conversionsrc/transform/dce.rs)cpu/mod.rs)cpu/codegen/cpp.rs)BufferImpl: Aligned host memory allocationTextureImpl: Mipmapped image storageBindlessArrayImpl: Array of buffer/texture descriptorsAccelImpl: Embree scene acceleration structureBoth luisa_compute_ir and luisa_compute_api_types use cbindgen:
build.rs workflow:
cbindgenir.hpp, api_types.hpp)api_types.h)include/luisa/rust/luisa_compute_ir_staticlib builds as staticlib.a/.lib file#[no_mangle] extern "C" functions for C++ callable API// Transform pipeline
luisa_compute_ir_transform_pipeline_new() -> *mut TransformPipeline
luisa_compute_ir_transform_pipeline_add_transform(pipeline, name)
luisa_compute_ir_transform_pipeline_transform(pipeline, module) -> Module
luisa_compute_ir_transform_auto(module) -> Module
// Library interface
luisa_compute_lib_interface() -> LibInterface
#[repr(C)] for C layout compatibilityu64 wrappers (Buffer(u64), Texture(u64))extern "C" function pointersDeviceInterface is a vtable struct of function pointersFile: src/rust/CMakeLists.txt
cargo build via CMake custom commanddev for Debug, release for Releasecpu, remote)luisa_compute_ir_static, luisa_compute_api_typesluisa_compute_backend_impl.lib/.a, .dll/.so/.dylib)luisa-compute-rust-meta (INTERFACE): Links static Rust libs, Windows system libsluisa_compute_backend_impl (INTERFACE): Links shared Rust backend implinstall_name_tool for rpath patchingpatchelf for rpath patching.dll, .lib, and .pdb filesEMBREE_ZIP_FILE for custom Embreecontext.rsCArc with C-compatible destructor callbacks