Skip to content

Begin validating some SPIR-V extensions/capabilities (esp. IntN/FloatN) on SPIR-T. #332

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 12 additions & 11 deletions crates/rustc_codegen_spirv/src/linker/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -481,16 +481,6 @@ pub fn link(
simple_passes::remove_non_uniform_decorations(sess, &mut output)?;
}

{
let _timer = sess.timer("link_remove_unused_type_capabilities");
simple_passes::remove_unused_type_capabilities(&mut output);
}

{
let _timer = sess.timer("link_type_capability_check");
simple_passes::check_type_capabilities(sess, &output)?;
}

// NOTE(eddyb) SPIR-T pipeline is entirely limited to this block.
{
let (spv_words, module_or_err, lower_from_spv_timer) =
Expand Down Expand Up @@ -563,10 +553,16 @@ pub fn link(
module,
&opts.spirt_passes,
|name, _module| before_pass(name),
after_pass,
&mut after_pass,
);
}

{
let timer = before_pass("spirt_passes::validate");
spirt_passes::validate::validate(module);
after_pass("validate", module, timer);
}

{
let _timer = before_pass("spirt_passes::diagnostics::report_diagnostics");
spirt_passes::diagnostics::report_diagnostics(sess, opts, module).map_err(
Expand Down Expand Up @@ -634,6 +630,11 @@ pub fn link(
}
}

{
let _timer = sess.timer("link_remove_unused_type_capabilities");
simple_passes::remove_unused_type_capabilities(&mut output);
}

{
let _timer = sess.timer("link_gather_all_interface_vars_from_uses");
entry_interface::gather_all_interface_vars_from_uses(&mut output);
Expand Down
99 changes: 26 additions & 73 deletions crates/rustc_codegen_spirv/src/linker/simple_passes.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use super::{Result, get_name, get_names};
use super::{get_name, get_names};
use rspirv::dr::{Block, Function, Module};
use rspirv::spirv::{Decoration, ExecutionModel, Op, Word};
use rustc_codegen_spirv_types::Capability;
Expand All @@ -7,23 +7,32 @@ use rustc_session::Session;
use std::iter::once;
use std::mem::take;

/// Error marker type, indicating an integer/float type SPIR-V lacks support for.
struct UnsupportedType;

/// Returns the capability required for an integer type of the given width, if any.
fn capability_for_int_width(width: u32) -> Option<rspirv::spirv::Capability> {
match width {
fn capability_for_int_width(
width: u32,
) -> Result<Option<rspirv::spirv::Capability>, UnsupportedType> {
Ok(match width {
8 => Some(rspirv::spirv::Capability::Int8),
16 => Some(rspirv::spirv::Capability::Int16),
32 => None,
64 => Some(rspirv::spirv::Capability::Int64),
_ => None,
}
_ => return Err(UnsupportedType),
})
}

/// Returns the capability required for a float type of the given width, if any.
fn capability_for_float_width(width: u32) -> Option<rspirv::spirv::Capability> {
match width {
fn capability_for_float_width(
width: u32,
) -> Result<Option<rspirv::spirv::Capability>, UnsupportedType> {
Ok(match width {
16 => Some(rspirv::spirv::Capability::Float16),
32 => None,
64 => Some(rspirv::spirv::Capability::Float64),
_ => None,
}
_ => return Err(UnsupportedType),
})
}

pub fn shift_ids(module: &mut Module, add: u32) {
Expand Down Expand Up @@ -177,7 +186,7 @@ pub fn name_variables_pass(module: &mut Module) {
}

// Some instructions are only valid in fragment shaders. Check them.
pub fn check_fragment_insts(sess: &Session, module: &Module) -> Result<()> {
pub fn check_fragment_insts(sess: &Session, module: &Module) -> super::Result<()> {
let mut visited = vec![false; module.functions.len()];
let mut stack = Vec::new();
let mut names = None;
Expand Down Expand Up @@ -219,7 +228,7 @@ pub fn check_fragment_insts(sess: &Session, module: &Module) -> Result<()> {
names: &mut Option<FxHashMap<Word, &'m str>>,
index: usize,
func_id_to_idx: &FxHashMap<Word, usize>,
) -> Result<()> {
) -> super::Result<()> {
if visited[index] {
return Ok(());
}
Expand Down Expand Up @@ -284,70 +293,14 @@ pub fn check_fragment_insts(sess: &Session, module: &Module) -> Result<()> {
}
}

/// Check that types requiring specific capabilities have those capabilities declared.
///
/// This function validates that if a module uses types like u8/i8 (requiring Int8),
/// u16/i16 (requiring Int16), etc., the corresponding capabilities are declared.
pub fn check_type_capabilities(sess: &Session, module: &Module) -> Result<()> {
use rspirv::spirv::Capability;

// Collect declared capabilities
let declared_capabilities: FxHashSet<Capability> = module
.capabilities
.iter()
.map(|inst| inst.operands[0].unwrap_capability())
.collect();

let mut errors = Vec::new();

for inst in &module.types_global_values {
match inst.class.opcode {
Op::TypeInt => {
let width = inst.operands[0].unwrap_literal_bit32();
let signedness = inst.operands[1].unwrap_literal_bit32() != 0;
let type_name = if signedness { "i" } else { "u" };

if let Some(required_cap) = capability_for_int_width(width)
&& !declared_capabilities.contains(&required_cap)
{
errors.push(format!(
"`{type_name}{width}` type used without `OpCapability {required_cap:?}`"
));
}
}
Op::TypeFloat => {
let width = inst.operands[0].unwrap_literal_bit32();

if let Some(required_cap) = capability_for_float_width(width)
&& !declared_capabilities.contains(&required_cap)
{
errors.push(format!(
"`f{width}` type used without `OpCapability {required_cap:?}`"
));
}
}
_ => {}
}
}

if !errors.is_empty() {
let mut err = sess
.dcx()
.struct_err("Missing required capabilities for types");
for error in errors {
err = err.with_note(error);
}
Err(err.emit())
} else {
Ok(())
}
}

/// Remove type-related capabilities that are not required by any types in the module.
///
/// This function specifically targets Int8, Int16, Int64, Float16, and Float64 capabilities,
/// removing them if no types in the module require them. All other capabilities are preserved.
/// This is part of the fix for issue #300 where constant casts were creating unnecessary types.
//
// FIXME(eddyb) move this to a SPIR-T pass (potentially even using sets of used
// exts/caps that validation itself can collect while traversing the module).
pub fn remove_unused_type_capabilities(module: &mut Module) {
use rspirv::spirv::Capability;

Expand All @@ -359,13 +312,13 @@ pub fn remove_unused_type_capabilities(module: &mut Module) {
match inst.class.opcode {
Op::TypeInt => {
let width = inst.operands[0].unwrap_literal_bit32();
if let Some(cap) = capability_for_int_width(width) {
if let Ok(Some(cap)) = capability_for_int_width(width) {
needed_type_capabilities.insert(cap);
}
}
Op::TypeFloat => {
let width = inst.operands[0].unwrap_literal_bit32();
if let Some(cap) = capability_for_float_width(width) {
if let Ok(Some(cap)) = capability_for_float_width(width) {
needed_type_capabilities.insert(cap);
}
}
Expand All @@ -391,7 +344,7 @@ pub fn remove_unused_type_capabilities(module: &mut Module) {

/// Remove all [`Decoration::NonUniform`] if this module does *not* have [`Capability::ShaderNonUniform`].
/// This allows image asm to always declare `NonUniform` and not worry about conditional compilation.
pub fn remove_non_uniform_decorations(_sess: &Session, module: &mut Module) -> Result<()> {
pub fn remove_non_uniform_decorations(_sess: &Session, module: &mut Module) -> super::Result<()> {
let has_shader_non_uniform_capability = module.capabilities.iter().any(|inst| {
inst.class.opcode == Op::Capability
&& inst.operands[0].unwrap_capability() == Capability::ShaderNonUniform
Expand Down
5 changes: 4 additions & 1 deletion crates/rustc_codegen_spirv/src/linker/spirt_passes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ pub(crate) mod debuginfo;
pub(crate) mod diagnostics;
mod fuse_selects;
mod reduce;
pub(crate) mod validate;

use lazy_static::lazy_static;
use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
Expand Down Expand Up @@ -63,7 +64,7 @@ macro_rules! def_spv_spec_with_extra_well_known {
let spv_spec = spv::spec::Spec::get();
let wk = &spv_spec.well_known;

let decorations = match &spv_spec.operand_kinds[wk.Decoration] {
let decorations = match wk.Decoration.def() {
spv::spec::OperandKindDef::ValueEnum { variants } => variants,
_ => unreachable!(),
};
Expand Down Expand Up @@ -101,7 +102,9 @@ def_spv_spec_with_extra_well_known! {
OpCompositeExtract,
],
operand_kind: spv::spec::OperandKind = [
Capability,
ExecutionModel,
ImageFormat,
],
decoration: u32 = [
UserTypeGOOGLE,
Expand Down
Loading
Loading