diff --git a/CHANGELOG.md b/CHANGELOG.md index 29766287..e8f804ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] - ReleaseDate +### Added ⭐ +- Preserve ID operands of `OpExecutionModeId` and `OpDecorateId`. + `OpMemberDecorateIdEXT` and `OpacityMicromapIdKHR` are potential future uses of this interface. + ## [0.4.0] - 2024-10-07 ### Changed 🛠 diff --git a/src/lib.rs b/src/lib.rs index 4f1b084b..b1732a64 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -403,6 +403,14 @@ pub enum Attr { SpvAnnotation(spv::Inst), + /// SPIR-V annotations with ID operands. The target is the implicit first + /// operand. Other IDs refer to types, constants, or global variables. + /// Global variables use [`ConstKind::PtrToGlobalVar`]. + /// + /// All such annotations share one attribute. This avoids ordering interned + /// handles when annotations have the same literal operands. + SpvAnnotationsWithIds(OrdAssertEq)>>), + /// Some SPIR-V instructions, like `OpFunction`, take a bitflags operand /// that is effectively an optimization over using `OpDecorate`. // @@ -569,6 +577,8 @@ impl context::InternInCx for TypeKind { // HACK(eddyb) this is like `Either`, only used in `TypeKind::SpvInst`, // and only because SPIR-V type definitions can references both types and consts. +// +// `Attr::SpvAnnotationsWithIds` also uses `TypeOrConst` for its ID operands. #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub enum TypeOrConst { Type(Type), diff --git a/src/print/mod.rs b/src/print/mod.rs index 8532ab9d..6d75a83b 100644 --- a/src/print/mod.rs +++ b/src/print/mod.rs @@ -3000,6 +3000,22 @@ impl Print for Attr { ]) } + Attr::SpvAnnotationsWithIds(OrdAssertEq(annotations)) => { + return pretty::Fragment::new(annotations.iter().map(|(inst, inputs)| { + pretty::Fragment::new([ + printer.attr_style().apply("#[").into(), + printer.pretty_spv_inst( + printer.attr_style(), + inst.opcode, + &inst.imms, + std::iter::once(None) + .chain(inputs.iter().map(|input| Some(input.print(printer)))), + ), + printer.attr_style().apply("]").into(), + pretty::Node::ForceLineSeparation.into(), + ]) + })); + } Attr::SpvAnnotation(spv::Inst { opcode, imms }) => { let wk = &spv::spec::Spec::get().well_known; @@ -3108,6 +3124,16 @@ impl Print for QPtrMemUsage { } } +impl Print for TypeOrConst { + type Output = pretty::Fragment; + fn print(&self, printer: &Printer<'_>) -> pretty::Fragment { + match *self { + Self::Type(ty) => ty.print(printer), + Self::Const(ct) => ct.print(printer), + } + } +} + impl Print for TypeDef { type Output = AttrsAndDef; fn print(&self, printer: &Printer<'_>) -> AttrsAndDef { @@ -3174,10 +3200,7 @@ impl Print for TypeDef { printer.spv_op_style(), spv_inst.opcode, &spv_inst.imms, - type_and_const_inputs.iter().map(|&ty_or_ct| match ty_or_ct { - TypeOrConst::Type(ty) => ty.print(printer), - TypeOrConst::Const(ct) => ct.print(printer), - }), + type_and_const_inputs.iter().map(|input| input.print(printer)), ), TypeKind::SpvStringLiteralForExtInst => pretty::Fragment::new([ printer.error_style().apply("type_of").into(), diff --git a/src/spv/lift.rs b/src/spv/lift.rs index 5bbb6551..35a8a52d 100644 --- a/src/spv/lift.rs +++ b/src/spv/lift.rs @@ -200,6 +200,7 @@ impl Visitor<'_> for NeedsIdsCollector<'_> { Attr::Diagnostics(_) | Attr::QPtr(_) | Attr::SpvAnnotation { .. } + | Attr::SpvAnnotationsWithIds(_) | Attr::SpvBitflagsOperand(_) => {} Attr::DbgSrcLoc(OrdAssertEq(DbgSrcLoc { file_path, .. })) => { self.debug_strings.insert(&self.cx[file_path]); @@ -1501,32 +1502,45 @@ impl Module { let (result_id, attrs, import) = lazy_inst.result_id_attrs_and_import(self, ids); for attr in cx[attrs].attrs.iter() { + let mut emit_annotation = |inst: &spv::Inst, inputs: &[TypeOrConst]| { + let target_id = result_id.expect( + "FIXME: it shouldn't be possible to attach \ + attributes to instructions without an output", + ); + let input_ids = inputs.iter().map(|&input| { + let global = match input { + TypeOrConst::Type(ty) => Global::Type(ty), + TypeOrConst::Const(ct) => Global::Const(ct), + }; + ids.globals[&global] + }); + let inst = spv::InstWithIds { + without_ids: inst.clone(), + result_type_id: None, + result_id: None, + ids: iter::once(target_id).chain(input_ids).collect(), + }; + + if [wk.OpExecutionMode, wk.OpExecutionModeId].contains(&inst.opcode) { + execution_mode_insts.push(inst); + } else if [wk.OpName, wk.OpMemberName].contains(&inst.opcode) { + debug_name_insts.push(inst); + } else { + decoration_insts.push(inst); + } + }; + match attr { Attr::DbgSrcLoc(_) | Attr::Diagnostics(_) | Attr::QPtr(_) | Attr::SpvBitflagsOperand(_) => {} - Attr::SpvAnnotation(inst @ spv::Inst { opcode, .. }) => { - let target_id = result_id.expect( - "FIXME: it shouldn't be possible to attach \ - attributes to instructions without an output", - ); - - let inst = spv::InstWithIds { - without_ids: inst.clone(), - result_type_id: None, - result_id: None, - ids: iter::once(target_id).collect(), - }; - - if [wk.OpExecutionMode, wk.OpExecutionModeId].contains(opcode) { - execution_mode_insts.push(inst); - } else if [wk.OpName, wk.OpMemberName].contains(opcode) { - debug_name_insts.push(inst); - } else { - decoration_insts.push(inst); + Attr::SpvAnnotationsWithIds(OrdAssertEq(annotations)) => { + for (inst, inputs) in annotations { + emit_annotation(inst, inputs); } } + Attr::SpvAnnotation(inst) => emit_annotation(inst, &[]), } if let Some(import) = import { diff --git a/src/spv/lower.rs b/src/spv/lower.rs index a2902c4a..9b4973c9 100644 --- a/src/spv/lower.rs +++ b/src/spv/lower.rs @@ -6,8 +6,8 @@ use crate::{ AddrSpace, Attr, AttrSet, Const, ConstDef, ConstKind, Context, DataInstDef, DataInstKind, DbgSrcLoc, DeclDef, Diag, EntityDefs, EntityList, ExportKey, Exportee, Func, FuncDecl, FuncDefBody, FuncParam, FxIndexMap, GlobalVarDecl, GlobalVarDefBody, Import, InternedStr, - Module, NodeDef, NodeKind, Region, RegionDef, RegionInputDecl, SelectionKind, Type, TypeDef, - TypeKind, TypeOrConst, Value, cfg, print, + Module, NodeDef, NodeKind, OrdAssertEq, Region, RegionDef, RegionInputDecl, SelectionKind, + Type, TypeDef, TypeKind, TypeOrConst, Value, cfg, print, }; use rustc_hash::FxHashMap; use smallvec::SmallVec; @@ -183,6 +183,7 @@ impl Module { let mut has_memory_model = false; let mut pending_attrs = FxHashMap::::default(); + let mut pending_annotations = FxHashMap::>::default(); let mut pending_imports = FxHashMap::::default(); let mut pending_exports = vec![]; let mut current_dbg_src_loc = None; @@ -256,6 +257,39 @@ impl Module { let mut attrs = inst.result_id.and_then(|id| pending_attrs.remove(&id)).unwrap_or_default(); + // SPIR-V requires annotation operands to be defined before the target. + // Resolve them when the target is reached. + if let Some(annotations) = inst.result_id.and_then(|id| pending_annotations.remove(&id)) + { + let mut resolved_annotations = Vec::with_capacity(annotations.len()); + for annotation in annotations { + let is_execution_mode = annotation.opcode == wk.OpExecutionModeId; + if is_execution_mode && opcode != wk.OpFunction { + return Err(invalid("OpExecutionModeId target is not a function")); + } + let inputs = annotation.ids[1..] + .iter() + .map(|id| match id_defs.get(id) { + Some(&IdDef::Type(ty)) if is_execution_mode => { + Ok(TypeOrConst::Type(ty)) + } + Some(&IdDef::Const(ct)) + if !is_execution_mode + || !matches!(cx[ct].kind, ConstKind::PtrToGlobalVar(_)) => + { + Ok(TypeOrConst::Const(ct)) + } + _ => Err(invalid(&format!( + "unsupported or undefined operand %{id} in {}", + annotation.opcode.name() + ))), + }) + .collect::>()?; + resolved_annotations.push((annotation.without_ids, inputs)); + } + attrs.attrs.insert(Attr::SpvAnnotationsWithIds(OrdAssertEq(resolved_annotations))); + } + if let Some(dbg_src_loc) = current_dbg_src_loc { attrs.set_dbg_src_loc(dbg_src_loc); } @@ -477,12 +511,12 @@ impl Module { Seq::EntryPoint } else if [ wk.OpExecutionMode, - wk.OpExecutionModeId, // FIXME(eddyb) not actually supported + wk.OpExecutionModeId, wk.OpName, wk.OpMemberName, wk.OpDecorate, wk.OpMemberDecorate, - wk.OpDecorateId, // FIXME(eddyb) not actually supported + wk.OpDecorateId, wk.OpDecorateString, wk.OpMemberDecorateString, ] @@ -491,10 +525,6 @@ impl Module { assert!(inst.result_type_id.is_none() && inst.result_id.is_none()); let target_id = inst.ids[0]; - if inst.ids.len() > 1 { - return Err(invalid("unsupported decoration with ID")); - } - match inst.imms[..] { // Special-case `OpDecorate LinkageAttributes ... Import|Export`. [ @@ -517,6 +547,9 @@ impl Module { } } + _ if inst.ids.len() > 1 => { + pending_annotations.entry(target_id).or_default().push(inst); + } _ => { pending_attrs .entry(target_id) @@ -817,8 +850,9 @@ impl Module { return Err(invalid("missing OpMemoryModel")); } - if !pending_attrs.is_empty() { - let ids = pending_attrs.keys().collect::>(); + if !pending_attrs.is_empty() || !pending_annotations.is_empty() { + let ids = + pending_attrs.keys().chain(pending_annotations.keys()).collect::>(); return Err(invalid(&format!("decorated IDs never defined: {ids:?}"))); } diff --git a/src/transform.rs b/src/transform.rs index 74670d34..6a38a593 100644 --- a/src/transform.rs +++ b/src/transform.rs @@ -320,6 +320,16 @@ impl InnerTransform for Attr { Transformed::Unchanged } + Attr::SpvAnnotationsWithIds(OrdAssertEq(annotations)) => { + Transformed::map_iter(annotations.iter(), |(inst, inputs)| { + Transformed::map_iter(inputs.iter(), |input| { + input.inner_transform_with(transformer) + }) + .map(|inputs| (inst.clone(), inputs.collect())) + }) + .map(|annotations| Attr::SpvAnnotationsWithIds(OrdAssertEq(annotations.collect()))) + } + &Attr::DbgSrcLoc(OrdAssertEq(DbgSrcLoc { file_path, start_line_col, @@ -424,6 +434,15 @@ impl InnerTransform for QPtrMemUsageKind { } } +impl InnerTransform for TypeOrConst { + fn inner_transform_with(&self, transformer: &mut impl Transformer) -> Transformed { + match *self { + Self::Type(ty) => transformer.transform_type_use(ty).map(Self::Type), + Self::Const(ct) => transformer.transform_const_use(ct).map(Self::Const), + } + } +} + impl InnerTransform for TypeDef { fn inner_transform_with(&self, transformer: &mut impl Transformer) -> Transformed { let Self { attrs, kind } = self; @@ -435,15 +454,7 @@ impl InnerTransform for TypeDef { TypeKind::SpvInst { spv_inst, type_and_const_inputs } => Transformed::map_iter( type_and_const_inputs.iter(), - |ty_or_ct| match *ty_or_ct { - TypeOrConst::Type(ty) => transform!({ - ty -> transformer.transform_type_use(ty), - } => TypeOrConst::Type(ty)), - - TypeOrConst::Const(ct) => transform!({ - ct -> transformer.transform_const_use(ct), - } => TypeOrConst::Const(ct)), - }, + |input| input.inner_transform_with(transformer), ).map(|new_iter| TypeKind::SpvInst { spv_inst: spv_inst.clone(), type_and_const_inputs: new_iter.collect(), diff --git a/src/visit.rs b/src/visit.rs index 1829c466..f08b93a7 100644 --- a/src/visit.rs +++ b/src/visit.rs @@ -234,6 +234,14 @@ impl InnerVisit for Attr { match self { Attr::Diagnostics(_) | Attr::SpvAnnotation(_) | Attr::SpvBitflagsOperand(_) => {} + Attr::SpvAnnotationsWithIds(OrdAssertEq(annotations)) => { + for (_, inputs) in annotations { + for input in inputs { + input.inner_visit_with(visitor); + } + } + } + &Attr::DbgSrcLoc(OrdAssertEq(DbgSrcLoc { file_path: _, start_line_col: _, @@ -313,6 +321,15 @@ impl InnerVisit for QPtrMemUsageKind { } } +impl InnerVisit for TypeOrConst { + fn inner_visit_with<'a>(&'a self, visitor: &mut impl Visitor<'a>) { + match *self { + Self::Type(ty) => visitor.visit_type_use(ty), + Self::Const(ct) => visitor.visit_const_use(ct), + } + } +} + impl InnerVisit for TypeDef { fn inner_visit_with<'a>(&'a self, visitor: &mut impl Visitor<'a>) { let Self { attrs, kind } = self; @@ -322,11 +339,8 @@ impl InnerVisit for TypeDef { TypeKind::QPtr | TypeKind::SpvStringLiteralForExtInst => {} TypeKind::SpvInst { spv_inst: _, type_and_const_inputs } => { - for &ty_or_ct in type_and_const_inputs { - match ty_or_ct { - TypeOrConst::Type(ty) => visitor.visit_type_use(ty), - TypeOrConst::Const(ct) => visitor.visit_const_use(ct), - } + for input in type_and_const_inputs { + input.inner_visit_with(visitor); } } }