Skip to content
Closed
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 🛠
Expand Down
10 changes: 10 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<(spv::Inst, Vec<TypeOrConst>)>>),

/// Some SPIR-V instructions, like `OpFunction`, take a bitflags operand
/// that is effectively an optimization over using `OpDecorate`.
//
Expand Down Expand Up @@ -569,6 +577,8 @@ impl context::InternInCx<Type> for TypeKind {

// HACK(eddyb) this is like `Either<Type, Const>`, 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),
Expand Down
31 changes: 27 additions & 4 deletions src/print/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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(),
Expand Down
52 changes: 33 additions & 19 deletions src/spv/lift.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
Expand Down Expand Up @@ -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 {
Expand Down
54 changes: 44 additions & 10 deletions src/spv/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -183,6 +183,7 @@ impl Module {

let mut has_memory_model = false;
let mut pending_attrs = FxHashMap::<spv::Id, crate::AttrSetDef>::default();
let mut pending_annotations = FxHashMap::<spv::Id, Vec<spv::InstWithIds>>::default();
let mut pending_imports = FxHashMap::<spv::Id, Import>::default();
let mut pending_exports = vec![];
let mut current_dbg_src_loc = None;
Expand Down Expand Up @@ -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::<Result<_, _>>()?;
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);
}
Expand Down Expand Up @@ -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,
]
Expand All @@ -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`.
[
Expand All @@ -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)
Expand Down Expand Up @@ -817,8 +850,9 @@ impl Module {
return Err(invalid("missing OpMemoryModel"));
}

if !pending_attrs.is_empty() {
let ids = pending_attrs.keys().collect::<BTreeSet<_>>();
if !pending_attrs.is_empty() || !pending_annotations.is_empty() {
let ids =
pending_attrs.keys().chain(pending_annotations.keys()).collect::<BTreeSet<_>>();
return Err(invalid(&format!("decorated IDs never defined: {ids:?}")));
}

Expand Down
29 changes: 20 additions & 9 deletions src/transform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -424,6 +434,15 @@ impl InnerTransform for QPtrMemUsageKind {
}
}

impl InnerTransform for TypeOrConst {
fn inner_transform_with(&self, transformer: &mut impl Transformer) -> Transformed<Self> {
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<Self> {
let Self { attrs, kind } = self;
Expand All @@ -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(),
Expand Down
24 changes: 19 additions & 5 deletions src/visit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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: _,
Expand Down Expand Up @@ -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;
Expand All @@ -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);
}
}
}
Expand Down
Loading