diff --git a/.gitmodules b/.gitmodules index d5cbc7da..acd70481 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,4 +1,3 @@ [submodule "khronos-spec/SPIRV-Headers"] path = khronos-spec/SPIRV-Headers url = https://github.com/KhronosGroup/SPIRV-Headers - branch = vulkan-sdk-1.3.290 diff --git a/README.md b/README.md index 3e3baf2b..2901b85e 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,7 @@ fn main() -> @location(0) i32 { ```cxx #[spv.Decoration.Flat] #[spv.Decoration.Location(Location: 0)] -global_var GV0 in spv.StorageClass.Output: s32 +global_var GV0(spv.StorageClass.Output): s32 func F0() -> spv.OpTypeVoid { loop(v0: s32 <- 1s32, v1: s32 <- 1s32) { diff --git a/examples/spv-lower-link-qptr-lift.rs b/examples/spv-lower-link-qptr-lift.rs index d4b788d0..f71238bb 100644 --- a/examples/spv-lower-link-qptr-lift.rs +++ b/examples/spv-lower-link-qptr-lift.rs @@ -80,10 +80,10 @@ fn main() -> std::io::Result<()> { after_pass("", &module)?; // HACK(eddyb) this is roughly what Rust-GPU would need. - let layout_config = &spirt::qptr::LayoutConfig { + let layout_config = &spirt::mem::LayoutConfig { abstract_bool_size_align: (1, 1), logical_ptr_size_align: (4, 4), - ..spirt::qptr::LayoutConfig::VULKAN_SCALAR_LAYOUT + ..spirt::mem::LayoutConfig::VULKAN_SCALAR_LAYOUT }; eprint_duration(|| { @@ -92,9 +92,11 @@ fn main() -> std::io::Result<()> { eprintln!("qptr::lower_from_spv_ptrs"); after_pass("qptr::lower_from_spv_ptrs", &module)?; - eprint_duration(|| spirt::passes::qptr::analyze_uses(&mut module, layout_config)); - eprintln!("qptr::analyze_uses"); - after_pass("qptr::analyze_uses", &module)?; + eprint_duration(|| { + spirt::passes::qptr::analyze_mem_accesses(&mut module, layout_config) + }); + eprintln!("mem::analyze_accesses"); + after_pass("mem::analyze_accesses", &module)?; eprint_duration(|| spirt::passes::qptr::lift_to_spv_ptrs(&mut module, layout_config)); eprintln!("qptr::lift_to_spv_ptrs"); diff --git a/khronos-spec/SPIRV-Headers b/khronos-spec/SPIRV-Headers index 2acb319a..49654312 160000 --- a/khronos-spec/SPIRV-Headers +++ b/khronos-spec/SPIRV-Headers @@ -1 +1 @@ -Subproject commit 2acb319af38d43be3ea76bfabf3998e5281d8d12 +Subproject commit 496543121ce6419f23d6fa5d7194ba66c36212d2 diff --git a/src/cfg.rs b/src/cfg.rs index 2e87a559..c891da02 100644 --- a/src/cfg.rs +++ b/src/cfg.rs @@ -1022,41 +1022,37 @@ impl<'a> Structurizer<'a> { }); let (loop_header_to_exit_targets, incoming_edge_counts_including_loop_exits) = - func_def_body - .unstructured_cfg - .as_ref() - .map(|cfg| { - let loop_header_to_exit_targets = { - let mut loop_finder = LoopFinder::new(cfg); - loop_finder.find_earliest_scc_root_of(func_def_body.body); - loop_finder.loop_header_to_exit_targets - }; + func_def_body.unstructured_cfg.as_ref().map_or_default(|cfg| { + let loop_header_to_exit_targets = { + let mut loop_finder = LoopFinder::new(cfg); + loop_finder.find_earliest_scc_root_of(func_def_body.body); + loop_finder.loop_header_to_exit_targets + }; - let mut state = TraversalState { - incoming_edge_counts: EntityOrientedDenseMap::new(), + let mut state = TraversalState { + incoming_edge_counts: EntityOrientedDenseMap::new(), - pre_order_visit: |_| {}, - post_order_visit: |_| {}, - reverse_targets: false, - }; - cfg.traverse_whole_func(func_def_body, &mut state); - - // HACK(eddyb) treat loop exits as "false edges", that their - // respective loop header "owns", such that structurization - // naturally stops at those loop exits, instead of continuing - // greedily into the loop exterior (producing "maximal loops"). - for loop_exit_targets in loop_header_to_exit_targets.values() { - for &exit_target in loop_exit_targets { - *state - .incoming_edge_counts - .entry(exit_target) - .get_or_insert(Default::default()) += IncomingEdgeCount::ONE; - } + pre_order_visit: |_| {}, + post_order_visit: |_| {}, + reverse_targets: false, + }; + cfg.traverse_whole_func(func_def_body, &mut state); + + // HACK(eddyb) treat loop exits as "false edges", that their + // respective loop header "owns", such that structurization + // naturally stops at those loop exits, instead of continuing + // greedily into the loop exterior (producing "maximal loops"). + for loop_exit_targets in loop_header_to_exit_targets.values() { + for &exit_target in loop_exit_targets { + *state + .incoming_edge_counts + .entry(exit_target) + .get_or_insert(Default::default()) += IncomingEdgeCount::ONE; } + } - (loop_header_to_exit_targets, state.incoming_edge_counts) - }) - .unwrap_or_default(); + (loop_header_to_exit_targets, state.incoming_edge_counts) + }); Self { cx, @@ -1548,8 +1544,7 @@ impl<'a> Structurizer<'a> { // Cache the edge count for backedges (which later get turned into loops). let accumulated_backedge_count = deferred_edges .get_edge_bundle_by_target(DeferredTarget::Region(region)) - .map(|backedge| backedge.accumulated_count) - .unwrap_or_default(); + .map_or_default(|backedge| backedge.accumulated_count); let old_state = self.structurize_region_state.insert( region, @@ -2035,8 +2030,9 @@ impl<'a> Structurizer<'a> { } }; - let condition = Some(condition) - .filter(|_| else_target_and_inputs.is_some()) + let condition = else_target_and_inputs + .is_some() + .then_some(condition) .map(|cond| self.materialize_lazy_cond(&cond)); let branch_control_inst = ControlInst { attrs: AttrSet::default(), diff --git a/src/context.rs b/src/context.rs index e5aa3c80..26e0223f 100644 --- a/src/context.rs +++ b/src/context.rs @@ -348,19 +348,14 @@ pub struct EntityOrientedDenseMap, V> { // since the ideal state is one chunk per map, the slow case might never be hit, // unless one `EntityOrientedDenseMap` is used with more than one `EntityDefs`, // which could still maybe be implemented more efficiently than `FxHashMap`. -#[derive(Clone)] +#[derive(Clone, Default)] enum SmallFxHashMap { + #[default] Empty, One(K, V), More(FxHashMap), } -impl Default for SmallFxHashMap { - fn default() -> Self { - Self::Empty - } -} - impl SmallFxHashMap { fn get_mut_or_insert_default(&mut self, k: K) -> &mut V { // HACK(eddyb) to avoid borrowing issues, this is done in two stages: diff --git a/src/lib.rs b/src/lib.rs index 4f1b084b..5ad6c78b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -71,7 +71,6 @@ clippy::dbg_macro, clippy::debug_assert_with_mut_call, clippy::doc_markdown, - clippy::empty_enum, clippy::enum_glob_use, clippy::exit, clippy::expl_impl_clone_on_copy, @@ -82,7 +81,6 @@ clippy::flat_map_option, clippy::float_cmp_const, clippy::fn_params_excessive_bools, - clippy::from_iter_instead_of_collect, clippy::if_let_mutex, clippy::implicit_clone, clippy::imprecise_flops, @@ -121,7 +119,6 @@ clippy::string_add_assign, clippy::string_add, clippy::string_lit_as_bytes, - clippy::string_to_string, clippy::todo, clippy::trait_duplication_in_bounds, clippy::unimplemented, @@ -169,6 +166,7 @@ pub mod passes { pub mod link; pub mod qptr; } +pub mod mem; pub mod qptr; pub mod spv; @@ -397,11 +395,28 @@ pub enum Attr { // of `AttrSetDef::{dbg_src_loc,set_dbg_src_loc}`. DbgSrcLoc(OrdAssertEq), + /// Memory-specific attributes (see [`mem::MemAttr`]). + #[from] + Mem(mem::MemAttr), + /// `QPtr`-specific attributes (see [`qptr::QPtrAttr`]). #[from] QPtr(qptr::QPtrAttr), - SpvAnnotation(spv::Inst), + SpvAnnotation { + spv_inst: spv::Inst, + + /// If present, each "instance" represents a different use of `spv_inst`, + /// grouped together only because the non-ID operands (enumerand/literals) + /// inside `spv::Inst` are not enough to uniquely identify an annotation + /// (i.e. at least some of the `Const` IDs are semantically part of the + /// "key" side `Attr`, which should normally be outside the `OrdAssertEq`). + // + // HACK(eddyb) this is enough of a complication to furthger call into + // question the use of ordered sets for `AttrSet`s, in the first place. + #[allow(clippy::type_complexity)] + per_instance_const_inputs: Option>>>>, + }, /// Some SPIR-V instructions, like `OpFunction`, take a bitflags operand /// that is effectively an optimization over using `OpDecorate`. @@ -489,7 +504,7 @@ pub enum DiagMsgPart { Attrs(AttrSet), Type(Type), Const(Const), - QPtrUsage(qptr::QPtrUsage), + MemAccesses(mem::MemAccesses), } /// Wrapper to limit `Ord` for interned index types (e.g. [`InternedStr`]) @@ -555,6 +570,10 @@ pub enum TypeKind { type_and_const_inputs: SmallVec<[TypeOrConst; 2]>, }, + /// The type of a [`ConstKind::SpvTypeOperand`] constant, i.e. a [`Type`] + /// embedded in a [`Value`] to be passed as a SPIR-V operand. + SpvTypeOperand, + /// The type of a [`ConstKind::SpvStringLiteralForExtInst`] constant, i.e. /// a SPIR-V `OpString` with no actual type in SPIR-V. SpvStringLiteralForExtInst, @@ -590,7 +609,13 @@ pub struct ConstDef { #[derive(Clone, PartialEq, Eq, Hash)] pub enum ConstKind { + // FIXME(eddyb) maybe merge these? however, their connection is somewhat + // tenuous (being one of the LLVM-isms SPIR-V inherited, among other things), + // there's still the need to rename "global variable" post-`Var`-refactor, + // and last but not least, `PtrToFunc` needs `SPV_INTEL_function_pointers`, + // an OpenCL-only extension Intel came up with for their own SPIR-V tooling. PtrToGlobalVar(GlobalVar), + PtrToFunc(Func), // HACK(eddyb) this is a fallback case that should become increasingly rare // (especially wrt recursive consts), `Rc` means it can't bloat `ConstDef`. @@ -598,6 +623,9 @@ pub enum ConstKind { spv_inst_and_const_inputs: Rc<(spv::Inst, SmallVec<[Const; 4]>)>, }, + /// Type used as an operand to a SPIR-V instruction (other than result type). + SpvTypeOperand(Type), + /// SPIR-V `OpString`, but only when used as an operand for an `OpExtInst`, /// which can't have literals itself - for non-string literals `OpConstant*` /// are readily usable, but only `OpString` is supported for string literals. @@ -638,7 +666,7 @@ pub struct GlobalVarDecl { /// When `type_of_ptr_to` is `QPtr`, `shape` must be used to describe the /// global variable (see `GlobalVarShape`'s documentation for more details). - pub shape: Option, + pub shape: Option, /// The address space the global variable will be allocated into. pub addr_space: AddrSpace, @@ -679,7 +707,7 @@ pub struct FuncDecl { pub def: DeclDef, } -#[derive(Copy, Clone)] +#[derive(Copy, Clone, PartialEq, Eq)] pub struct FuncParam { pub attrs: AttrSet, @@ -947,6 +975,10 @@ pub enum DataInstKind { // to avoid needing special handling for recursion where it's impossible. FuncCall(Func), + /// Memory-specific operations (see [`mem::MemOp`]). + #[from] + Mem(mem::MemOp), + /// `QPtr`-specific operations (see [`qptr::QPtrOp`]). #[from] QPtr(qptr::QPtrOp), diff --git a/src/qptr/analyze.rs b/src/mem/analyze.rs similarity index 69% rename from src/qptr/analyze.rs rename to src/mem/analyze.rs index f1f1e23c..f9b8b28b 100644 --- a/src/qptr/analyze.rs +++ b/src/mem/analyze.rs @@ -1,10 +1,10 @@ -//! [`QPtr`](crate::TypeKind::QPtr) usage analysis (for legalizing/lifting). +//! Memory access analysis (for "type recovery", i.e. untyped -> typed memory). +// +// TODO(eddyb) consider renaming this to `mem::typed`. -// HACK(eddyb) sharing layout code with other modules. -use super::{QPtrMemUsageKind, layout::*}; - -use super::{QPtrAttr, QPtrMemUsage, QPtrOp, QPtrUsage, shapes}; use crate::func_at::FuncAt; +use crate::mem::{DataHapp, DataHappKind, MemAccesses, MemAttr, MemOp, shapes}; +use crate::qptr::{QPtrAttr, QPtrOp}; use crate::visit::{InnerVisit, Visitor}; use crate::{ AddrSpace, Attr, AttrSet, AttrSetDef, Const, ConstKind, Context, DataInst, DataInstKind, @@ -19,14 +19,18 @@ use std::num::NonZeroU32; use std::ops::Bound; use std::rc::Rc; +// HACK(eddyb) sharing layout code with other modules. +// FIXME(eddyb) can this just be a non-glob import? +use crate::mem::layout::*; + #[derive(Clone)] struct AnalysisError(Diag); -struct UsageMerger<'a> { +struct AccessMerger<'a> { layout_cache: &'a LayoutCache<'a>, } -/// Result type for `UsageMerger` methods - unlike `Result`, +/// Result type for `AccessMerger` methods - unlike `Result`, /// this always keeps the `T` value, even in the case of an error. struct MergeResult { merged: T, @@ -53,28 +57,28 @@ impl MergeResult { } } -impl UsageMerger<'_> { - fn merge(&self, a: QPtrUsage, b: QPtrUsage) -> MergeResult { +impl AccessMerger<'_> { + fn merge(&self, a: MemAccesses, b: MemAccesses) -> MergeResult { match (a, b) { ( - QPtrUsage::Handles(shapes::Handle::Opaque(a)), - QPtrUsage::Handles(shapes::Handle::Opaque(b)), - ) if a == b => MergeResult::ok(QPtrUsage::Handles(shapes::Handle::Opaque(a))), + MemAccesses::Handles(shapes::Handle::Opaque(a)), + MemAccesses::Handles(shapes::Handle::Opaque(b)), + ) if a == b => MergeResult::ok(MemAccesses::Handles(shapes::Handle::Opaque(a))), ( - QPtrUsage::Handles(shapes::Handle::Buffer(a_as, a)), - QPtrUsage::Handles(shapes::Handle::Buffer(b_as, b)), + MemAccesses::Handles(shapes::Handle::Buffer(a_as, a)), + MemAccesses::Handles(shapes::Handle::Buffer(b_as, b)), ) => { // HACK(eddyb) the `AddrSpace` field is entirely redundant. assert!(a_as == AddrSpace::Handles && b_as == AddrSpace::Handles); - self.merge_mem(a, b).map(|usage| { - QPtrUsage::Handles(shapes::Handle::Buffer(AddrSpace::Handles, usage)) + self.merge_data(a, b).map(|happ| { + MemAccesses::Handles(shapes::Handle::Buffer(AddrSpace::Handles, happ)) }) } - (QPtrUsage::Memory(a), QPtrUsage::Memory(b)) => { - self.merge_mem(a, b).map(QPtrUsage::Memory) + (MemAccesses::Data(a), MemAccesses::Data(b)) => { + self.merge_data(a, b).map(MemAccesses::Data) } (a, b) => { @@ -94,9 +98,9 @@ impl UsageMerger<'_> { } } - fn merge_mem(&self, a: QPtrMemUsage, b: QPtrMemUsage) -> MergeResult { - // NOTE(eddyb) this is possible because it's currently impossible for - // the merged usage to be outside the bounds of *both* `a` and `b`. + fn merge_data(&self, a: DataHapp, b: DataHapp) -> MergeResult { + // NOTE(eddyb) this is doable because it's currently impossible for + // the merged HAPP to be outside the bounds of *both* `a` and `b`. let max_size = match (a.max_size, b.max_size) { (Some(a), Some(b)) => Some(a.max(b)), (None, _) | (_, None) => None, @@ -107,14 +111,14 @@ impl UsageMerger<'_> { // to make it easier to handle all the possible interactions below, // by skipping (or deprioritizing, if supported) the "wrong direction". let mut sorted = [a, b]; - sorted.sort_by_key(|usage| { + sorted.sort_by_key(|happ| { #[derive(PartialEq, Eq, PartialOrd, Ord)] enum MaxSize { Fixed(T), // FIXME(eddyb) this probably needs to track "min size"? Dynamic, } - let max_size = usage.max_size.map_or(MaxSize::Dynamic, MaxSize::Fixed); + let max_size = happ.max_size.map_or(MaxSize::Dynamic, MaxSize::Fixed); // When sizes are equal, pick the more restrictive side. #[derive(PartialEq, Eq, PartialOrd, Ord)] @@ -124,21 +128,21 @@ impl UsageMerger<'_> { Exact, } #[allow(clippy::match_same_arms)] - let type_strictness = match usage.kind { - QPtrMemUsageKind::Unused | QPtrMemUsageKind::OffsetBase(_) => TypeStrictness::Any, + let type_strictness = match happ.kind { + DataHappKind::Dead | DataHappKind::Disjoint(_) => TypeStrictness::Any, - QPtrMemUsageKind::DynOffsetBase { .. } => TypeStrictness::Array, + DataHappKind::Repeated { .. } => TypeStrictness::Array, // FIXME(eddyb) this should be `Any`, even if in theory it // could contain arrays or structs that need decomposition // (note that, for typed reads/write, arrays do not need to be // *indexed* to work, i.e. they *do not* require `DynOffset`s, - // `Offset`s suffice, and for them `DynOffsetBase` is at most - // a "run-length"/deduplication optimization over `OffsetBase`). - // NOTE(eddyb) this should still prefer `OpTypeVector` over `DynOffsetBase`! - QPtrMemUsageKind::DirectAccess(_) => TypeStrictness::Exact, + // `Offset`s suffice, and for them `Repeated` is at most + // a "run-length"/deduplication optimization over `Disjoint`). + // NOTE(eddyb) this should still prefer `OpTypeVector` over `Repeated`! + DataHappKind::Direct(_) => TypeStrictness::Exact, - QPtrMemUsageKind::StrictlyTyped(_) => TypeStrictness::Exact, + DataHappKind::StrictlyTyped(_) => TypeStrictness::Exact, }; (max_size, type_strictness) @@ -146,33 +150,28 @@ impl UsageMerger<'_> { let [b, a] = sorted; assert_eq!(max_size, a.max_size); - self.merge_mem_at(a, 0, b) + self.merge_data_at(a, 0, b) } // FIXME(eddyb) make the name of this clarify the asymmetric effect, something // like "make `a` compatible with `offset => b`". - fn merge_mem_at( - &self, - a: QPtrMemUsage, - b_offset_in_a: u32, - b: QPtrMemUsage, - ) -> MergeResult { - // NOTE(eddyb) this is possible because it's currently impossible for - // the merged usage to be outside the bounds of *both* `a` and `b`. + fn merge_data_at(&self, a: DataHapp, b_offset_in_a: u32, b: DataHapp) -> MergeResult { + // NOTE(eddyb) this is doable because it's currently impossible for + // the merged HAPP to be outside the bounds of *both* `a` and `b`. let max_size = match (a.max_size, b.max_size) { (Some(a), Some(b)) => Some(a.max(b.checked_add(b_offset_in_a).unwrap())), (None, _) | (_, None) => None, }; - // HACK(eddyb) we require biased `a` vs `b` (see `merge_mem` method above). + // HACK(eddyb) we require biased `a` vs `b` (see `merge_data` method above). assert_eq!(max_size, a.max_size); // Decompose the "smaller" and/or "less strict" side (`b`) first. match b.kind { - // `Unused`s are always ignored. - QPtrMemUsageKind::Unused => return MergeResult::ok(a), + // `Dead`s are always ignored. + DataHappKind::Dead => return MergeResult::ok(a), - QPtrMemUsageKind::OffsetBase(b_entries) + DataHappKind::Disjoint(b_entries) if { // HACK(eddyb) this check was added later, after it turned out // that *deep* flattening of arbitrary offsets in `b` would've @@ -190,11 +189,11 @@ impl UsageMerger<'_> { let mut ab = a; let mut all_errors = None; - for (b_offset, b_sub_usage) in b_entries { - let MergeResult { merged, error: new_error } = self.merge_mem_at( + for (b_offset, b_sub_happ) in b_entries { + let MergeResult { merged, error: new_error } = self.merge_data_at( ab, b_offset.checked_add(b_offset_in_a).unwrap(), - b_sub_usage, + b_sub_happ, ); ab = merged; @@ -218,7 +217,7 @@ impl UsageMerger<'_> { // FIXME(eddyb) should this mean `MergeResult` should // use `errors: Vec` instead of `Option`? error: all_errors.map(|AnalysisError(mut e)| { - e.message.insert(0, "merge_mem: conflicts:\n".into()); + e.message.insert(0, "merge_data: conflicts:\n".into()); AnalysisError(e) }), }; @@ -228,16 +227,15 @@ impl UsageMerger<'_> { } let kind = match a.kind { - // `Unused`s are always ignored. - QPtrMemUsageKind::Unused => MergeResult::ok(b.kind), + // `Dead`s are always ignored. + DataHappKind::Dead => MergeResult::ok(b.kind), - // Typed leaves must support any possible usage applied to them - // (when they match, or overtake, that usage, in size, like here), + // Typed leaves must support any possible accesses applied to them + // (when they match, or overtake, that access, in size, like here), // with their inherent hierarchy (i.e. their array/struct nesting). - QPtrMemUsageKind::StrictlyTyped(a_type) | QPtrMemUsageKind::DirectAccess(a_type) => { + DataHappKind::StrictlyTyped(a_type) | DataHappKind::Direct(a_type) => { let b_type_at_offset_0 = match b.kind { - QPtrMemUsageKind::StrictlyTyped(b_type) - | QPtrMemUsageKind::DirectAccess(b_type) + DataHappKind::StrictlyTyped(b_type) | DataHappKind::Direct(b_type) if b_offset_in_a == 0 => { Some(b_type) @@ -247,11 +245,11 @@ impl UsageMerger<'_> { let ty = if Some(a_type) == b_type_at_offset_0 { MergeResult::ok(a_type) } else { - // Returns `Some(MergeResult::ok(ty))` iff `usage` is valid + // Returns `Some(MergeResult::ok(ty))` iff `happ` is valid // for type `ty`, and `None` iff invalid w/o layout errors - // (see `mem_layout_supports_usage_at_offset` for more details). - let type_supporting_usage_at_offset = |ty, usage_offset, usage| { - let supports_usage = match self.layout_of(ty) { + // (see `mem_layout_supports_happ_at_offset` for more details). + let type_supporting_happ_at_offset = |ty, happ_offset, happ| { + let supports_happ = match self.layout_of(ty) { // FIXME(eddyb) should this be `unreachable!()`? also, is // it possible to end up with `ty` being an `OpTypeStruct` // decorated with `Block`, showing up as a `Buffer` handle? @@ -261,27 +259,27 @@ impl UsageMerger<'_> { // conflict with our own `Block`-annotated wrapper. Ok(TypeLayout::Handle(_) | TypeLayout::HandleArray(..)) => { Err(AnalysisError(Diag::bug([ - "merge_mem: impossible handle type for QPtrMemUsage".into(), + "merge_data: impossible handle type for DataHapp".into(), ]))) } Ok(TypeLayout::Concrete(concrete)) => { - Ok(concrete.supports_usage_at_offset(usage_offset, usage)) + Ok(concrete.supports_happ_at_offset(happ_offset, happ)) } Err(e) => Err(e), }; - match supports_usage { + match supports_happ { Ok(false) => None, Ok(true) | Err(_) => { - Some(MergeResult { merged: ty, error: supports_usage.err() }) + Some(MergeResult { merged: ty, error: supports_happ.err() }) } } }; - type_supporting_usage_at_offset(a_type, b_offset_in_a, &b) + type_supporting_happ_at_offset(a_type, b_offset_in_a, &b) .or_else(|| { b_type_at_offset_0.and_then(|b_type_at_offset_0| { - type_supporting_usage_at_offset(b_type_at_offset_0, 0, &a) + type_supporting_happ_at_offset(b_type_at_offset_0, 0, &a) }) }) .unwrap_or_else(|| { @@ -290,11 +288,11 @@ impl UsageMerger<'_> { // FIXME(eddyb) this should ideally embed the types in the // error somehow. error: Some(AnalysisError(Diag::bug([ - "merge_mem: type subcomponents incompatible with usage (" + "merge_data: type subcomponents incompatible with accesses (" .into(), - QPtrUsage::Memory(a.clone()).into(), + MemAccesses::Data(a.clone()).into(), " vs ".into(), - QPtrUsage::Memory(b.clone()).into(), + MemAccesses::Data(b.clone()).into(), ")".into(), ]))), } @@ -307,19 +305,19 @@ impl UsageMerger<'_> { // FIXME(eddyb) this might not enough because the // strict leaf could be *nested* inside `b`!!! - let is_strict = |kind| matches!(kind, &QPtrMemUsageKind::StrictlyTyped(_)); + let is_strict = |kind| matches!(kind, &DataHappKind::StrictlyTyped(_)); if is_strict(&a.kind) || is_strict(&b.kind) { - ty.map(QPtrMemUsageKind::StrictlyTyped) + ty.map(DataHappKind::StrictlyTyped) } else { - ty.map(QPtrMemUsageKind::DirectAccess) + ty.map(DataHappKind::Direct) } } - QPtrMemUsageKind::DynOffsetBase { element: mut a_element, stride: a_stride } => { + DataHappKind::Repeated { element: mut a_element, stride: a_stride } => { let b_offset_in_a_element = b_offset_in_a % a_stride; - // Array-like dynamic offsetting needs to always merge any usage that - // fits inside the stride, with its "element" usage, no matter how + // Array-like dynamic offsetting needs to always merge any HAPP that + // fits inside the stride, with its "element" HAPP, no matter how // complex it may be (notably, this is needed for nested arrays). if b.max_size .and_then(|b_max_size| b_max_size.checked_add(b_offset_in_a_element)) @@ -328,50 +326,44 @@ impl UsageMerger<'_> { // FIXME(eddyb) this in-place merging dance only needed due to `Rc`. ({ let a_element_mut = Rc::make_mut(&mut a_element); - let a_element = mem::replace(a_element_mut, QPtrMemUsage::UNUSED); - // FIXME(eddyb) remove this silliness by making `merge_mem_at` do symmetrical sorting. + let a_element = mem::replace(a_element_mut, DataHapp::DEAD); + // FIXME(eddyb) remove this silliness by making `merge_data_at` do symmetrical sorting. if b_offset_in_a_element == 0 { - self.merge_mem(a_element, b) + self.merge_data(a_element, b) } else { - self.merge_mem_at(a_element, b_offset_in_a_element, b) + self.merge_data_at(a_element, b_offset_in_a_element, b) } .map(|merged| *a_element_mut = merged) }) - .map(|()| QPtrMemUsageKind::DynOffsetBase { - element: a_element, - stride: a_stride, - }) + .map(|()| DataHappKind::Repeated { element: a_element, stride: a_stride }) } else { match b.kind { - QPtrMemUsageKind::DynOffsetBase { - element: b_element, - stride: b_stride, - } if b_offset_in_a_element == 0 && a_stride == b_stride => { + DataHappKind::Repeated { element: b_element, stride: b_stride } + if b_offset_in_a_element == 0 && a_stride == b_stride => + { // FIXME(eddyb) this in-place merging dance only needed due to `Rc`. ({ let a_element_mut = Rc::make_mut(&mut a_element); - let a_element = mem::replace(a_element_mut, QPtrMemUsage::UNUSED); + let a_element = mem::replace(a_element_mut, DataHapp::DEAD); let b_element = Rc::try_unwrap(b_element).unwrap_or_else(|e| (*e).clone()); - self.merge_mem(a_element, b_element) + self.merge_data(a_element, b_element) .map(|merged| *a_element_mut = merged) }) - .map(|()| { - QPtrMemUsageKind::DynOffsetBase { - element: a_element, - stride: a_stride, - } + .map(|()| DataHappKind::Repeated { + element: a_element, + stride: a_stride, }) } _ => { // FIXME(eddyb) implement somehow (by adjusting stride?). - // NOTE(eddyb) with `b` as an `DynOffsetBase`/`OffsetBase`, it could + // NOTE(eddyb) with `b` as an `Repeated`/`Disjoint`, it could // also be possible to superimpose its offset patterns onto `a`, - // though that's easier for `OffsetBase` than `DynOffsetBase`. + // though that's easier for `Disjoint` than `Repeated`. // HACK(eddyb) needed due to `a` being moved out of. - let a = QPtrMemUsage { + let a = DataHapp { max_size: a.max_size, - kind: QPtrMemUsageKind::DynOffsetBase { + kind: DataHappKind::Repeated { element: a_element, stride: a_stride, }, @@ -380,13 +372,13 @@ impl UsageMerger<'_> { merged: a.kind.clone(), error: Some(AnalysisError(Diag::bug([ format!( - "merge_mem: unimplemented \ + "merge_data: unimplemented \ non-intra-element merging into stride={a_stride} (" ) .into(), - QPtrUsage::Memory(a).into(), + MemAccesses::Data(a).into(), " vs ".into(), - QPtrUsage::Memory(b).into(), + MemAccesses::Data(b).into(), ")".into(), ]))), } @@ -395,7 +387,7 @@ impl UsageMerger<'_> { } } - QPtrMemUsageKind::OffsetBase(mut a_entries) => { + DataHappKind::Disjoint(mut a_entries) => { let overlapping_entries = a_entries .range(( Bound::Unbounded, @@ -404,8 +396,8 @@ impl UsageMerger<'_> { }), )) .rev() - .take_while(|(a_sub_offset, a_sub_usage)| { - a_sub_usage.max_size.is_none_or(|a_sub_max_size| { + .take_while(|(a_sub_offset, a_sub_happ)| { + a_sub_happ.max_size.is_none_or(|a_sub_max_size| { a_sub_offset.checked_add(a_sub_max_size).unwrap() > b_offset_in_a }) }); @@ -418,15 +410,15 @@ impl UsageMerger<'_> { let mut all_errors = None; let (mut b_offset_in_a, mut b) = (b_offset_in_a, b); for a_sub_offset in overlapping_offsets { - let a_sub_usage = a_entries_mut.remove(&a_sub_offset).unwrap(); + let a_sub_happ = a_entries_mut.remove(&a_sub_offset).unwrap(); // HACK(eddyb) this replicates the condition in which - // `merge_mem_at` would fail its similar assert, some of + // `merge_data_at` would fail its similar assert, some of // the cases denied here might be legal, but they're rare // enough that we can do this for now. let is_illegal = a_sub_offset != b_offset_in_a && { let (a_sub_total_max_size, b_total_max_size) = ( - a_sub_usage.max_size.map(|a| a.checked_add(a_sub_offset).unwrap()), + a_sub_happ.max_size.map(|a| a.checked_add(a_sub_offset).unwrap()), b.max_size.map(|b| b.checked_add(b_offset_in_a).unwrap()), ); let total_max_size_merged = match (a_sub_total_max_size, b_total_max_size) { @@ -442,24 +434,21 @@ impl UsageMerger<'_> { }; if is_illegal { // HACK(eddyb) needed due to `a` being moved out of. - let a = QPtrMemUsage { + let a = DataHapp { max_size: a.max_size, - kind: QPtrMemUsageKind::OffsetBase(a_entries.clone()), + kind: DataHappKind::Disjoint(a_entries.clone()), }; return MergeResult { - merged: QPtrMemUsage { - max_size, - kind: QPtrMemUsageKind::OffsetBase(a_entries), - }, + merged: DataHapp { max_size, kind: DataHappKind::Disjoint(a_entries) }, error: Some(AnalysisError(Diag::bug([ format!( - "merge_mem: unsupported straddling overlap \ + "merge_data: unsupported straddling overlap \ at offsets {a_sub_offset} vs {b_offset_in_a} (" ) .into(), - QPtrUsage::Memory(a).into(), + MemAccesses::Data(a).into(), " vs ".into(), - QPtrUsage::Memory(b).into(), + MemAccesses::Data(b).into(), ")".into(), ]))), }; @@ -470,16 +459,16 @@ impl UsageMerger<'_> { if a_sub_offset < b_offset_in_a { ( a_sub_offset, - self.merge_mem_at(a_sub_usage, b_offset_in_a - a_sub_offset, b), + self.merge_data_at(a_sub_happ, b_offset_in_a - a_sub_offset, b), ) } else { - // FIXME(eddyb) remove this silliness by making `merge_mem_at` do symmetrical sorting. + // FIXME(eddyb) remove this silliness by making `merge_data_at` do symmetrical sorting. if a_sub_offset - b_offset_in_a == 0 { - (b_offset_in_a, self.merge_mem(b, a_sub_usage)) + (b_offset_in_a, self.merge_data(b, a_sub_happ)) } else { ( b_offset_in_a, - self.merge_mem_at(b, a_sub_offset - b_offset_in_a, a_sub_usage), + self.merge_data_at(b, a_sub_offset - b_offset_in_a, a_sub_happ), ) } }; @@ -501,17 +490,17 @@ impl UsageMerger<'_> { } a_entries_mut.insert(b_offset_in_a, b); MergeResult { - merged: QPtrMemUsageKind::OffsetBase(a_entries), + merged: DataHappKind::Disjoint(a_entries), // FIXME(eddyb) should this mean `MergeResult` should // use `errors: Vec` instead of `Option`? error: all_errors.map(|AnalysisError(mut e)| { - e.message.insert(0, "merge_mem: conflicts:\n".into()); + e.message.insert(0, "merge_data: conflicts:\n".into()); AnalysisError(e) }), } } }; - kind.map(|kind| QPtrMemUsage { max_size, kind }) + kind.map(|kind| DataHapp { max_size, kind }) } /// Attempt to compute a `TypeLayout` for a given (SPIR-V) `Type`. @@ -521,85 +510,84 @@ impl UsageMerger<'_> { } impl MemTypeLayout { - /// Determine if this layout is compatible with `usage` at `usage_offset`. + /// Determine if this layout is compatible with `happ` at `happ_offset`. /// - /// That is, all typed leaves of `usage` must be found inside `self`, at - /// their respective offsets, and all [`QPtrMemUsageKind::DynOffsetBase`]s - /// must find a same-stride array inside `self` (to allow dynamic indexing). + /// That is, all typed leaves of `happ` must be found inside `self`, at + /// their respective offsets, and all [`DataHappKind::Repeated`]s must + /// find a same-stride array inside `self` (to allow dynamic indexing). // // FIXME(eddyb) consider using `Result` to make it unambiguous. - fn supports_usage_at_offset(&self, usage_offset: u32, usage: &QPtrMemUsage) -> bool { - if let QPtrMemUsageKind::Unused = usage.kind { + fn supports_happ_at_offset(&self, happ_offset: u32, happ: &DataHapp) -> bool { + if let DataHappKind::Dead = happ.kind { return true; } // "Fast accept" based on type alone (expected as recursion base case). - if let QPtrMemUsageKind::StrictlyTyped(usage_type) - | QPtrMemUsageKind::DirectAccess(usage_type) = usage.kind - && usage_offset == 0 - && self.original_type == usage_type + if let DataHappKind::StrictlyTyped(happ_type) | DataHappKind::Direct(happ_type) = happ.kind + && happ_offset == 0 + && self.original_type == happ_type { return true; } { - // FIXME(eddyb) should `QPtrMemUsage` track a `min_size` as well? + // FIXME(eddyb) should `DataHapp` track a `min_size` as well? // FIXME(eddyb) duplicated below. - let min_usage_offset_range = - usage_offset..usage_offset.saturating_add(usage.max_size.unwrap_or(0)); + let min_happ_offset_range = + happ_offset..happ_offset.saturating_add(happ.max_size.unwrap_or(0)); // "Fast reject" based on size alone (expected w/ multiple attempts). if self.mem_layout.dyn_unit_stride.is_none() - && (self.mem_layout.fixed_base.size < min_usage_offset_range.end - || usage.max_size.is_none()) + && (self.mem_layout.fixed_base.size < min_happ_offset_range.end + || happ.max_size.is_none()) { return false; } } - let any_component_supports = |usage_offset: u32, usage: &QPtrMemUsage| { - // FIXME(eddyb) should `QPtrMemUsage` track a `min_size` as well? + let any_component_supports = |happ_offset: u32, happ: &DataHapp| { + // FIXME(eddyb) should `DataHapp` track a `min_size` as well? // FIXME(eddyb) duplicated above. - let min_usage_offset_range = - usage_offset..usage_offset.saturating_add(usage.max_size.unwrap_or(0)); + let min_happ_offset_range = + happ_offset..happ_offset.saturating_add(happ.max_size.unwrap_or(0)); // FIXME(eddyb) `find_components_containing` is linear today but // could be made logarithmic (via binary search). - self.components.find_components_containing(min_usage_offset_range).any( - |idx| match &self.components { - Components::Scalar => unreachable!(), - Components::Elements { stride, elem, .. } => { - elem.supports_usage_at_offset(usage_offset % stride.get(), usage) - } - Components::Fields { offsets, layouts, .. } => { - layouts[idx].supports_usage_at_offset(usage_offset - offsets[idx], usage) - } - }, - ) + self.components.find_components_containing(min_happ_offset_range).any(|idx| match &self + .components + { + Components::Scalar => unreachable!(), + Components::Elements { stride, elem, .. } => { + elem.supports_happ_at_offset(happ_offset % stride.get(), happ) + } + Components::Fields { offsets, layouts, .. } => { + layouts[idx].supports_happ_at_offset(happ_offset - offsets[idx], happ) + } + }) }; - match &usage.kind { - _ if any_component_supports(usage_offset, usage) => true, + match &happ.kind { + _ if any_component_supports(happ_offset, happ) => true, - QPtrMemUsageKind::Unused => unreachable!(), + DataHappKind::Dead => unreachable!(), - QPtrMemUsageKind::StrictlyTyped(_) | QPtrMemUsageKind::DirectAccess(_) => false, + DataHappKind::StrictlyTyped(_) | DataHappKind::Direct(_) => false, - QPtrMemUsageKind::OffsetBase(entries) => { - entries.iter().all(|(&sub_offset, sub_usage)| { + DataHappKind::Disjoint(entries) => { + entries.iter().all(|(&sub_offset, sub_happ)| { // FIXME(eddyb) maybe this overflow should be propagated up, - // as a sign that `usage` is malformed? - usage_offset.checked_add(sub_offset).is_some_and(|combined_offset| { + // as a sign that `happ` is malformed? + happ_offset.checked_add(sub_offset).is_some_and(|combined_offset| { // NOTE(eddyb) the reason this is only applicable to // offset `0` is that *in all other cases*, every - // individual `OffsetBase` requires its own type, to + // individual `Disjoint` requires its own type, to // allow performing offsets *in steps* (even if the // offsets could easily be constant-folded, they'd // *have to* be constant-folded *before* analysis, // to ensure there is no need for the intermediaries). if combined_offset == 0 { - self.supports_usage_at_offset(0, sub_usage) + self.supports_happ_at_offset(0, sub_happ) } else { - any_component_supports(combined_offset, sub_usage) + any_component_supports(combined_offset, sub_happ) } }) }) @@ -607,16 +595,16 @@ impl MemTypeLayout { // Finding an array entirely nested in a component was handled above, // so here `layout` can only be a matching array (same stride and length). - QPtrMemUsageKind::DynOffsetBase { element: usage_elem, stride: usage_stride } => { - let usage_fixed_len = usage + DataHappKind::Repeated { element: happ_elem, stride: happ_stride } => { + let happ_fixed_len = happ .max_size .map(|size| { - if !size.is_multiple_of(usage_stride.get()) { + if !size.is_multiple_of(happ_stride.get()) { // FIXME(eddyb) maybe this should be propagated up, - // as a sign that `usage` is malformed? + // as a sign that `happ` is malformed? return Err(()); } - NonZeroU32::new(size / usage_stride.get()).ok_or(()) + NonZeroU32::new(size / happ_stride.get()).ok_or(()) }) .transpose(); @@ -631,17 +619,17 @@ impl MemTypeLayout { elem: layout_elem, fixed_len: layout_fixed_len, } => { - // HACK(eddyb) extend the max length implied by `usage`, + // HACK(eddyb) extend the max length implied by `happ`, // such that the array can start at offset `0`. - let ext_usage_offset = usage_offset % usage_stride.get(); - let ext_usage_fixed_len = usage_fixed_len.and_then(|usage_fixed_len| { - usage_fixed_len - .map(|usage_fixed_len| { + let ext_happ_offset = happ_offset % happ_stride.get(); + let ext_happ_fixed_len = happ_fixed_len.and_then(|happ_fixed_len| { + happ_fixed_len + .map(|happ_fixed_len| { NonZeroU32::new( // FIXME(eddyb) maybe this overflow should be propagated up, - // as a sign that `usage` is malformed? - (usage_offset / usage_stride.get()) - .checked_add(usage_fixed_len.get()) + // as a sign that `happ` is malformed? + (happ_offset / happ_stride.get()) + .checked_add(happ_fixed_len.get()) .ok_or(())?, ) .ok_or(()) @@ -651,13 +639,13 @@ impl MemTypeLayout { // FIXME(eddyb) this could maybe be allowed if there is still // some kind of divisibility relation between the strides. - if ext_usage_offset != 0 { + if ext_happ_offset != 0 { return false; } - layout_stride == usage_stride - && Ok(*layout_fixed_len) == ext_usage_fixed_len - && layout_elem.supports_usage_at_offset(0, usage_elem) + layout_stride == happ_stride + && Ok(*layout_fixed_len) == ext_happ_fixed_len + && layout_elem.supports_happ_at_offset(0, happ_elem) } } } @@ -665,59 +653,59 @@ impl MemTypeLayout { } } -struct FuncInferUsageResults { - param_usages: SmallVec<[Option>; 2]>, - usage_or_err_attrs_to_attach: Vec<(Value, Result)>, +struct FuncGatherAccessesResults { + param_accesses: SmallVec<[Option>; 2]>, + accesses_or_err_attrs_to_attach: Vec<(Value, Result)>, } #[derive(Clone)] -enum FuncInferUsageState { +enum FuncGatherAccessesState { InProgress, - Complete(Rc), + Complete(Rc), } -pub struct InferUsage<'a> { +pub struct GatherAccesses<'a> { cx: Rc, layout_cache: LayoutCache<'a>, - global_var_usages: FxIndexMap>>, - func_states: FxIndexMap, + global_var_accesses: FxIndexMap>>, + func_states: FxIndexMap, } -impl<'a> InferUsage<'a> { +impl<'a> GatherAccesses<'a> { pub fn new(cx: Rc, layout_config: &'a LayoutConfig) -> Self { Self { cx: cx.clone(), layout_cache: LayoutCache::new(cx, layout_config), - global_var_usages: Default::default(), + global_var_accesses: Default::default(), func_states: Default::default(), } } - pub fn infer_usage_in_module(mut self, module: &mut Module) { + pub fn gather_accesses_in_module(mut self, module: &mut Module) { for (export_key, &exportee) in &module.exports { if let Exportee::Func(func) = exportee { - self.infer_usage_in_func(module, func); + self.gather_accesses_in_func(module, func); } - // Ensure even unused interface variables get their `qptr.usage`. + // Ensure even unused interface variables get their `mem.accesses`. match export_key { ExportKey::LinkName(_) => {} ExportKey::SpvEntryPoint { imms: _, interface_global_vars } => { for &gv in interface_global_vars { - self.global_var_usages.entry(gv).or_insert_with(|| { + self.global_var_accesses.entry(gv).or_insert_with(|| { Some(Ok(match module.global_vars[gv].shape { Some(shapes::GlobalVarShape::Handles { handle, .. }) => { - QPtrUsage::Handles(match handle { + MemAccesses::Handles(match handle { shapes::Handle::Opaque(ty) => shapes::Handle::Opaque(ty), shapes::Handle::Buffer(..) => shapes::Handle::Buffer( AddrSpace::Handles, - QPtrMemUsage::UNUSED, + DataHapp::DEAD, ), }) } - _ => QPtrUsage::Memory(QPtrMemUsage::UNUSED), + _ => MemAccesses::Data(DataHapp::DEAD), })) }); } @@ -726,18 +714,18 @@ impl<'a> InferUsage<'a> { } // Analysis over, write all attributes back to the module. - for (gv, usage) in self.global_var_usages { - if let Some(usage) = usage { + for (gv, accesses) in self.global_var_accesses { + if let Some(accesses) = accesses { let global_var_def = &mut module.global_vars[gv]; - match usage { - Ok(usage) => { + match accesses { + Ok(accesses) => { // FIXME(eddyb) deduplicate attribute manipulation. global_var_def.attrs = self.cx.intern(AttrSetDef { attrs: self.cx[global_var_def.attrs] .attrs .iter() .cloned() - .chain([Attr::QPtr(QPtrAttr::Usage(OrdAssertEq(usage)))]) + .chain([Attr::Mem(MemAttr::Accesses(OrdAssertEq(accesses)))]) .collect(), }); } @@ -749,24 +737,26 @@ impl<'a> InferUsage<'a> { } for (func, state) in self.func_states { match state { - FuncInferUsageState::InProgress => unreachable!(), - FuncInferUsageState::Complete(func_results) => { - let FuncInferUsageResults { param_usages, usage_or_err_attrs_to_attach } = - Rc::try_unwrap(func_results).ok().unwrap(); + FuncGatherAccessesState::InProgress => unreachable!(), + FuncGatherAccessesState::Complete(func_results) => { + let FuncGatherAccessesResults { + param_accesses, + accesses_or_err_attrs_to_attach, + } = Rc::try_unwrap(func_results).ok().unwrap(); let func_decl = &mut module.funcs[func]; - for (param_decl, usage) in func_decl.params.iter_mut().zip(param_usages) { - if let Some(usage) = usage { - match usage { - Ok(usage) => { + for (param_decl, accesses) in func_decl.params.iter_mut().zip(param_accesses) { + if let Some(accesses) = accesses { + match accesses { + Ok(accesses) => { // FIXME(eddyb) deduplicate attribute manipulation. param_decl.attrs = self.cx.intern(AttrSetDef { attrs: self.cx[param_decl.attrs] .attrs .iter() .cloned() - .chain([Attr::QPtr(QPtrAttr::Usage(OrdAssertEq( - usage, + .chain([Attr::Mem(MemAttr::Accesses(OrdAssertEq( + accesses, )))]) .collect(), }); @@ -783,7 +773,7 @@ impl<'a> InferUsage<'a> { DeclDef::Imported(_) => continue, }; - for (v, usage) in usage_or_err_attrs_to_attach { + for (v, accesses) in accesses_or_err_attrs_to_attach { let attrs = match v { Value::Const(_) => unreachable!(), Value::RegionInput { region, input_idx } => { @@ -798,15 +788,17 @@ impl<'a> InferUsage<'a> { &mut func_def_body.at_mut(data_inst).def().attrs } }; - match usage { - Ok(usage) => { + match accesses { + Ok(accesses) => { // FIXME(eddyb) deduplicate attribute manipulation. *attrs = self.cx.intern(AttrSetDef { attrs: self.cx[*attrs] .attrs .iter() .cloned() - .chain([Attr::QPtr(QPtrAttr::Usage(OrdAssertEq(usage)))]) + .chain([Attr::Mem(MemAttr::Accesses(OrdAssertEq( + accesses, + )))]) .collect(), }); } @@ -820,62 +812,66 @@ impl<'a> InferUsage<'a> { } } - // HACK(eddyb) `FuncInferUsageState` also serves to indicate recursion errors. - fn infer_usage_in_func(&mut self, module: &Module, func: Func) -> FuncInferUsageState { + // HACK(eddyb) `FuncGatherAccessesState` also serves to indicate recursion errors. + fn gather_accesses_in_func(&mut self, module: &Module, func: Func) -> FuncGatherAccessesState { if let Some(cached) = self.func_states.get(&func).cloned() { return cached; } - self.func_states.insert(func, FuncInferUsageState::InProgress); + self.func_states.insert(func, FuncGatherAccessesState::InProgress); - let completed_state = - FuncInferUsageState::Complete(Rc::new(self.infer_usage_in_func_uncached(module, func))); + let completed_state = FuncGatherAccessesState::Complete(Rc::new( + self.gather_accesses_in_func_uncached(module, func), + )); self.func_states.insert(func, completed_state.clone()); completed_state } - fn infer_usage_in_func_uncached( + fn gather_accesses_in_func_uncached( &mut self, module: &Module, func: Func, - ) -> FuncInferUsageResults { + ) -> FuncGatherAccessesResults { let cx = self.cx.clone(); let is_qptr = |ty: Type| matches!(cx[ty].kind, TypeKind::QPtr); let func_decl = &module.funcs[func]; - let mut param_usages: SmallVec<[_; 2]> = + let mut param_accesses: SmallVec<[_; 2]> = (0..func_decl.params.len()).map(|_| None).collect(); - let mut usage_or_err_attrs_to_attach = vec![]; + let mut accesses_or_err_attrs_to_attach = vec![]; let func_def_body = match &module.funcs[func].def { DeclDef::Present(func_def_body) => func_def_body, DeclDef::Imported(_) => { - for (param, param_usage) in func_decl.params.iter().zip(&mut param_usages) { + for (param, param_accesses) in func_decl.params.iter().zip(&mut param_accesses) { if is_qptr(param.ty) { - *param_usage = Some(Err(AnalysisError(Diag::bug([ + *param_accesses = Some(Err(AnalysisError(Diag::bug([ "pointer param of imported func".into(), ])))); } } - return FuncInferUsageResults { param_usages, usage_or_err_attrs_to_attach }; + return FuncGatherAccessesResults { + param_accesses, + accesses_or_err_attrs_to_attach, + }; } }; let mut all_data_insts = CollectAllDataInsts::default(); func_def_body.inner_visit_with(&mut all_data_insts); - let mut data_inst_output_usages = FxHashMap::default(); + let mut data_inst_output_accesses = FxHashMap::default(); for insts in all_data_insts.0.into_iter().rev() { for func_at_inst in func_def_body.at(insts).into_iter().rev() { let data_inst = func_at_inst.position; let data_inst_def = func_at_inst.def(); - let output_usage = data_inst_output_usages.remove(&data_inst).flatten(); + let output_accesses = data_inst_output_accesses.remove(&data_inst).flatten(); - let mut generate_usage = |this: &mut Self, ptr: Value, new_usage| { + let mut generate_accesses = |this: &mut Self, ptr: Value, new_accesses| { let slot = match ptr { Value::Const(ct) => match cx[ct].kind { ConstKind::PtrToGlobalVar(gv) => { - this.global_var_usages.entry(gv).or_default() + this.global_var_accesses.entry(gv).or_default() } // FIXME(eddyb) may be relevant? _ => unreachable!(), @@ -883,43 +879,43 @@ impl<'a> InferUsage<'a> { Value::RegionInput { region, input_idx } if region == func_def_body.body => { - &mut param_usages[input_idx as usize] + &mut param_accesses[input_idx as usize] } // FIXME(eddyb) implement Value::RegionInput { .. } | Value::NodeOutput { .. } => { - usage_or_err_attrs_to_attach.push(( + accesses_or_err_attrs_to_attach.push(( ptr, Err(AnalysisError(Diag::bug(["unsupported φ".into()]))), )); return; } Value::DataInstOutput(ptr_inst) => { - data_inst_output_usages.entry(ptr_inst).or_default() + data_inst_output_accesses.entry(ptr_inst).or_default() } }; *slot = Some(match slot.take() { Some(old) => old.and_then(|old| { - UsageMerger { layout_cache: &this.layout_cache } - .merge(old, new_usage?) + AccessMerger { layout_cache: &this.layout_cache } + .merge(old, new_accesses?) .into_result() }), - None => new_usage, + None => new_accesses, }); }; match &data_inst_def.kind { &DataInstKind::FuncCall(callee) => { - match self.infer_usage_in_func(module, callee) { - FuncInferUsageState::Complete(callee_results) => { - for (&arg, param_usage) in - data_inst_def.inputs.iter().zip(&callee_results.param_usages) + match self.gather_accesses_in_func(module, callee) { + FuncGatherAccessesState::Complete(callee_results) => { + for (&arg, param_accesses) in + data_inst_def.inputs.iter().zip(&callee_results.param_accesses) { - if let Some(param_usage) = param_usage { - generate_usage(self, arg, param_usage.clone()); + if let Some(param_accesses) = param_accesses { + generate_accesses(self, arg, param_accesses.clone()); } } } - FuncInferUsageState::InProgress => { - usage_or_err_attrs_to_attach.push(( + FuncGatherAccessesState::InProgress => { + accesses_or_err_attrs_to_attach.push(( Value::DataInstOutput(data_inst), Err(AnalysisError(Diag::bug([ "unsupported recursive call".into() @@ -928,55 +924,57 @@ impl<'a> InferUsage<'a> { } }; if data_inst_def.output_type.is_some_and(is_qptr) - && let Some(usage) = output_usage + && let Some(accesses) = output_accesses { - usage_or_err_attrs_to_attach - .push((Value::DataInstOutput(data_inst), usage)); + accesses_or_err_attrs_to_attach + .push((Value::DataInstOutput(data_inst), accesses)); } } - DataInstKind::QPtr(QPtrOp::FuncLocalVar(_)) => { - if let Some(usage) = output_usage { - usage_or_err_attrs_to_attach - .push((Value::DataInstOutput(data_inst), usage)); + DataInstKind::Mem(MemOp::FuncLocalVar(_)) => { + if let Some(accesses) = output_accesses { + accesses_or_err_attrs_to_attach + .push((Value::DataInstOutput(data_inst), accesses)); } } DataInstKind::QPtr(QPtrOp::HandleArrayIndex) => { - generate_usage( + generate_accesses( self, data_inst_def.inputs[0], - output_usage + output_accesses .unwrap_or_else(|| { Err(AnalysisError(Diag::bug([ "HandleArrayIndex: unknown element".into(), ]))) }) - .and_then(|usage| match usage { - QPtrUsage::Handles(handle) => Ok(QPtrUsage::Handles(handle)), - QPtrUsage::Memory(_) => Err(AnalysisError(Diag::bug([ - "HandleArrayIndex: cannot be used as Memory".into(), + .and_then(|accesses| match accesses { + MemAccesses::Handles(handle) => { + Ok(MemAccesses::Handles(handle)) + } + MemAccesses::Data(_) => Err(AnalysisError(Diag::bug([ + "HandleArrayIndex: cannot be accessed as data".into(), ]))), }), ); } DataInstKind::QPtr(QPtrOp::BufferData) => { - generate_usage( + generate_accesses( self, data_inst_def.inputs[0], - output_usage - .unwrap_or(Ok(QPtrUsage::Memory(QPtrMemUsage::UNUSED))) - .and_then(|usage| { - let usage = match usage { - QPtrUsage::Handles(_) => { + output_accesses + .unwrap_or(Ok(MemAccesses::Data(DataHapp::DEAD))) + .and_then(|accesses| { + let happ = match accesses { + MemAccesses::Handles(_) => { return Err(AnalysisError(Diag::bug([ - "BufferData: cannot be used as Handles".into(), + "BufferData: cannot be accessed as handles".into(), ]))); } - QPtrUsage::Memory(usage) => usage, + MemAccesses::Data(happ) => happ, }; - Ok(QPtrUsage::Handles(shapes::Handle::Buffer( + Ok(MemAccesses::Handles(shapes::Handle::Buffer( AddrSpace::Handles, - usage, + happ, ))) }), ); @@ -985,47 +983,47 @@ impl<'a> InferUsage<'a> { fixed_base_size, dyn_unit_stride, }) => { - let array_usage = QPtrMemUsage { + let array_happ = DataHapp { max_size: None, - kind: QPtrMemUsageKind::DynOffsetBase { - element: Rc::new(QPtrMemUsage::UNUSED), + kind: DataHappKind::Repeated { + element: Rc::new(DataHapp::DEAD), stride: dyn_unit_stride, }, }; - let buf_data_usage = if fixed_base_size == 0 { - array_usage + let buf_data_happ = if fixed_base_size == 0 { + array_happ } else { - QPtrMemUsage { + DataHapp { max_size: None, - kind: QPtrMemUsageKind::OffsetBase(Rc::new( - [(fixed_base_size, array_usage)].into(), + kind: DataHappKind::Disjoint(Rc::new( + [(fixed_base_size, array_happ)].into(), )), } }; - generate_usage( + generate_accesses( self, data_inst_def.inputs[0], - Ok(QPtrUsage::Handles(shapes::Handle::Buffer( + Ok(MemAccesses::Handles(shapes::Handle::Buffer( AddrSpace::Handles, - buf_data_usage, + buf_data_happ, ))), ); } &DataInstKind::QPtr(QPtrOp::Offset(offset)) => { - generate_usage( + generate_accesses( self, data_inst_def.inputs[0], - output_usage - .unwrap_or(Ok(QPtrUsage::Memory(QPtrMemUsage::UNUSED))) - .and_then(|usage| { - let usage = match usage { - QPtrUsage::Handles(_) => { + output_accesses + .unwrap_or(Ok(MemAccesses::Data(DataHapp::DEAD))) + .and_then(|accesses| { + let happ = match accesses { + MemAccesses::Handles(_) => { return Err(AnalysisError(Diag::bug([format!( - "Offset({offset}): cannot offset Handles" + "Offset({offset}): cannot offset in handle memory" ) .into()]))); } - QPtrUsage::Memory(usage) => usage, + MemAccesses::Data(happ) => happ, }; let offset = u32::try_from(offset).ok().ok_or_else(|| { AnalysisError(Diag::bug([format!( @@ -1038,11 +1036,11 @@ impl<'a> InferUsage<'a> { // (e.g. constant-folded) out of existence, // but while they exist, they should be noops. if offset == 0 { - return Ok(QPtrUsage::Memory(usage)); + return Ok(MemAccesses::Data(happ)); } - Ok(QPtrUsage::Memory(QPtrMemUsage { - max_size: usage + Ok(MemAccesses::Data(DataHapp { + max_size: happ .max_size .map(|max_size| { offset.checked_add(max_size).ok_or_else(|| { @@ -1057,36 +1055,36 @@ impl<'a> InferUsage<'a> { // FIXME(eddyb) allocating `Rc>` // to represent the one-element case, seems // quite wasteful when it's likely consumed. - kind: QPtrMemUsageKind::OffsetBase(Rc::new( - [(offset, usage)].into(), + kind: DataHappKind::Disjoint(Rc::new( + [(offset, happ)].into(), )), })) }), ); } DataInstKind::QPtr(QPtrOp::DynOffset { stride, index_bounds }) => { - generate_usage( + generate_accesses( self, data_inst_def.inputs[0], - output_usage - .unwrap_or(Ok(QPtrUsage::Memory(QPtrMemUsage::UNUSED))) - .and_then(|usage| { - let usage = match usage { - QPtrUsage::Handles(_) => { + output_accesses + .unwrap_or(Ok(MemAccesses::Data(DataHapp::DEAD))) + .and_then(|accesses| { + let happ = match accesses { + MemAccesses::Handles(_) => { return Err(AnalysisError(Diag::bug([ - "DynOffset: cannot offset Handles".into(), + "DynOffset: cannot offset in handle memory".into(), ]))); } - QPtrUsage::Memory(usage) => usage, + MemAccesses::Data(happ) => happ, }; - match usage.max_size { + match happ.max_size { None => { return Err(AnalysisError(Diag::bug([ "DynOffset: unsized element".into(), ]))); } // FIXME(eddyb) support this by "folding" - // the usage onto itself (i.e. applying + // the HAPP onto itself (i.e. applying // `%= stride` on all offsets inside). Some(max_size) if max_size > stride.get() => { return Err(AnalysisError(Diag::bug([ @@ -1095,7 +1093,7 @@ impl<'a> InferUsage<'a> { } Some(_) => {} } - Ok(QPtrUsage::Memory(QPtrMemUsage { + Ok(MemAccesses::Data(DataHapp { // FIXME(eddyb) does the `None` case allow // for negative offsets? max_size: index_bounds @@ -1120,23 +1118,25 @@ impl<'a> InferUsage<'a> { }) }) .transpose()?, - kind: QPtrMemUsageKind::DynOffsetBase { - element: Rc::new(usage), + kind: DataHappKind::Repeated { + element: Rc::new(happ), stride: *stride, }, })) }), ); } - DataInstKind::QPtr(op @ (QPtrOp::Load | QPtrOp::Store)) => { + DataInstKind::Mem(op @ (MemOp::Load | MemOp::Store)) => { + // HACK(eddyb) `_` will match multiple variants soon. + #[allow(clippy::match_wildcard_for_single_variants)] let (op_name, access_type) = match op { - QPtrOp::Load => ("Load", data_inst_def.output_type.unwrap()), - QPtrOp::Store => { + MemOp::Load => ("Load", data_inst_def.output_type.unwrap()), + MemOp::Store => { ("Store", func_at_inst.at(data_inst_def.inputs[1]).type_of(&cx)) } _ => unreachable!(), }; - generate_usage( + generate_accesses( self, data_inst_def.inputs[0], self.layout_cache @@ -1144,7 +1144,7 @@ impl<'a> InferUsage<'a> { .map_err(|LayoutError(e)| AnalysisError(e)) .and_then(|layout| match layout { TypeLayout::Handle(shapes::Handle::Opaque(ty)) => { - Ok(QPtrUsage::Handles(shapes::Handle::Opaque(ty))) + Ok(MemAccesses::Handles(shapes::Handle::Opaque(ty))) } TypeLayout::Handle(shapes::Handle::Buffer(..)) => { Err(AnalysisError(Diag::bug([format!( @@ -1167,9 +1167,9 @@ impl<'a> InferUsage<'a> { .into()]))) } TypeLayout::Concrete(concrete) => { - Ok(QPtrUsage::Memory(QPtrMemUsage { + Ok(MemAccesses::Data(DataHapp { max_size: Some(concrete.mem_layout.fixed_base.size), - kind: QPtrMemUsageKind::DirectAccess(access_type), + kind: DataHappKind::Direct(access_type), })) } }), @@ -1182,7 +1182,7 @@ impl<'a> InferUsage<'a> { match *attr { Attr::QPtr(QPtrAttr::ToSpvPtrInput { input_idx, pointee }) => { let ty = pointee.0; - generate_usage( + generate_accesses( self, data_inst_def.inputs[input_idx as usize], self.layout_cache @@ -1210,11 +1210,11 @@ impl<'a> InferUsage<'a> { )); } }; - Ok(QPtrUsage::Handles(handle)) + Ok(MemAccesses::Handles(handle)) } // NOTE(eddyb) because we can't represent // the original type, in the same way we - // use `QPtrMemUsageKind::StrictlyTyped` + // use `DataHappKind::StrictlyTyped` // for non-handles, we can't guarantee // a generated type that matches the // desired `pointee` type. @@ -1227,7 +1227,7 @@ impl<'a> InferUsage<'a> { ]))) } TypeLayout::Concrete(concrete) => { - Ok(QPtrUsage::Memory(QPtrMemUsage { + Ok(MemAccesses::Data(DataHapp { max_size: if concrete .mem_layout .dyn_unit_stride @@ -1242,9 +1242,7 @@ impl<'a> InferUsage<'a> { .size, ) }, - kind: QPtrMemUsageKind::StrictlyTyped( - ty, - ), + kind: DataHappKind::StrictlyTyped(ty), })) } } @@ -1263,9 +1261,9 @@ impl<'a> InferUsage<'a> { if has_from_spv_ptr_output_attr { // FIXME(eddyb) merge with `FromSpvPtrOutput`'s `pointee`. - if let Some(usage) = output_usage { - usage_or_err_attrs_to_attach - .push((Value::DataInstOutput(data_inst), usage)); + if let Some(accesses) = output_accesses { + accesses_or_err_attrs_to_attach + .push((Value::DataInstOutput(data_inst), accesses)); } } } @@ -1273,7 +1271,7 @@ impl<'a> InferUsage<'a> { } } - FuncInferUsageResults { param_usages, usage_or_err_attrs_to_attach } + FuncGatherAccessesResults { param_accesses, accesses_or_err_attrs_to_attach } } } diff --git a/src/qptr/layout.rs b/src/mem/layout.rs similarity index 94% rename from src/qptr/layout.rs rename to src/mem/layout.rs index cbc407b1..e47260b3 100644 --- a/src/qptr/layout.rs +++ b/src/mem/layout.rs @@ -1,6 +1,6 @@ // FIXME(eddyb) layouts are a bit tricky: this recomputes them from several passes. -use crate::qptr::shapes; +use crate::mem::shapes; use crate::{ AddrSpace, Attr, Const, ConstKind, Context, Diag, FxIndexMap, Type, TypeKind, TypeOrConst, spv, }; @@ -61,10 +61,10 @@ impl LayoutConfig { Self { min_aggregate_legacy_align: 16, ..Self::VULKAN_STANDARD_LAYOUT }; } -pub(super) struct LayoutError(pub(super) Diag); +pub(crate) struct LayoutError(pub(crate) Diag); #[derive(Clone)] -pub(super) enum TypeLayout { +pub(crate) enum TypeLayout { Handle(HandleLayout), HandleArray(HandleLayout, Option), @@ -73,16 +73,16 @@ pub(super) enum TypeLayout { } // NOTE(eddyb) `Handle` is parameterized over the `Buffer` layout. -pub(super) type HandleLayout = shapes::Handle>; +pub(crate) type HandleLayout = shapes::Handle>; -pub(super) struct MemTypeLayout { - pub(super) original_type: Type, - pub(super) mem_layout: shapes::MaybeDynMemLayout, - pub(super) components: Components, +pub(crate) struct MemTypeLayout { + pub(crate) original_type: Type, + pub(crate) mem_layout: shapes::MaybeDynMemLayout, + pub(crate) components: Components, } // FIXME(eddyb) use proper newtypes for byte sizes. -pub(super) enum Components { +pub(crate) enum Components { Scalar, /// Vector and array elements (all of them having the same `elem` layout). @@ -106,7 +106,7 @@ impl Components { /// this can return multiple components, with at most one ever being non-ZST. // // FIXME(eddyb) be more aggressive in pruning ZSTs so this can be simpler. - pub(super) fn find_components_containing( + pub(crate) fn find_components_containing( &self, // FIXME(eddyb) consider renaming such offset ranges to "extent". offset_range: Range, @@ -168,7 +168,7 @@ impl Components { } /// Context for computing `TypeLayout`s from `Type`s (with caching). -pub(super) struct LayoutCache<'a> { +pub(crate) struct LayoutCache<'a> { cx: Rc, wk: &'static spv::spec::WellKnown, @@ -178,7 +178,7 @@ pub(super) struct LayoutCache<'a> { } impl<'a> LayoutCache<'a> { - pub(super) fn new(cx: Rc, config: &'a LayoutConfig) -> Self { + pub(crate) fn new(cx: Rc, config: &'a LayoutConfig) -> Self { Self { cx, wk: &spv::spec::Spec::get().well_known, config, cache: Default::default() } } @@ -197,7 +197,7 @@ impl<'a> LayoutCache<'a> { } /// Attempt to compute a `TypeLayout` for a given (SPIR-V) `Type`. - pub(super) fn layout_of(&self, ty: Type) -> Result { + pub(crate) fn layout_of(&self, ty: Type) -> Result { if let Some(cached) = self.cache.borrow().get(&ty).cloned() { return Ok(cached); } @@ -216,6 +216,9 @@ impl<'a> LayoutCache<'a> { TypeKind::SpvInst { spv_inst, type_and_const_inputs } => { (spv_inst, type_and_const_inputs) } + TypeKind::SpvTypeOperand => { + return Err(LayoutError(Diag::bug(["`layout_of(type_of(type))`".into()]))); + } TypeKind::SpvStringLiteralForExtInst => { return Err(LayoutError(Diag::bug([ "`layout_of(type_of(OpString<\"...\">))`".into() @@ -348,7 +351,7 @@ impl<'a> LayoutCache<'a> { // FIXME(eddyb) !!! what if... types had a min/max size and then... // that would allow surrounding offsets to limit their size... but... ugh... // ugh this doesn't make any sense. maybe if the front-end specifies - // offsets with "abstract types", it must configure `qptr::layout`? + // offsets with "abstract types", it must configure `mem::layout`? let layout = if spv_inst.opcode == wk.OpTypeBool { // FIXME(eddyb) make this properly abstract instead of only configurable. scalar_with_size_and_align(self.config.abstract_bool_size_align) @@ -399,11 +402,14 @@ impl<'a> LayoutCache<'a> { let mut stride_decoration = None; for attr in &cx[ty_def.attrs].attrs { match attr { - Attr::SpvAnnotation(attr_spv_inst) + Attr::SpvAnnotation { spv_inst: attr_spv_inst, per_instance_const_inputs } if attr_spv_inst.opcode == wk.OpDecorate && attr_spv_inst.imms[0] == spv::Imm::Short(wk.Decoration, wk.ArrayStride) => { + // FIXME(eddyb) support `ArrayStrideId`. + assert!(per_instance_const_inputs.is_none()); + stride_decoration = Some(match attr_spv_inst.imms[1] { spv::Imm::Short(_, x) => x, _ => unreachable!(), @@ -445,20 +451,25 @@ impl<'a> LayoutCache<'a> { let mut field_offsets: SmallVec<[_; 4]> = SmallVec::with_capacity(field_layouts.len()); for attr in &cx[ty_def.attrs].attrs { match attr { - Attr::SpvAnnotation(attr_spv_inst) + Attr::SpvAnnotation { spv_inst: attr_spv_inst, per_instance_const_inputs } if attr_spv_inst.opcode == wk.OpMemberDecorate && attr_spv_inst.imms[1] == spv::Imm::Short(wk.Decoration, wk.RowMajor) => { + assert!(per_instance_const_inputs.is_none()); + return Err(LayoutError(Diag::bug([ "`RowMajor` matrix types unsupported".into(), ]))); } - Attr::SpvAnnotation(attr_spv_inst) + Attr::SpvAnnotation { spv_inst: attr_spv_inst, per_instance_const_inputs } if attr_spv_inst.opcode == wk.OpMemberDecorate && attr_spv_inst.imms[1] == spv::Imm::Short(wk.Decoration, wk.Offset) => { + // FIXME(eddyb) support `OffsetId`. + assert!(per_instance_const_inputs.is_none()); + let (field_idx, field_offset) = match attr_spv_inst.imms[..] { [spv::Imm::Short(_, idx), _, spv::Imm::Short(_, offset)] => { (idx, offset) @@ -597,11 +608,13 @@ impl<'a> LayoutCache<'a> { let mut is_interface_block = false; for attr in &cx[ty_def.attrs].attrs { match attr { - Attr::SpvAnnotation(attr_spv_inst) + Attr::SpvAnnotation { spv_inst: attr_spv_inst, per_instance_const_inputs } if attr_spv_inst.opcode == wk.OpDecorate && attr_spv_inst.imms[0] == spv::Imm::Short(wk.Decoration, wk.Block) => { + assert!(per_instance_const_inputs.is_none()); + is_interface_block = true; break; } diff --git a/src/mem/mod.rs b/src/mem/mod.rs new file mode 100644 index 00000000..f52208a5 --- /dev/null +++ b/src/mem/mod.rs @@ -0,0 +1,151 @@ +//! Memory operations, analyses and transformations. +// +// FIXME(eddyb) document at least these aspects: +// - "memory" = indirect storage of data and/or resources +// - (untyped) "data" = mix of plain bytes and pointers (as per RalfJ blog post) +// (does "non-data memory" actually make sense? could be considered typed?) +// +// FIXME(eddyb) dig into past notes (e.g. `qptr::legalize`, Rust-GPU release notes, +// https://github.com/EmbarkStudios/spirt/pull/24, etc.) for useful docs. +// +// FIXME(eddyb) consider taking this into a more (R)VSDG "state type" direction. + +use crate::{OrdAssertEq, Type}; +use std::collections::BTreeMap; +use std::num::NonZeroU32; +use std::rc::Rc; + +// NOTE(eddyb) all the modules are declared here, but they're documented "inside" +// (i.e. using inner doc comments). +pub mod analyze; +// FIXME(eddyb) make this public? +pub(crate) mod layout; +pub mod shapes; + +pub use layout::LayoutConfig; + +/// Memory-specific attributes ([`Attr::Mem`]). +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum MemAttr { + /// When applied to a `GlobalVar` or `FuncLocalVar`, this tracks all possible + /// access patterns its memory may be subjected to (see [`MemAccesses`]). + Accesses(OrdAssertEq), +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub enum MemAccesses { + /// Accesses to one or more handles (i.e. optionally indexed by + /// [`crate::qptr::QPtrOp::HandleArrayIndex`]), which can be: + /// - `Handle::Opaque(handle_type)`: all accesses involve [`MemOp::Load`] or + /// [`crate::qptr::QPtrAttr::ToSpvPtrInput`], with the common type `handle_type` + /// - `Handle::Buffer(data_happ)`: carries with it `data_happ`, + /// i.e. the access patterns for the memory that is reached through + /// [`crate::qptr::QPtrOp::BufferData`] + Handles(shapes::Handle), + + Data(DataHapp), +} + +/// Data HAPP ("Hierarchical Access Pattern Partitioning"): all access patterns +/// for some memory, structured by disjoint offset ranges ("partitions"). +/// +/// This is the core of "type recovery" (inferring typed memory from untyped), +/// with "struct/"array" equivalents (i.e. as `DataHappKind` variants), but +/// while it can be mapped to an explicitly laid out data type, it also tracks +/// distinctions only needed during merging (e.g. [`DataHappKind::StrictlyTyped`]). +/// +/// **Note**: the only reason for the recursive/"hierarchical" aspect is that +/// (array-like) dynamic indexing allows for compact representation of repeated +/// patterns, which can non-trivially nest for 3+ levels without losing the need +/// for efficient representation - in fact, one can construct a worst-case like: +/// ```ignore +/// [(A, [(B, [(C, [(D, [T; N], X); 2], Y); 2], Z); 2], W); 2] +/// ``` +/// (with only `N * 2**4` leaf `T`s because of the 4 `[(_, ..., _); 2]` levels, +/// and the potential for dozens of such levels while remaining a plausible size) +// +// FIXME(eddyb) reconsider the name (acronym was picked to avoid harder decisions). +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct DataHapp { + /// If present, this is a worst-case upper bound on the offsets at which + /// accesses may be perfomed. + // + // FIXME(eddyb) use proper newtypes for byte amounts. + // + // FIXME(eddyb) suboptimal naming choice, but other options are too verbose, + // including maybe using `RangeTo<_>` to explicitly indicate "exclusive". + // + // FIXME(eddyb) consider renaming such information to "extent", but that might + // be ambiguous with an offset range (as opposed to using the maximum of all + // *possible* `offset_range.end` values to describe a "maximum size"). + pub max_size: Option, + + pub kind: DataHappKind, +} + +impl DataHapp { + pub const DEAD: Self = Self { max_size: Some(0), kind: DataHappKind::Dead }; +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub enum DataHappKind { + /// Not actually accessed (only an intermediary state, during access analysis). + // + // FIXME(eddyb) use `Option` instead? or an empty `Disjoint`? + Dead, + + // FIXME(eddyb) replace the two leaves with e.g. `Leaf(Type, LeafAccessKind)`. + // + // + /// Accesses through typed pointers (e.g. via unknown SPIR-V instructions), + /// requiring a specific choice of pointee type which cannot be modified, + /// and has to be reused as-is, when lifting to typed memory. + /// + /// Other overlapping accesses can be merged into this one as long as they + /// can be fully expressed using the (transitive) components of this type. + StrictlyTyped(Type), + + /// Direct accesses (e.g. [`MemOp::Load`], [`MemOp::Store`]), which can be + /// decomposed as necessary (down to individual scalar leaves), to allow + /// maximal merging opportunities. + // + // FIXME(eddyb) track whether accesses are `Load`s and/or `Store`s, to allow + // inferring `NonWritable`/`NonReadable` annotations, as well. + Direct(Type), + + /// Partitioning into disjoint offset ranges (the map is keyed by the start + /// of the offset range, while the end is implied by its corresponding value), + /// requiring a "struct" type, when lifting to typed memory. + // + // FIXME(eddyb) make this non-nestable and the fundamental basis of "HAPP". + Disjoint(Rc>), + + /// `Disjoint` counterpart for dynamic offsetting, requiring an "array" type, + /// when lifting to typed memory, with one single element type being repeated + /// across the entire size, at all offsets that are a multiple of `stride`. + Repeated { + // FIXME(eddyb) this feels inefficient. + element: Rc, + stride: NonZeroU32, + }, +} + +/// Memory-specific operations ([`DataInstKind::Mem`]). +#[derive(Clone, PartialEq, Eq, Hash)] +pub enum MemOp { + // HACK(eddyb) `OpVariable` replacement, which itself should not be kept as + // a `SpvInst` - once fn-local variables are lowered, this should go there. + FuncLocalVar(shapes::MemLayout), + + /// Read a single value from a pointer (`inputs[0]`). + // + // FIXME(eddyb) limit this to data - and scalars, maybe vectors at most. + Load, + + /// Write a single value (`inputs[1]`) to a pointer (`inputs[0]`). + // + // FIXME(eddyb) limit this to data - and scalars, maybe vectors at most. + Store, + // + // FIXME(eddyb) implement more ops (e.g. copies, atomics). +} diff --git a/src/qptr/shapes.rs b/src/mem/shapes.rs similarity index 93% rename from src/qptr/shapes.rs rename to src/mem/shapes.rs index ac53d43c..dc9f3e20 100644 --- a/src/qptr/shapes.rs +++ b/src/mem/shapes.rs @@ -1,6 +1,7 @@ //! Variable shapes (untyped memory layouts vs abstract resources). // // FIXME(eddyb) does this need its own module still? +// TODO(eddyb) strongly consider moving these to `mem/mod.rs`. use crate::{AddrSpace, Type}; use std::num::NonZeroU32; @@ -22,6 +23,7 @@ pub enum GlobalVarShape { }, // FIXME(eddyb) unify terminology around "concrete"/"memory"/"untyped (data)". + // TODO(eddyb) strongly consider renaming this to just `Data`. UntypedData(MemLayout), /// Non-memory pipeline interface, which must keep the exact original type, @@ -73,7 +75,7 @@ pub enum Handle { // instead of being treated like a buffer? // // FIXME(eddyb) should this be a `Type` of its own, that can be loaded from - // a handle `QPtr`, and then has data pointer / length ops *on that*? + // a handle pointer, and then has data pointer / length ops *on that*? Buffer(AddrSpace, BL), } @@ -83,11 +85,12 @@ pub enum Handle { /// and are both kept track of to detect ambiguity in implicit layouts, e.g. /// field offsets when the `Offset` decoration isn't being used. /// Note, however, that `legacy_align` can be raised to "extended" alignment, -/// or completeley ignored, using [`LayoutConfig`](crate::qptr::LayoutConfig). +/// or completeley ignored, using [`LayoutConfig`](crate::mem::LayoutConfig). /// /// Only `align` is *required*, that is `size % align == 0` must be always enforced. // // FIXME(eddyb) consider supporting specialization-constant-length arrays. +// TODO(eddyb) strongly consider renaming this to `DataLayout`. #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub struct MemLayout { // FIXME(eddyb) use proper newtypes (and log2 for align!). diff --git a/src/passes/qptr.rs b/src/passes/qptr.rs index 0cf95ef6..59a6ac7f 100644 --- a/src/passes/qptr.rs +++ b/src/passes/qptr.rs @@ -4,7 +4,7 @@ use crate::qptr; use crate::visit::{InnerVisit, Visitor}; use crate::{AttrSet, Const, Context, Func, FxIndexSet, GlobalVar, Module, Type}; -pub fn lower_from_spv_ptrs(module: &mut Module, layout_config: &qptr::LayoutConfig) { +pub fn lower_from_spv_ptrs(module: &mut Module, layout_config: &crate::mem::LayoutConfig) { let cx = &module.cx(); let (seen_global_vars, seen_funcs) = { @@ -34,11 +34,13 @@ pub fn lower_from_spv_ptrs(module: &mut Module, layout_config: &qptr::LayoutConf } } -pub fn analyze_uses(module: &mut Module, layout_config: &qptr::LayoutConfig) { - qptr::analyze::InferUsage::new(module.cx(), layout_config).infer_usage_in_module(module); +// FIXME(eddyb) this doesn't really belong in `qptr`. +pub fn analyze_mem_accesses(module: &mut Module, layout_config: &crate::mem::LayoutConfig) { + crate::mem::analyze::GatherAccesses::new(module.cx(), layout_config) + .gather_accesses_in_module(module); } -pub fn lift_to_spv_ptrs(module: &mut Module, layout_config: &qptr::LayoutConfig) { +pub fn lift_to_spv_ptrs(module: &mut Module, layout_config: &crate::mem::LayoutConfig) { let cx = &module.cx(); let (seen_global_vars, seen_funcs) = { diff --git a/src/print/mod.rs b/src/print/mod.rs index 8532ab9d..284548c8 100644 --- a/src/print/mod.rs +++ b/src/print/mod.rs @@ -20,8 +20,9 @@ use itertools::Itertools as _; use crate::func_at::FuncAt; +use crate::mem::{DataHapp, DataHappKind, MemAccesses, MemAttr, MemOp}; use crate::print::multiversion::Versions; -use crate::qptr::{self, QPtrAttr, QPtrMemUsage, QPtrMemUsageKind, QPtrOp, QPtrUsage}; +use crate::qptr::{QPtrAttr, QPtrOp}; use crate::visit::{InnerVisit, Visit, Visitor}; use crate::{ AddrSpace, Attr, AttrSet, AttrSetDef, Const, ConstDef, ConstKind, Context, DataInst, @@ -483,7 +484,12 @@ impl<'a> Visitor<'a> for Plan<'a> { .attrs .iter() .filter_map(|attr| match attr { - Attr::SpvAnnotation(spv_inst) if spv_inst.opcode == wk.OpName => Some(spv_inst), + Attr::SpvAnnotation { spv_inst, per_instance_const_inputs } + if spv_inst.opcode == wk.OpName => + { + assert!(per_instance_const_inputs.is_none()); + Some(spv_inst) + } _ => None, }) .peekable(); @@ -764,8 +770,7 @@ impl DbgScopeDefMap { } merged }) - .map(|merged| merged.rev_scopes) - .unwrap_or_default(); + .map_or_default(|merged| merged.rev_scopes); DbgScopeDefMap { top, rev_scopes } } @@ -1133,9 +1138,9 @@ impl<'a> Printer<'a> { || type_and_const_inputs.is_empty() } - TypeKind::QPtr | TypeKind::SpvStringLiteralForExtInst => { - true - } + TypeKind::QPtr + | TypeKind::SpvTypeOperand + | TypeKind::SpvStringLiteralForExtInst => true, }; ty_def.attrs == AttrSet::default() @@ -1802,7 +1807,7 @@ impl Printer<'_> { fn sanitize_spv_operand_name<'b>(&self, name: &'b str) -> Option> { Some(name).and_then(|name| { // HACK(eddyb) some operand names are useless. - if name == "Type" + if matches!(name, "Opcode" | "Operand" | "Type") || name .strip_prefix("Operand ") .is_some_and(|s| s.chars().all(|c| c.is_ascii_digit())) @@ -1840,8 +1845,7 @@ impl Printer<'_> { spv::print::Token::Error(s) => self.error_style().apply(s).into(), spv::print::Token::OperandName(s) => self .sanitize_spv_operand_name(s) - .map(|name| self.pretty_named_argument_prefix(name)) - .unwrap_or_default(), + .map_or_default(|name| self.pretty_named_argument_prefix(name)), spv::print::Token::Punctuation(s) => s.into(), spv::print::Token::OperandKindNamespacePrefix(s) => { pretty::Fragment::new([ @@ -1876,7 +1880,7 @@ impl Printer<'_> { &self, imms: impl IntoIterator, ) -> pretty::Fragment { - self.pretty_spv_print_tokens_for_operand(spv::print::operand_from_imms(imms)) + self.pretty_spv_print_tokens_for_operand(spv::print::operand(imms, [])) } /// Pretty-print a single SPIR-V (short) immediate (e.g. an enumerand). @@ -2254,11 +2258,8 @@ impl Plan<'_> { }) .map(PlanItemOrRoot::PlanItem); let root = [PlanItemOrRoot::Root].into_iter(); - let all_items_and_or_root = Some(all_items) - .filter(|_| print_all_items) - .into_iter() - .flatten() - .chain(Some(root).filter(|_| print_root).into_iter().flatten()); + let all_items_and_or_root = (print_all_items.then_some(all_items).into_iter().flatten()) + .chain(print_root.then_some(root).into_iter().flatten()); let per_item_versions_with_repeat_count = all_items_and_or_root.map(|item_or_root| -> SmallVec<[_; 1]> { @@ -2275,10 +2276,8 @@ impl Plan<'_> { self.versions .iter() .map(move |version| match item_or_root { - PlanItemOrRoot::PlanItem(item) => version - .item_defs - .get(&item) - .map(|def| { + PlanItemOrRoot::PlanItem(item) => { + version.item_defs.get(&item).map_or_default(|def| { let prev_plan_item = printer.current_plan_item.replace(Some(item)); let printed_def = def.print(printer); printer.current_plan_item.set(prev_plan_item); @@ -2287,7 +2286,7 @@ impl Plan<'_> { Use::PlanItem(item).print_as_def(printer), ) }) - .unwrap_or_default(), + } PlanItemOrRoot::Root => version.root.print(printer), }) .dedup_with_count() @@ -2426,7 +2425,7 @@ impl Print for spv::Dialect { // HACK(eddyb) construct a custom `spv.Capability.{A,B,C}`. let capability_namespace_prefix = printer .pretty_spv_print_tokens_for_operand({ - let mut tokens = spv::print::operand_from_imms(cap_imms(0)); + let mut tokens = spv::print::operand(cap_imms(0), []); assert!(matches!( tokens.tokens.pop(), Some(spv::print::Token::EnumerandName(_)) @@ -2436,7 +2435,7 @@ impl Print for spv::Dialect { let mut cap_names = capabilities.iter().map(|&cap| { printer.pretty_spv_print_tokens_for_operand({ - let mut tokens = spv::print::operand_from_imms(cap_imms(cap)); + let mut tokens = spv::print::operand(cap_imms(cap), []); tokens.tokens.drain(..tokens.tokens.len() - 1); assert!(matches!( tokens.tokens[..], @@ -2710,7 +2709,9 @@ impl Print for AttrSet { attrs .iter() .filter(|attr| match attr { - Attr::SpvAnnotation(spv_inst) => Some(spv_inst) != spv_name_to_hide, + Attr::SpvAnnotation { spv_inst, per_instance_const_inputs: None } => { + Some(spv_inst) != spv_name_to_hide + } _ => true, }) .map(|attr| attr.print(printer)) @@ -2788,7 +2789,14 @@ impl DbgScope { impl Print for Attr { type Output = pretty::Fragment; fn print(&self, printer: &Printer<'_>) -> pretty::Fragment { - let non_comment_attr = match self { + let mk_non_comment_attr = |attr| { + pretty::Fragment::new([ + printer.attr_style().apply("#[").into(), + attr, + printer.attr_style().apply("]").into(), + ]) + }; + match self { &Attr::DbgSrcLoc(OrdAssertEq(dbg_src_loc)) => { let mut comment = SmallVec::<[_; 4]>::new(); @@ -2876,11 +2884,11 @@ impl Print for Attr { } } - return comment; + comment } Attr::Diagnostics(diags) => { - return pretty::Fragment::new( + pretty::Fragment::new( diags .0 .iter() @@ -2954,7 +2962,23 @@ impl Print for Attr { ]) }) .intersperse(pretty::Node::ForceLineSeparation.into()), - ); + ) + } + + Attr::Mem(attr) => { + let (name, params_inputs) = match attr { + MemAttr::Accesses(accesses) => { + ("accesses", pretty::join_comma_sep("(", [accesses.0.print(printer)], ")")) + } + }; + pretty::Fragment::new([ + printer + .demote_style_for_namespace_prefix(printer.attr_style()) + .apply("mem.") + .into(), + printer.attr_style().apply(name).into(), + params_inputs, + ]) } Attr::QPtr(attr) => { @@ -2985,46 +3009,78 @@ impl Print for Attr { ")", ), ), - - QPtrAttr::Usage(usage) => { - ("usage", pretty::join_comma_sep("(", [usage.0.print(printer)], ")")) - } }; - pretty::Fragment::new([ + mk_non_comment_attr(pretty::Fragment::new([ printer .demote_style_for_namespace_prefix(printer.attr_style()) .apply("qptr.") .into(), printer.attr_style().apply(name).into(), params_inputs, - ]) + ])) } - Attr::SpvAnnotation(spv::Inst { opcode, imms }) => { + Attr::SpvAnnotation { + spv_inst: spv::Inst { opcode, imms }, + per_instance_const_inputs, + } => { let wk = &spv::spec::Spec::get().well_known; - // HACK(eddyb) `#[spv.OpDecorate(...)]` is redundant (with its operand). - if [wk.OpDecorate, wk.OpDecorateString, wk.OpExecutionMode].contains(opcode) { - printer.pretty_spv_operand_from_imms(imms.iter().copied()) - } else if *opcode == wk.OpName { - // HACK(eddyb) unlike `OpDecorate`, we can't just omit `OpName`, - // but pretending it's a SPIR-T-specific `#[name = "..."]` - // attribute should be good enough for now. - pretty::Fragment::new([ - printer.attr_style().apply("name = ").into(), - printer.pretty_spv_operand_from_imms(imms.iter().copied()), - ]) - } else { - printer.pretty_spv_inst(printer.attr_style(), *opcode, imms, [None]) - } + let empty_const_inputs = SmallVec::new(); + let instances = + per_instance_const_inputs + .as_ref() + .map_or(std::slice::from_ref(&empty_const_inputs), |instances| { + &instances.0[..] + }); + + pretty::Fragment::new( + instances + .iter() + .map(|const_inputs| { + // HACK(eddyb) `#[spv.OpDecorate(...)]` is redundant (with its operand). + if [ + wk.OpDecorate, + wk.OpDecorateId, + wk.OpDecorateString, + wk.OpExecutionMode, + wk.OpExecutionModeId, + ] + .contains(opcode) + { + printer.pretty_spv_print_tokens_for_operand(spv::print::operand( + imms.iter().copied(), + const_inputs.iter().map(|ct| ct.print(printer).into()), + )) + } else if *opcode == wk.OpName { + assert_eq!(const_inputs.len(), 0); + + // HACK(eddyb) unlike `OpDecorate`, we can't just omit `OpName`, + // but pretending it's a SPIR-T-specific `#[name = "..."]` + // attribute should be good enough for now. + pretty::Fragment::new([ + printer.attr_style().apply("name = ").into(), + printer.pretty_spv_operand_from_imms(imms.iter().copied()), + ]) + } else { + printer.pretty_spv_inst( + printer.attr_style(), + *opcode, + imms, + [None].into_iter().chain( + const_inputs.iter().map(|ct| ct.print(printer)).map(Some), + ), + ) + } + }) + .map(mk_non_comment_attr) + .intersperse_with(|| pretty::Node::ForceLineSeparation.into()), + ) } - &Attr::SpvBitflagsOperand(imm) => printer.pretty_spv_operand_from_imms([imm]), - }; - pretty::Fragment::new([ - printer.attr_style().apply("#[").into(), - non_comment_attr, - printer.attr_style().apply("]").into(), - ]) + &Attr::SpvBitflagsOperand(imm) => { + mk_non_comment_attr(printer.pretty_spv_operand_from_imms([imm])) + } + } } } @@ -3036,54 +3092,51 @@ impl Print for Vec { DiagMsgPart::Attrs(attrs) => attrs.print(printer), DiagMsgPart::Type(ty) => ty.print(printer), DiagMsgPart::Const(ct) => ct.print(printer), - DiagMsgPart::QPtrUsage(usage) => usage.print(printer), + DiagMsgPart::MemAccesses(accesses) => accesses.print(printer), })) } } -impl Print for QPtrUsage { +impl Print for MemAccesses { type Output = pretty::Fragment; fn print(&self, printer: &Printer<'_>) -> pretty::Fragment { match self { - QPtrUsage::Handles(qptr::shapes::Handle::Opaque(ty)) => ty.print(printer), - QPtrUsage::Handles(qptr::shapes::Handle::Buffer(_, data_usage)) => { + MemAccesses::Handles(crate::mem::shapes::Handle::Opaque(ty)) => ty.print(printer), + MemAccesses::Handles(crate::mem::shapes::Handle::Buffer(_, data_happ)) => { pretty::Fragment::new([ printer.declarative_keyword_style().apply("buffer_data").into(), - pretty::join_comma_sep("(", [data_usage.print(printer)], ")"), + pretty::join_comma_sep("(", [data_happ.print(printer)], ")"), ]) } - QPtrUsage::Memory(usage) => usage.print(printer), + MemAccesses::Data(happ) => happ.print(printer), } } } -impl Print for QPtrMemUsage { +impl Print for DataHapp { type Output = pretty::Fragment; fn print(&self, printer: &Printer<'_>) -> pretty::Fragment { // FIXME(eddyb) should this be a helper on `Printer`? let num_lit = |x: u32| printer.numeric_literal_style().apply(format!("{x}")).into(); match &self.kind { - QPtrMemUsageKind::Unused => "_".into(), + DataHappKind::Dead => "_".into(), // FIXME(eddyb) should the distinction be noted? - &QPtrMemUsageKind::StrictlyTyped(ty) | &QPtrMemUsageKind::DirectAccess(ty) => { - ty.print(printer) - } - QPtrMemUsageKind::OffsetBase(entries) => pretty::join_comma_sep( + &DataHappKind::StrictlyTyped(ty) | &DataHappKind::Direct(ty) => ty.print(printer), + DataHappKind::Disjoint(entries) => pretty::join_comma_sep( "{", entries .iter() - .map(|(&offset, sub_usage)| { + .map(|(&offset, sub_happ)| { pretty::Fragment::new([ num_lit(offset), "..".into(), - sub_usage + sub_happ .max_size .and_then(|max_size| offset.checked_add(max_size)) - .map(num_lit) - .unwrap_or_default(), + .map_or_default(num_lit), " => ".into(), - sub_usage.print(printer), + sub_happ.print(printer), ]) }) .map(|entry| { @@ -3091,14 +3144,11 @@ impl Print for QPtrMemUsage { }), "}", ), - QPtrMemUsageKind::DynOffsetBase { element, stride } => pretty::Fragment::new([ + DataHappKind::Repeated { element, stride } => pretty::Fragment::new([ "(".into(), num_lit(0), "..".into(), - self.max_size - .map(|max_size| max_size / stride.get()) - .map(num_lit) - .unwrap_or_default(), + self.max_size.map(|max_size| max_size / stride.get()).map_or_default(num_lit), ") × ".into(), num_lit(stride.get()), " => ".into(), @@ -3179,6 +3229,12 @@ impl Print for TypeDef { TypeOrConst::Const(ct) => ct.print(printer), }), ), + TypeKind::SpvTypeOperand => pretty::Fragment::new([ + printer.error_style().apply("type_of"), + "(".into(), + printer.declarative_keyword_style().apply("type"), + ")".into(), + ]), TypeKind::SpvStringLiteralForExtInst => pretty::Fragment::new([ printer.error_style().apply("type_of").into(), "(".into(), @@ -3337,6 +3393,9 @@ impl Print for ConstDef { &ConstKind::PtrToGlobalVar(gv) => { pretty::Fragment::new(["&".into(), gv.print(printer)]) } + &ConstKind::PtrToFunc(func) => { + pretty::Fragment::new(["&".into(), func.print(printer)]) + } ConstKind::SpvInst { spv_inst_and_const_inputs } => { let (spv_inst, const_inputs) = &**spv_inst_and_const_inputs; pretty::Fragment::new([ @@ -3349,6 +3408,7 @@ impl Print for ConstDef { printer.pretty_type_ascription_suffix(*ty), ]) } + ConstKind::SpvTypeOperand(ty) => ty.print(printer), &ConstKind::SpvStringLiteralForExtInst(s) => pretty::Fragment::new([ printer.pretty_spv_opcode(printer.spv_op_style(), wk.OpString), "(".into(), @@ -3380,139 +3440,146 @@ impl Print for GlobalVarDecl { let wk = &spv::spec::Spec::get().well_known; - // HACK(eddyb) get the pointee type from SPIR-V `OpTypePointer`, but - // ideally the `GlobalVarDecl` would hold that type itself. - let type_ascription_suffix = match &printer.cx[*type_of_ptr_to].kind { - TypeKind::QPtr if shape.is_some() => match shape.unwrap() { - qptr::shapes::GlobalVarShape::Handles { handle, fixed_count } => { - let handle = match handle { - qptr::shapes::Handle::Opaque(ty) => ty.print(printer), - qptr::shapes::Handle::Buffer(addr_space, buf) => pretty::Fragment::new([ - printer.declarative_keyword_style().apply("buffer").into(), - pretty::join_comma_sep( - "(", - [ - addr_space.print(printer), - pretty::Fragment::new([ - printer.pretty_named_argument_prefix("size"), - pretty::Fragment::new( - Some(buf.fixed_base.size) - .filter(|&base_size| { - base_size > 0 || buf.dyn_unit_stride.is_none() - }) - .map(|base_size| { - printer - .numeric_literal_style() - .apply(base_size.to_string()) - .into() - }) - .into_iter() - .chain(buf.dyn_unit_stride.map(|stride| { - pretty::Fragment::new([ - "N × ".into(), - printer - .numeric_literal_style() - .apply(stride.to_string()), - ]) - })) - .intersperse_with(|| " + ".into()), - ), - ]), - pretty::Fragment::new([ - printer.pretty_named_argument_prefix("align"), - printer - .numeric_literal_style() - .apply(buf.fixed_base.align.to_string()) - .into(), - ]), - ], - ")", - ), - ]), - }; + // HACK(eddyb) to avoid too many syntax variations, most details (other + // than the type, if present) use named arguments in `GV123(...)`. + let mut details = SmallVec::<[_; 4]>::new(); - let handles = if fixed_count.map_or(0, |c| c.get()) == 1 { - handle - } else { - pretty::Fragment::new([ - "[".into(), - fixed_count - .map(|count| { - pretty::Fragment::new([ - printer.numeric_literal_style().apply(count.to_string()), - " × ".into(), - ]) - }) - .unwrap_or_default(), - handle, - "]".into(), - ]) - }; - pretty::join_space(":", [handles]) - } - qptr::shapes::GlobalVarShape::UntypedData(mem_layout) => pretty::Fragment::new([ - " ".into(), - printer.declarative_keyword_style().apply("layout").into(), - pretty::join_comma_sep( - "(", - [ - pretty::Fragment::new([ - printer.pretty_named_argument_prefix("size"), - printer - .numeric_literal_style() - .apply(mem_layout.size.to_string()) - .into(), - ]), - pretty::Fragment::new([ - printer.pretty_named_argument_prefix("align"), - printer - .numeric_literal_style() - .apply(mem_layout.align.to_string()) - .into(), - ]), - ], - ")", - ), - ]), - qptr::shapes::GlobalVarShape::TypedInterface(ty) => { - printer.pretty_type_ascription_suffix(ty) - } - }, - TypeKind::SpvInst { spv_inst, type_and_const_inputs } + match addr_space { + AddrSpace::Handles => {} + AddrSpace::SpvStorageClass(_) => { + details.push(addr_space.print(printer)); + } + } + + // FIXME(eddyb) should this be a helper on `Printer`? + let num_lit = |x: u32| printer.numeric_literal_style().apply(format!("{x}")).into(); + + // FIXME(eddyb) should the pointer type be shown as something like + // `&GV123: OpTypePointer(..., T123)` *after* the variable definition? + // (but each reference can technically have a different type...) + let (qptr_shape, spv_ptr_pointee_type) = match &printer.cx[*type_of_ptr_to].kind { + TypeKind::QPtr => (shape.as_ref(), None), + + // HACK(eddyb) get the pointee type from SPIR-V `OpTypePointer`, but + // ideally the `GlobalVarDecl` would hold that type itself. + TypeKind::SpvInst { spv_inst, type_and_const_inputs, .. } if spv_inst.opcode == wk.OpTypePointer => { match type_and_const_inputs[..] { - [TypeOrConst::Type(ty)] => printer.pretty_type_ascription_suffix(ty), - _ => unreachable!(), + [TypeOrConst::Type(pointee_type)] => (None, Some(pointee_type)), + _ => (None, None), } } - _ => pretty::Fragment::new([ - ": ".into(), - printer.error_style().apply("pointee_type_of").into(), - "(".into(), - type_of_ptr_to.print(printer), - ")".into(), - ]), + + _ => (None, None), }; - let addr_space_suffix = match addr_space { - AddrSpace::Handles => pretty::Fragment::default(), - AddrSpace::SpvStorageClass(_) => { - pretty::Fragment::new([" in ".into(), addr_space.print(printer)]) + let ascribe_type = match qptr_shape { + Some(crate::mem::shapes::GlobalVarShape::Handles { handle, fixed_count }) => { + let handle = match handle { + crate::mem::shapes::Handle::Opaque(ty) => ty.print(printer), + crate::mem::shapes::Handle::Buffer(addr_space, buf) => pretty::Fragment::new([ + printer.declarative_keyword_style().apply("buffer").into(), + pretty::join_comma_sep( + "(", + [ + addr_space.print(printer), + pretty::Fragment::new([ + printer.pretty_named_argument_prefix("size"), + pretty::Fragment::new( + [ + Some(buf.fixed_base.size) + .filter(|&base_size| { + base_size > 0 || buf.dyn_unit_stride.is_none() + }) + .map(num_lit), + buf.dyn_unit_stride.map(|stride| { + pretty::Fragment::new([ + "N × ".into(), + num_lit(stride.get()), + ]) + }), + ] + .into_iter() + .flatten() + .intersperse_with(|| " + ".into()), + ), + ]), + pretty::Fragment::new([ + printer.pretty_named_argument_prefix("align"), + num_lit(buf.fixed_base.align), + ]), + ], + ")", + ), + ]), + }; + + let handles = if fixed_count.map_or(0, |c| c.get()) == 1 { + handle + } else { + pretty::Fragment::new([ + "[".into(), + fixed_count.map_or_default(|count| { + pretty::Fragment::new([num_lit(count.get()), " × ".into()]) + }), + handle, + "]".into(), + ]) + }; + Some(handles) } + Some(crate::mem::shapes::GlobalVarShape::UntypedData(mem_layout)) => { + details.extend([ + pretty::Fragment::new([ + printer.pretty_named_argument_prefix("size"), + num_lit(mem_layout.size), + ]), + pretty::Fragment::new([ + printer.pretty_named_argument_prefix("align"), + num_lit(mem_layout.align), + ]), + ]); + None + } + Some(crate::mem::shapes::GlobalVarShape::TypedInterface(ty)) => Some(ty.print(printer)), + + None => Some(match spv_ptr_pointee_type { + Some(ty) => ty.print(printer), + None => pretty::Fragment::new([ + printer.error_style().apply("pointee_type_of").into(), + "(".into(), + type_of_ptr_to.print(printer), + ")".into(), + ]), + }), }; - let header = pretty::Fragment::new([addr_space_suffix, type_ascription_suffix]); - let maybe_rhs = match def { + let import = match def { + // FIXME(eddyb) deduplicate with `FuncDecl`, and maybe consider + // putting the import *before* the declaration, to end up with: + // import "..." + // as global_var GV... DeclDef::Imported(import) => Some(import.print(printer)), DeclDef::Present(GlobalVarDefBody { initializer }) => { - // FIXME(eddyb) `global_varX in AS: T = Y` feels a bit wonky for - // the initializer, but it's cleaner than obvious alternatives. - initializer.map(|initializer| initializer.print(printer)) + if let Some(initializer) = initializer { + details.push(pretty::Fragment::new([ + printer.pretty_named_argument_prefix("init"), + initializer.print(printer), + ])); + } + None } }; - let body = maybe_rhs.map(|rhs| pretty::Fragment::new(["= ".into(), rhs])); - let def_without_name = pretty::Fragment::new([header, pretty::join_space("", body)]); + let def_without_name = pretty::Fragment::new( + [ + (!details.is_empty()).then(|| pretty::join_comma_sep("(", details, ")")), + ascribe_type.map(|ty| pretty::join_space(":", [ty])), + import.map(|import| pretty::Fragment::new([" = ".into(), import])), + ] + .into_iter() + .flatten(), + ); AttrsAndDef { attrs: attrs.print(printer), def_without_name } } @@ -3557,9 +3624,17 @@ impl Print for FuncDecl { ]); let def_without_name = match def { - DeclDef::Imported(import) => { - pretty::Fragment::new([sig, " = ".into(), import.print(printer)]) - } + // FIXME(eddyb) deduplicate with `GlobalVarDecl`, and maybe consider + // putting the import *before* the declaration, to end up with: + // import "..." + // as func F... + DeclDef::Imported(import) => pretty::Fragment::new([ + sig, + pretty::join_space( + "", + [pretty::Fragment::new(["= ".into(), import.print(printer)])], + ), + ]), // FIXME(eddyb) this can probably go into `impl Print for FuncDefBody`. DeclDef::Present(def) => pretty::Fragment::new([ @@ -3671,7 +3746,7 @@ impl Print for FuncAt<'_, Region> { }; let header = dbg_scope_defs_at(DbgScopeDefPlaceInRegion { before_node: None }) - .map(|dbg_scope_defs| { + .map_or_default(|dbg_scope_defs| { pretty::Fragment::new([ dbg_scope_defs, // HACK(eddyb) separate hoisted `DbgScope`s with an empty line. @@ -3679,8 +3754,7 @@ impl Print for FuncAt<'_, Region> { // for "vertical gap" instead. "\n\n".into(), ]) - }) - .unwrap_or_default(); + }); let body = (self.at(*children).into_iter()) .map(|func_at_node| { @@ -3903,15 +3977,10 @@ impl Print for FuncAt<'_, DataInst> { pretty::join_comma_sep("(", inputs.iter().map(|v| v.print(printer)), ")"), ]), - DataInstKind::QPtr(op) => { - let (qptr_input, extra_inputs) = match op { - // HACK(eddyb) `FuncLocalVar` should probably not even be in `QPtrOp`. - QPtrOp::FuncLocalVar(_) => (None, &inputs[..]), - _ => (Some(inputs[0]), &inputs[1..]), - }; - let (name, extra_inputs): (_, SmallVec<[_; 1]>) = match op { - QPtrOp::FuncLocalVar(mem_layout) => { - assert!(extra_inputs.len() <= 1); + DataInstKind::Mem(op) => { + let (name, inputs): (_, SmallVec<[_; 1]>) = match op { + MemOp::FuncLocalVar(mem_layout) => { + assert!(inputs.len() <= 1); ( "func_local_var", [ @@ -3931,7 +4000,7 @@ impl Print for FuncAt<'_, DataInst> { ]), ] .into_iter() - .chain(extra_inputs.first().map(|&init| { + .chain(inputs.first().map(|&init| { pretty::Fragment::new([ printer.pretty_named_argument_prefix("initializer"), init.print(printer), @@ -3941,6 +4010,35 @@ impl Print for FuncAt<'_, DataInst> { ) } + MemOp::Load => { + assert_eq!(inputs.len(), 1); + ("load", [inputs[0].print(printer)].into_iter().collect()) + } + MemOp::Store => { + assert_eq!(inputs.len(), 2); + ( + "store", + [inputs[0].print(printer), inputs[1].print(printer)] + .into_iter() + .collect(), + ) + } + }; + + pretty::Fragment::new([ + printer + .demote_style_for_namespace_prefix(printer.declarative_keyword_style()) + .apply("mem.") + .into(), + printer.declarative_keyword_style().apply(name).into(), + pretty::join_comma_sep("(", inputs, ")"), + ]) + } + + DataInstKind::QPtr(op) => { + let qptr_input = inputs[0].print(printer); + let extra_inputs = &inputs[1..]; + let (name, extra_inputs): (_, SmallVec<[_; 1]>) = match op { QPtrOp::HandleArrayIndex => { assert_eq!(extra_inputs.len(), 1); ( @@ -4002,15 +4100,6 @@ impl Print for FuncAt<'_, DataInst> { .collect(), ) } - - QPtrOp::Load => { - assert_eq!(extra_inputs.len(), 0); - ("load", [].into_iter().collect()) - } - QPtrOp::Store => { - assert_eq!(extra_inputs.len(), 1); - ("store", [extra_inputs[0].print(printer)].into_iter().collect()) - } }; pretty::Fragment::new([ @@ -4019,11 +4108,7 @@ impl Print for FuncAt<'_, DataInst> { .apply("qptr.") .into(), printer.declarative_keyword_style().apply(name).into(), - pretty::join_comma_sep( - "(", - qptr_input.map(|v| v.print(printer)).into_iter().chain(extra_inputs), - ")", - ), + pretty::join_comma_sep("(", [qptr_input].into_iter().chain(extra_inputs), ")"), ]) } @@ -4103,7 +4188,9 @@ impl Print for FuncAt<'_, DataInst> { } } } - ConstKind::PtrToGlobalVar(_) => {} + ConstKind::PtrToGlobalVar(_) + | ConstKind::PtrToFunc(_) + | ConstKind::SpvTypeOperand(_) => {} } } None @@ -4226,9 +4313,7 @@ impl Print for FuncAt<'_, DataInst> { let def_without_name = pretty::Fragment::new([ def_without_type, - output_type_to_print - .map(|ty| printer.pretty_type_ascription_suffix(ty)) - .unwrap_or_default(), + output_type_to_print.map_or_default(|ty| printer.pretty_type_ascription_suffix(ty)), ]); // FIXME(eddyb) this is quite verbose for prepending. @@ -4238,11 +4323,9 @@ impl Print for FuncAt<'_, DataInst> { ]); AttrsAndDef { attrs, def_without_name }.insert_name_before_def( - output_use_to_print_as_lhs - .map(|output_use| { - pretty::Fragment::new([output_use.print_as_def(printer), " = ".into()]) - }) - .unwrap_or_default(), + output_use_to_print_as_lhs.map_or_default(|output_use| { + pretty::Fragment::new([output_use.print_as_def(printer), " = ".into()]) + }), ) } } diff --git a/src/qptr/lift.rs b/src/qptr/lift.rs index c4af4e2f..59fdc79e 100644 --- a/src/qptr/lift.rs +++ b/src/qptr/lift.rs @@ -1,10 +1,8 @@ //! [`QPtr`](crate::TypeKind::QPtr) lifting (e.g. to SPIR-V). -// HACK(eddyb) sharing layout code with other modules. -use super::layout::*; - use crate::func_at::FuncAtMut; -use crate::qptr::{QPtrAttr, QPtrMemUsage, QPtrMemUsageKind, QPtrOp, QPtrUsage, shapes}; +use crate::mem::{DataHapp, DataHappKind, MemAccesses, MemAttr, MemOp, shapes}; +use crate::qptr::{QPtrAttr, QPtrOp}; use crate::transform::{InnerInPlaceTransform, InnerTransform, Transformed, Transformer}; use crate::{ AddrSpace, Attr, AttrSet, AttrSetDef, Const, ConstDef, ConstKind, Context, DataInst, @@ -18,6 +16,10 @@ use std::mem; use std::num::NonZeroU32; use std::rc::Rc; +// HACK(eddyb) sharing layout code with other modules. +// FIXME(eddyb) can this just be a non-glob import? +use crate::mem::layout::*; + struct LiftError(Diag); /// Context for lifting `QPtr`s to SPIR-V `OpTypePointer`s. @@ -44,7 +46,7 @@ impl<'a> LiftToSpvPtrs<'a> { pub fn lift_global_var(&self, global_var_decl: &mut GlobalVarDecl) { match self.spv_ptr_type_and_addr_space_for_global_var(global_var_decl) { Ok((spv_ptr_type, addr_space)) => { - global_var_decl.attrs = self.strip_qptr_usage_attr(global_var_decl.attrs); + global_var_decl.attrs = self.strip_mem_accesses_attr(global_var_decl.attrs); global_var_decl.type_of_ptr_to = spv_ptr_type; global_var_decl.addr_space = addr_space; global_var_decl.shape = None; @@ -67,29 +69,29 @@ impl<'a> LiftToSpvPtrs<'a> { deferred_ptr_noops: Default::default(), data_inst_use_counts: Default::default(), - func_has_qptr_analysis_bug_diags: false, + func_has_mem_analysis_bug_diags: false, } .in_place_transform_func_decl(&mut module.funcs[func]); } } - fn find_qptr_usage_attr(&self, attrs: AttrSet) -> Result<&QPtrUsage, LiftError> { + fn find_mem_accesses_attr(&self, attrs: AttrSet) -> Result<&MemAccesses, LiftError> { self.cx[attrs] .attrs .iter() .find_map(|attr| match attr { - Attr::QPtr(QPtrAttr::Usage(usage)) => Some(&usage.0), + Attr::Mem(MemAttr::Accesses(accesses)) => Some(&accesses.0), _ => None, }) - .ok_or_else(|| LiftError(Diag::bug(["missing `qptr.usage` attribute".into()]))) + .ok_or_else(|| LiftError(Diag::bug(["missing `mem.accesses` attribute".into()]))) } - fn strip_qptr_usage_attr(&self, attrs: AttrSet) -> AttrSet { + fn strip_mem_accesses_attr(&self, attrs: AttrSet) -> AttrSet { self.cx.intern(AttrSetDef { attrs: self.cx[attrs] .attrs .iter() - .filter(|attr| !matches!(attr, Attr::QPtr(QPtrAttr::Usage(_)))) + .filter(|attr| !matches!(attr, Attr::Mem(MemAttr::Accesses(_)))) .cloned() .collect(), }) @@ -101,7 +103,7 @@ impl<'a> LiftToSpvPtrs<'a> { ) -> Result<(Type, AddrSpace), LiftError> { let wk = self.wk; - let qptr_usage = self.find_qptr_usage_attr(global_var_decl.attrs)?; + let mem_accesses = self.find_mem_accesses_attr(global_var_decl.attrs)?; let shape = global_var_decl.shape.ok_or_else(|| LiftError(Diag::bug(["missing shape".into()])))?; @@ -109,17 +111,18 @@ impl<'a> LiftToSpvPtrs<'a> { (AddrSpace::Handles, shapes::GlobalVarShape::Handles { handle, fixed_count }) => { let (storage_class, handle_type) = match handle { shapes::Handle::Opaque(ty) => { - if self.pointee_type_for_usage(qptr_usage)? != ty { + if self.pointee_type_for_accesses(mem_accesses)? != ty { return Err(LiftError(Diag::bug([ - "mismatched opaque handle types in `qptr.usage` vs `shape`".into(), + "mismatched opaque handle types in `mem.accesses` vs `shape`" + .into(), ]))); } (wk.UniformConstant, ty) } - // FIXME(eddyb) validate usage against `buf` and/or expand + // FIXME(eddyb) validate accesses against `buf` and/or expand // the type to make sure it has the right size. shapes::Handle::Buffer(AddrSpace::SpvStorageClass(storage_class), _buf) => { - (storage_class, self.pointee_type_for_usage(qptr_usage)?) + (storage_class, self.pointee_type_for_accesses(mem_accesses)?) } shapes::Handle::Buffer(AddrSpace::Handles, _) => { return Err(LiftError(Diag::bug([ @@ -136,12 +139,12 @@ impl<'a> LiftToSpvPtrs<'a> { }, ) } - // FIXME(eddyb) validate usage against `layout` and/or expand + // FIXME(eddyb) validate accesses against `layout` and/or expand // the type to make sure it has the right size. ( AddrSpace::SpvStorageClass(storage_class), shapes::GlobalVarShape::UntypedData(_layout), - ) => (storage_class, self.pointee_type_for_usage(qptr_usage)?), + ) => (storage_class, self.pointee_type_for_accesses(mem_accesses)?), ( AddrSpace::SpvStorageClass(storage_class), shapes::GlobalVarShape::TypedInterface(ty), @@ -197,57 +200,58 @@ impl<'a> LiftToSpvPtrs<'a> { }) } - fn pointee_type_for_usage(&self, usage: &QPtrUsage) -> Result { + fn pointee_type_for_accesses(&self, accesses: &MemAccesses) -> Result { let wk = self.wk; - match usage { - &QPtrUsage::Handles(shapes::Handle::Opaque(ty)) => Ok(ty), - QPtrUsage::Handles(shapes::Handle::Buffer(_, data_usage)) => { - let attr_spv_decorate_block = Attr::SpvAnnotation(spv::Inst { - opcode: wk.OpDecorate, - imms: [spv::Imm::Short(wk.Decoration, wk.Block)].into_iter().collect(), - }); - match &data_usage.kind { - QPtrMemUsageKind::Unused => { - self.spv_op_type_struct([], [attr_spv_decorate_block]) - } - QPtrMemUsageKind::OffsetBase(fields) => self.spv_op_type_struct( - fields.iter().map(|(&field_offset, field_usage)| { - Ok((field_offset, self.pointee_type_for_mem_usage(field_usage)?)) + match accesses { + &MemAccesses::Handles(shapes::Handle::Opaque(ty)) => Ok(ty), + MemAccesses::Handles(shapes::Handle::Buffer(_, data_happ)) => { + let attr_spv_decorate_block = Attr::SpvAnnotation { + spv_inst: spv::Inst { + opcode: wk.OpDecorate, + imms: [spv::Imm::Short(wk.Decoration, wk.Block)].into_iter().collect(), + }, + per_instance_const_inputs: None, + }; + match &data_happ.kind { + DataHappKind::Dead => self.spv_op_type_struct([], [attr_spv_decorate_block]), + DataHappKind::Disjoint(fields) => self.spv_op_type_struct( + fields.iter().map(|(&field_offset, field_happ)| { + Ok((field_offset, self.pointee_type_for_data_happ(field_happ)?)) }), [attr_spv_decorate_block], ), - QPtrMemUsageKind::StrictlyTyped(_) - | QPtrMemUsageKind::DirectAccess(_) - | QPtrMemUsageKind::DynOffsetBase { .. } => self.spv_op_type_struct( - [Ok((0, self.pointee_type_for_mem_usage(data_usage)?))], + DataHappKind::StrictlyTyped(_) + | DataHappKind::Direct(_) + | DataHappKind::Repeated { .. } => self.spv_op_type_struct( + [Ok((0, self.pointee_type_for_data_happ(data_happ)?))], [attr_spv_decorate_block], ), } } - QPtrUsage::Memory(usage) => self.pointee_type_for_mem_usage(usage), + MemAccesses::Data(happ) => self.pointee_type_for_data_happ(happ), } } - fn pointee_type_for_mem_usage(&self, usage: &QPtrMemUsage) -> Result { - match &usage.kind { - QPtrMemUsageKind::Unused => self.spv_op_type_struct([], []), - &QPtrMemUsageKind::StrictlyTyped(ty) | &QPtrMemUsageKind::DirectAccess(ty) => Ok(ty), - QPtrMemUsageKind::OffsetBase(fields) => self.spv_op_type_struct( - fields.iter().map(|(&field_offset, field_usage)| { - Ok((field_offset, self.pointee_type_for_mem_usage(field_usage)?)) + fn pointee_type_for_data_happ(&self, happ: &DataHapp) -> Result { + match &happ.kind { + DataHappKind::Dead => self.spv_op_type_struct([], []), + &DataHappKind::StrictlyTyped(ty) | &DataHappKind::Direct(ty) => Ok(ty), + DataHappKind::Disjoint(fields) => self.spv_op_type_struct( + fields.iter().map(|(&field_offset, field_happ)| { + Ok((field_offset, self.pointee_type_for_data_happ(field_happ)?)) }), [], ), - QPtrMemUsageKind::DynOffsetBase { element, stride } => { - let element_type = self.pointee_type_for_mem_usage(element)?; + DataHappKind::Repeated { element, stride } => { + let element_type = self.pointee_type_for_data_happ(element)?; - let fixed_len = usage + let fixed_len = happ .max_size .map(|size| { if !size.is_multiple_of(stride.get()) { return Err(LiftError(Diag::bug([format!( - "DynOffsetBase: size ({size}) not a multiple of stride ({stride})" + "Repeated: size ({size}) not a multiple of stride ({stride})" ) .into()]))); } @@ -270,15 +274,18 @@ impl<'a> LiftToSpvPtrs<'a> { let stride_attrs = stride.map(|stride| { self.cx.intern(AttrSetDef { - attrs: [Attr::SpvAnnotation(spv::Inst { - opcode: wk.OpDecorate, - imms: [ - spv::Imm::Short(wk.Decoration, wk.ArrayStride), - spv::Imm::Short(wk.LiteralInteger, stride.get()), - ] - .into_iter() - .collect(), - })] + attrs: [Attr::SpvAnnotation { + spv_inst: spv::Inst { + opcode: wk.OpDecorate, + imms: [ + spv::Imm::Short(wk.Decoration, wk.ArrayStride), + spv::Imm::Short(wk.LiteralInteger, stride.get()), + ] + .into_iter() + .collect(), + }, + per_instance_const_inputs: None, + }] .into(), }) }); @@ -310,16 +317,19 @@ impl<'a> LiftToSpvPtrs<'a> { SmallVec::with_capacity(field_offsets_and_types.size_hint().0); for (i, field_offset_and_type) in field_offsets_and_types.enumerate() { let (offset, field_type) = field_offset_and_type?; - attrs.attrs.insert(Attr::SpvAnnotation(spv::Inst { - opcode: wk.OpMemberDecorate, - imms: [ - spv::Imm::Short(wk.LiteralInteger, i.try_into().unwrap()), - spv::Imm::Short(wk.Decoration, wk.Offset), - spv::Imm::Short(wk.LiteralInteger, offset), - ] - .into_iter() - .collect(), - })); + attrs.attrs.insert(Attr::SpvAnnotation { + spv_inst: spv::Inst { + opcode: wk.OpMemberDecorate, + imms: [ + spv::Imm::Short(wk.LiteralInteger, i.try_into().unwrap()), + spv::Imm::Short(wk.Decoration, wk.Offset), + spv::Imm::Short(wk.LiteralInteger, offset), + ] + .into_iter() + .collect(), + }, + per_instance_const_inputs: None, + }); type_and_const_inputs.push(TypeOrConst::Type(field_type)); } attrs.attrs.extend(extra_attrs); @@ -397,8 +407,8 @@ struct LiftToSpvPtrInstsInFunc<'a> { // FIXME(eddyb) consider removing this and just do a full second traversal. data_inst_use_counts: EntityOrientedDenseMap, - // HACK(eddyb) this is used to avoid noise when `qptr::analyze` failed. - func_has_qptr_analysis_bug_diags: bool, + // HACK(eddyb) this is used to avoid noise when `mem::analyze` failed. + func_has_mem_analysis_bug_diags: bool, } struct DeferredPtrNoop { @@ -458,13 +468,13 @@ impl LiftToSpvPtrInstsInFunc<'_> { return Ok(Transformed::Unchanged); } - DataInstKind::QPtr(QPtrOp::FuncLocalVar(_mem_layout)) => { - let qptr_usage = self.lifter.find_qptr_usage_attr(data_inst_def.attrs)?; + DataInstKind::Mem(MemOp::FuncLocalVar(_mem_layout)) => { + let mem_accesses = self.lifter.find_mem_accesses_attr(data_inst_def.attrs)?; // FIXME(eddyb) validate against `mem_layout`! - let pointee_type = self.lifter.pointee_type_for_usage(qptr_usage)?; + let pointee_type = self.lifter.pointee_type_for_accesses(mem_accesses)?; DataInstDef { - attrs: self.lifter.strip_qptr_usage_attr(data_inst_def.attrs), + attrs: self.lifter.strip_mem_accesses_attr(data_inst_def.attrs), kind: DataInstKind::SpvInst(spv::Inst { opcode: wk.OpVariable, imms: [spv::Imm::Short(wk.StorageClass, wk.Function)].into_iter().collect(), @@ -751,10 +761,12 @@ impl LiftToSpvPtrInstsInFunc<'_> { output_type: Some(self.lifter.spv_ptr_type(addr_space, layout.original_type)), } } - DataInstKind::QPtr(op @ (QPtrOp::Load | QPtrOp::Store)) => { + DataInstKind::Mem(op @ (MemOp::Load | MemOp::Store)) => { + // HACK(eddyb) `_` will match multiple variants soon. + #[allow(clippy::match_wildcard_for_single_variants)] let (spv_opcode, access_type) = match op { - QPtrOp::Load => (wk.OpLoad, data_inst_def.output_type.unwrap()), - QPtrOp::Store => (wk.OpStore, type_of_val(data_inst_def.inputs[1])), + MemOp::Load => (wk.OpLoad, data_inst_def.output_type.unwrap()), + MemOp::Store => (wk.OpStore, type_of_val(data_inst_def.inputs[1])), _ => unreachable!(), }; @@ -1116,16 +1128,15 @@ impl Transformer for LiftToSpvPtrInstsInFunc<'_> { Err(LiftError(e)) => { let data_inst_def = func_at_inst.def(); - // HACK(eddyb) do not add redundant errors to `qptr::analyze` bugs. - self.func_has_qptr_analysis_bug_diags = self - .func_has_qptr_analysis_bug_diags + // HACK(eddyb) do not add redundant errors to `mem::analyze` bugs. + self.func_has_mem_analysis_bug_diags = self.func_has_mem_analysis_bug_diags || self.lifter.cx[data_inst_def.attrs].attrs.iter().any(|attr| { match attr { Attr::Diagnostics(diags) => { diags.0.iter().any(|diag| match diag.level { DiagLevel::Bug(loc) => { - loc.file().ends_with("qptr/analyze.rs") - || loc.file().ends_with("qptr\\analyze.rs") + loc.file().ends_with("mem/analyze.rs") + || loc.file().ends_with("mem\\analyze.rs") } _ => false, }) @@ -1134,7 +1145,7 @@ impl Transformer for LiftToSpvPtrInstsInFunc<'_> { } }); - if !self.func_has_qptr_analysis_bug_diags { + if !self.func_has_mem_analysis_bug_diags { data_inst_def.attrs.push_diag(&self.lifter.cx, e); } } diff --git a/src/qptr/lower.rs b/src/qptr/lower.rs index 409ed07e..e452bed6 100644 --- a/src/qptr/lower.rs +++ b/src/qptr/lower.rs @@ -1,10 +1,8 @@ //! [`QPtr`](crate::TypeKind::QPtr) lowering (e.g. from SPIR-V). -// HACK(eddyb) layout code used to be in this module. -use super::layout::*; - use crate::func_at::FuncAtMut; -use crate::qptr::{QPtrAttr, QPtrOp, shapes}; +use crate::mem::{MemOp, shapes}; +use crate::qptr::{QPtrAttr, QPtrOp}; use crate::transform::{InnerInPlaceTransform, Transformed, Transformer}; use crate::{ AddrSpace, AttrSet, AttrSetDef, Const, ConstDef, ConstKind, Context, DataInst, DataInstDef, @@ -16,6 +14,9 @@ use std::cell::Cell; use std::num::NonZeroU32; use std::rc::Rc; +// HACK(eddyb) sharing layout code with other modules. +use crate::mem::layout::*; + struct LowerError(Diag); /// Context for lowering SPIR-V `OpTypePointer`s to `QPtr`s. @@ -161,6 +162,14 @@ impl<'a> LowerFromSpvPtrs<'a> { [spv::Imm::Short(_, sc)] => sc, _ => unreachable!(), }; + + // HACK(eddyb) keep function pointers separate, perhaps eventually + // adding an `OpTypeUntypedPointerKHR CodeSectionINTEL` equivalent + // to SPIR-T itself (after `SPV_KHR_untyped_pointers` support). + if sc == self.wk.CodeSectionINTEL { + return None; + } + let pointee = match type_and_const_inputs[..] { [TypeOrConst::Type(elem_type)] => elem_type, _ => unreachable!(), @@ -412,7 +421,7 @@ impl LowerFromSpvPtrInstsInFunc<'_> { match self.lowerer.layout_of(var_data_type)? { TypeLayout::Concrete(concrete) if concrete.mem_layout.dyn_unit_stride.is_none() => { ( - QPtrOp::FuncLocalVar(concrete.mem_layout.fixed_base).into(), + MemOp::FuncLocalVar(concrete.mem_layout.fixed_base).into(), data_inst_def.inputs.clone(), ) } @@ -424,14 +433,14 @@ impl LowerFromSpvPtrInstsInFunc<'_> { return Ok(Transformed::Unchanged); } assert_eq!(data_inst_def.inputs.len(), 1); - (QPtrOp::Load.into(), data_inst_def.inputs.clone()) + (MemOp::Load.into(), data_inst_def.inputs.clone()) } else if spv_inst.opcode == wk.OpStore { // FIXME(eddyb) support memory operands somehow. if !spv_inst.imms.is_empty() { return Ok(Transformed::Unchanged); } assert_eq!(data_inst_def.inputs.len(), 2); - (QPtrOp::Store.into(), data_inst_def.inputs.clone()) + (MemOp::Store.into(), data_inst_def.inputs.clone()) } else if spv_inst.opcode == wk.OpArrayLength { let field_idx = match spv_inst.imms[..] { [spv::Imm::Short(_, field_idx)] => field_idx, @@ -606,7 +615,7 @@ impl LowerFromSpvPtrInstsInFunc<'_> { match data_inst_def.kind { // Known semantics, no need to preserve SPIR-V pointer information. - DataInstKind::FuncCall(_) | DataInstKind::QPtr(_) => return, + DataInstKind::FuncCall(_) | DataInstKind::Mem(_) | DataInstKind::QPtr(_) => return, DataInstKind::SpvInst(_) | DataInstKind::SpvExtInst { .. } => {} } diff --git a/src/qptr/mod.rs b/src/qptr/mod.rs index da2091ec..ce675ebe 100644 --- a/src/qptr/mod.rs +++ b/src/qptr/mod.rs @@ -3,22 +3,17 @@ // FIXME(eddyb) consider `#[cfg(doc)] use crate::TypeKind::QPtr;` for doc comments. // FIXME(eddyb) PR description of https://github.com/EmbarkStudios/spirt/pull/24 // has more useful docs that could be copied here. +// +// FIXME(eddyb) fully update post-`mem`-split. use crate::{AddrSpace, OrdAssertEq, Type}; -use std::collections::BTreeMap; use std::num::NonZeroU32; use std::ops::Range; -use std::rc::Rc; // NOTE(eddyb) all the modules are declared here, but they're documented "inside" // (i.e. using inner doc comments). -pub mod analyze; -mod layout; pub mod lift; pub mod lower; -pub mod shapes; - -pub use layout::LayoutConfig; /// `QPtr`-specific attributes ([`Attr::QPtr`]). #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -52,97 +47,11 @@ pub enum QPtrAttr { addr_space: OrdAssertEq, pointee: OrdAssertEq, }, - - /// When applied to a `QPtr`-typed `GlobalVar`, `DataInst`, - /// `RegionInputDecl` or `NodeOutputDecl`, this tracks all the - /// ways in which the pointer may be used (see `QPtrUsage`). - Usage(OrdAssertEq), -} - -#[derive(Clone, PartialEq, Eq, Hash)] -pub enum QPtrUsage { - /// Used to access one or more handles (i.e. optionally indexed by - /// [`QPtrOp::HandleArrayIndex`]), which can be: - /// - `Handle::Opaque(handle_type)`: all uses involve [`QPtrOp::Load`] or - /// [`QPtrAttr::ToSpvPtrInput`], with the common type `handle_type` - /// - `Handle::Buffer(data_usage)`: carries with it `data_usage`, i.e. the - /// usage of the memory that can be accessed through [`QPtrOp::BufferData`] - Handles(shapes::Handle), - - // FIXME(eddyb) unify terminology around "concrete"/"memory"/"untyped (data)". - Memory(QPtrMemUsage), -} - -#[derive(Clone, PartialEq, Eq, Hash)] -pub struct QPtrMemUsage { - /// If present, this is a worst-case upper bound on memory accesses that may - /// be performed through this pointer. - // - // FIXME(eddyb) use proper newtypes for byte amounts. - // - // FIXME(eddyb) suboptimal naming choice, but other options are too verbose, - // including maybe using `RangeTo<_>` to explicitly indicate "exclusive". - // - // FIXME(eddyb) consider renaming such information to "extent", but that might - // be ambiguous with an offset range (as opposed to min/max of *possible* - // `offset_range.end`, i.e. "size"). - pub max_size: Option, - - pub kind: QPtrMemUsageKind, -} - -impl QPtrMemUsage { - pub const UNUSED: Self = Self { max_size: Some(0), kind: QPtrMemUsageKind::Unused }; -} - -#[derive(Clone, PartialEq, Eq, Hash)] -pub enum QPtrMemUsageKind { - /// Not actually used, which could be caused by pointer offsetting operations - /// with unused results, or as an intermediary state during analyses. - Unused, - - // FIXME(eddyb) replace the two leaves with e.g. `Leaf(Type, QPtrMemLeafUsage)`. - // - // - // - /// Used as a typed pointer (e.g. via unknown SPIR-V instructions), requiring - /// a specific choice of pointee type which cannot be modified, and has to be - /// reused as-is when lifting `QPtr`s back to typed pointers. - /// - /// Other overlapping uses can be merged into this one as long as they can - /// be fully expressed using the (transitive) components of this type. - StrictlyTyped(Type), - - /// Used directly to access memory (e.g. [`QPtrOp::Load`], [`QPtrOp::Store`]), - /// which can be decomposed as necessary (down to individual scalar leaves), - /// to allow maximal merging opportunities. - // - // FIXME(eddyb) track whether `Load`s and/or `Store`s are used, so that we - // can infer `NonWritable`/`NonReadable` annotations as well. - DirectAccess(Type), - - /// Used as a common base for (constant) offsetting, which requires it to have - /// its own (aggregate) type, when lifting `QPtr`s back to typed pointers. - OffsetBase(Rc>), - - /// Used as a common base for (dynamic) offsetting, which requires it to have - /// its own (array) type, when lifting `QPtr`s back to typed pointers, with - /// one single element type being repeated across the entire size. - DynOffsetBase { - // FIXME(eddyb) this feels inefficient. - element: Rc, - stride: NonZeroU32, - }, - // FIXME(eddyb) consider adding an `Union` case for driving legalization. } /// `QPtr`-specific operations ([`DataInstKind::QPtr`]). #[derive(Clone, PartialEq, Eq, Hash)] pub enum QPtrOp { - // HACK(eddyb) `OpVariable` replacement, which itself should not be kept as - // a `SpvInst` - once fn-local variables are lowered, this should go there. - FuncLocalVar(shapes::MemLayout), - /// Adjust a **handle array** `QPtr` (`inputs[0]`), by selecting the handle /// at the index (`inputs[1]`) from the handle array (i.e. the resulting /// `QPtr` is limited to that one handle and can't be further "moved around"). @@ -169,10 +78,7 @@ pub enum QPtrOp { // the redundant `(x * a + b - b) / a` to just `x`? // // FIXME(eddyb) actually lower `OpArrayLength` to this! - BufferDynLen { - fixed_base_size: u32, - dyn_unit_stride: NonZeroU32, - }, + BufferDynLen { fixed_base_size: u32, dyn_unit_stride: NonZeroU32 }, /// Adjust a **memory** `QPtr` (`inputs[0]`), by adding a (signed) immediate /// amount of bytes to its "address" (whether physical or conceptual). @@ -192,17 +98,4 @@ pub enum QPtrOp { // FIXME(eddyb) should this be an attribute/refinement? index_bounds: Option>, }, - - /// Read a single value from a `QPtr` (`inputs[0]`). - // - // FIXME(eddyb) limit this to memory, and scalars, maybe vectors at most. - Load, - - /// Write a single value (`inputs[1]`) to a `QPtr` (`inputs[0]`). - // - // FIXME(eddyb) limit this to memory, and scalars, maybe vectors at most. - Store, - // - // FIXME(eddyb) implement more ops! at the very least copying! - // (and lowering could ignore pointercasts, I guess?) } diff --git a/src/spv/lift.rs b/src/spv/lift.rs index 5bbb6551..dd5e74e9 100644 --- a/src/spv/lift.rs +++ b/src/spv/lift.rs @@ -127,6 +127,14 @@ impl Visitor<'_> for NeedsIdsCollector<'_> { } TypeKind::SpvInst { .. } => {} + + TypeKind::SpvTypeOperand => { + unreachable!( + "`TypeKind::SpvTypeOperand` should not be used \ + as a type outside of `ConstKind::SpvTypeOperand`" + ); + } + TypeKind::SpvStringLiteralForExtInst => { unreachable!( "`TypeKind::SpvStringLiteralForExtInst` should not be used \ @@ -144,11 +152,26 @@ impl Visitor<'_> for NeedsIdsCollector<'_> { } let ct_def = &self.cx[ct]; match ct_def.kind { - ConstKind::PtrToGlobalVar(_) | ConstKind::SpvInst { .. } => { + ConstKind::PtrToGlobalVar(_) | ConstKind::PtrToFunc(_) | ConstKind::SpvInst { .. } => { self.visit_const_def(ct_def); self.globals.insert(global); } + // HACK(eddyb) because this is merely a way to refer to `wrapped_type` + // as a `Value` (for a SPIR-V operand), it needs to be special-cased, + // without visiting its type, or an entry in `self.globals`. + ConstKind::SpvTypeOperand(wrapped_type) => { + let ConstDef { attrs, ty, kind: _ } = ct_def; + + assert!(*attrs == AttrSet::default()); + assert!( + self.cx[*ty] + == TypeDef { attrs: AttrSet::default(), kind: TypeKind::SpvTypeOperand } + ); + + self.visit_type_use(wrapped_type); + } + // HACK(eddyb) because this is an `OpString` and needs to go earlier // in the module than any `OpConstant*`, it needs to be special-cased, // without visiting its type, or an entry in `self.globals`. @@ -198,6 +221,7 @@ impl Visitor<'_> for NeedsIdsCollector<'_> { fn visit_attr(&mut self, attr: &Attr) { match *attr { Attr::Diagnostics(_) + | Attr::Mem(_) | Attr::QPtr(_) | Attr::SpvAnnotation { .. } | Attr::SpvBitflagsOperand(_) => {} @@ -211,6 +235,12 @@ impl Visitor<'_> for NeedsIdsCollector<'_> { fn visit_data_inst_def(&mut self, data_inst_def: &DataInstDef) { #[allow(clippy::match_same_arms)] match data_inst_def.kind { + // FIXME(eddyb) this should be a proper `Result`-based error instead, + // and/or `spv::lift` should mutate the module for legalization. + DataInstKind::Mem(_) => { + unreachable!("`DataInstKind::Mem` should be legalized away before lifting"); + } + // FIXME(eddyb) this should be a proper `Result`-based error instead, // and/or `spv::lift` should mutate the module for legalization. DataInstKind::QPtr(_) => { @@ -229,6 +259,9 @@ impl Visitor<'_> for NeedsIdsCollector<'_> { } struct AllocatedIds<'a> { + // HACK(eddyb) only for `Index` impl. + cx: &'a Context, + ext_inst_imports: BTreeMap<&'a str, spv::Id>, debug_strings: BTreeMap<&'a str, spv::Id>, @@ -238,6 +271,19 @@ struct AllocatedIds<'a> { funcs: FxIndexMap>, } +// HACK(eddyb) this makes accessing the right ID a bit easier. +impl std::ops::Index for AllocatedIds<'_> { + type Output = spv::Id; + fn index(&self, ct: Const) -> &Self::Output { + match self.cx[ct].kind { + ConstKind::SpvTypeOperand(ty) => &self.globals[&Global::Type(ty)], + ConstKind::SpvStringLiteralForExtInst(s) => &self.debug_strings[&self.cx[s]], + + _ => &self.globals[&Global::Const(ct)], + } + } +} + // FIXME(eddyb) should this use ID ranges instead of `SmallVec<[spv::Id; 4]>`? struct FuncLifting<'a> { func_id: spv::Id, @@ -358,6 +404,8 @@ impl<'a> NeedsIdsCollector<'a> { } = self; Ok(AllocatedIds { + cx, + ext_inst_imports: ext_inst_imports .into_iter() .map(|name| Ok((name, alloc_id()?))) @@ -863,22 +911,70 @@ impl<'a> FuncLifting<'a> { // HACK(eddyb) this takes advantage of `blocks` being an `IndexMap`, // to iterate at the same time as mutating other entries. for block_idx in (0..blocks.len()).rev() { - let BlockLifting { terminator: original_terminator, .. } = &blocks[block_idx]; + // HACK(eddyb) elide empty cases of an `if`-`else`/`switch`, as + // SPIR-V allows their targets to just be the whole merge block + // (the same one that `OpSelectionMerge` describes). + let block = &blocks[block_idx]; + if let (cfg::ControlInstKind::SelectBranch(_), Some(Merge::Selection(merge_point))) = + (&*block.terminator.kind, block.terminator.merge) + { + for target_idx in 0..block.terminator.targets.len() { + let block = &blocks[block_idx]; + let target = block.terminator.targets[target_idx]; + if !block + .terminator + .target_phi_values + .get(&target) + .copied() + .unwrap_or_default() + .is_empty() + { + continue; + } + + let target_is_trivial_branch = { + let BlockLifting { + phis, + insts, + terminator: + Terminator { attrs, kind, inputs, targets, target_phi_values, merge }, + } = &blocks[&target]; + + (phis.is_empty() + && insts.iter().all(|insts| insts.is_empty()) + && *attrs == AttrSet::default() + && matches!(**kind, cfg::ControlInstKind::Branch) + && inputs.is_empty() + && targets.len() == 1 + && target_phi_values.is_empty() + && merge.is_none()) + .then(|| targets[0]) + }; + if let Some(target_of_target) = target_is_trivial_branch + && target_of_target == merge_point + { + blocks[block_idx].terminator.targets[target_idx] = target_of_target; + *use_counts.get_mut(&target).unwrap() -= 1; + *use_counts.get_mut(&target_of_target).unwrap() += 1; + } + } + } + let block = &blocks[block_idx]; let is_trivial_branch = { let Terminator { attrs, kind, inputs, targets, target_phi_values, merge } = - original_terminator; + &block.terminator; - *attrs == AttrSet::default() + (*attrs == AttrSet::default() && matches!(**kind, cfg::ControlInstKind::Branch) && inputs.is_empty() && targets.len() == 1 && target_phi_values.is_empty() - && merge.is_none() + && merge.is_none()) + .then(|| targets[0]) }; - if is_trivial_branch { - let target = original_terminator.targets[0]; + if let Some(target) = is_trivial_branch { let target_use_count = use_counts.get_mut(&target).unwrap(); if *target_use_count == 1 { @@ -1032,10 +1128,13 @@ impl LazyInst<'_, '_> { }; (gv_decl.attrs, import) } - ConstKind::SpvInst { .. } => (ct_def.attrs, None), + ConstKind::PtrToFunc(_) | ConstKind::SpvInst { .. } => { + (ct_def.attrs, None) + } // Not inserted into `globals` while visiting. - ConstKind::SpvStringLiteralForExtInst(_) => unreachable!(), + ConstKind::SpvTypeOperand(_) + | ConstKind::SpvStringLiteralForExtInst(_) => unreachable!(), } } }; @@ -1069,11 +1168,7 @@ impl LazyInst<'_, '_> { let cx = module.cx_ref(); let value_to_id = |parent_func: &FuncLifting<'_>, v| match v { - Value::Const(ct) => match cx[ct].kind { - ConstKind::SpvStringLiteralForExtInst(s) => ids.debug_strings[&cx[s]], - - _ => ids.globals[&Global::Const(ct)], - }, + Value::Const(ct) => ids[ct], Value::RegionInput { region, input_idx } => { let input_idx = usize::try_from(input_idx).unwrap(); match parent_func.region_inputs_source.get(®ion) { @@ -1105,17 +1200,17 @@ impl LazyInst<'_, '_> { result_id, ids: type_and_const_inputs .iter() - .map(|&ty_or_ct| { - ids.globals[&match ty_or_ct { - TypeOrConst::Type(ty) => Global::Type(ty), - TypeOrConst::Const(ct) => Global::Const(ct), - }] + .map(|&ty_or_ct| match ty_or_ct { + TypeOrConst::Type(ty) => ids.globals[&Global::Type(ty)], + TypeOrConst::Const(ct) => ids[ct], }) .collect(), }, // Not inserted into `globals` while visiting. - TypeKind::QPtr | TypeKind::SpvStringLiteralForExtInst => unreachable!(), + TypeKind::QPtr + | TypeKind::SpvTypeOperand + | TypeKind::SpvStringLiteralForExtInst => unreachable!(), }, Global::Const(ct) => { let ct_def = &cx[ct]; @@ -1139,8 +1234,9 @@ impl LazyInst<'_, '_> { }; let initializer = match gv_decl.def { DeclDef::Imported(_) => None, - DeclDef::Present(GlobalVarDefBody { initializer }) => initializer - .map(|initializer| ids.globals[&Global::Const(initializer)]), + DeclDef::Present(GlobalVarDefBody { initializer }) => { + initializer.map(|initializer| ids[initializer]) + } }; spv::InstWithIds { without_ids: spv::Inst { @@ -1153,21 +1249,27 @@ impl LazyInst<'_, '_> { } } + &ConstKind::PtrToFunc(func) => spv::InstWithIds { + without_ids: wk.OpConstantFunctionPointerINTEL.into(), + result_type_id: Some(ids.globals[&Global::Type(ct_def.ty)]), + result_id, + ids: [ids.funcs[&func].func_id].into_iter().collect(), + }, + ConstKind::SpvInst { spv_inst_and_const_inputs } => { let (spv_inst, const_inputs) = &**spv_inst_and_const_inputs; spv::InstWithIds { without_ids: spv_inst.clone(), result_type_id: Some(ids.globals[&Global::Type(ct_def.ty)]), result_id, - ids: const_inputs - .iter() - .map(|&ct| ids.globals[&Global::Const(ct)]) - .collect(), + ids: const_inputs.iter().map(|&ct| ids[ct]).collect(), } } // Not inserted into `globals` while visiting. - ConstKind::SpvStringLiteralForExtInst(_) => unreachable!(), + ConstKind::SpvTypeOperand(_) | ConstKind::SpvStringLiteralForExtInst(_) => { + unreachable!() + } } } }, @@ -1225,7 +1327,7 @@ impl LazyInst<'_, '_> { Self::DataInst { parent_func, result_id: _, data_inst_def } => { let (inst, extra_initial_id_operand) = match &data_inst_def.kind { // Disallowed while visiting. - DataInstKind::QPtr(_) => unreachable!(), + DataInstKind::Mem(_) | DataInstKind::QPtr(_) => unreachable!(), &DataInstKind::FuncCall(callee) => { (wk.OpFunctionCall.into(), Some(ids.funcs[&callee].func_id)) @@ -1504,27 +1606,40 @@ impl Module { match attr { Attr::DbgSrcLoc(_) | Attr::Diagnostics(_) + | Attr::Mem(_) | Attr::QPtr(_) | Attr::SpvBitflagsOperand(_) => {} - Attr::SpvAnnotation(inst @ spv::Inst { opcode, .. }) => { + Attr::SpvAnnotation { + spv_inst: inst @ spv::Inst { opcode, .. }, + per_instance_const_inputs, + } => { let target_id = result_id.expect( "FIXME: it shouldn't be possible to attach \ - attributes to instructions without an output", + attributes to instructions without an output", ); - let inst = spv::InstWithIds { + let empty_const_inputs = SmallVec::new(); + let instances = per_instance_const_inputs + .as_ref() + .map_or(std::slice::from_ref(&empty_const_inputs), |instances| { + &instances.0[..] + }); + + let insts = instances.iter().map(|const_inputs| spv::InstWithIds { without_ids: inst.clone(), result_type_id: None, result_id: None, - ids: iter::once(target_id).collect(), - }; + ids: iter::once(target_id) + .chain(const_inputs.iter().map(|&ct| ids[ct])) + .collect(), + }); if [wk.OpExecutionMode, wk.OpExecutionModeId].contains(opcode) { - execution_mode_insts.push(inst); + execution_mode_insts.extend(insts); } else if [wk.OpName, wk.OpMemberName].contains(opcode) { - debug_name_insts.push(inst); + debug_name_insts.extend(insts); } else { - decoration_insts.push(inst); + decoration_insts.extend(insts); } } } diff --git a/src/spv/lower.rs b/src/spv/lower.rs index a2902c4a..4ea1ba82 100644 --- a/src/spv/lower.rs +++ b/src/spv/lower.rs @@ -9,6 +9,7 @@ use crate::{ Module, NodeDef, NodeKind, Region, RegionDef, RegionInputDecl, SelectionKind, Type, TypeDef, TypeKind, TypeOrConst, Value, cfg, print, }; +use itertools::Itertools as _; use rustc_hash::FxHashMap; use smallvec::SmallVec; use std::collections::{BTreeMap, BTreeSet}; @@ -22,8 +23,16 @@ enum IdDef { Type(Type), Const(Const), + // HACK(eddyb) for illegal cycles caused by global initializers. + PtrToGlobalVarForwardRef(Const), + Func(Func), + // HACK(eddyb) despite `FuncBody` deferring ID resolution to allow forward + // references *between* functions, function pointer *constants* need a `Func` + // long before any `OpFunction`s, so they're pre-defined as dummy imports. + FuncForwardRef(Func), + SpvExtInstImport(InternedStr), SpvDebugString(InternedStr), } @@ -34,9 +43,9 @@ impl IdDef { // FIXME(eddyb) print these with some kind of "maximum depth", // instead of just describing the kind of definition. IdDef::Type(_) => "a type".into(), - IdDef::Const(_) => "a constant".into(), + IdDef::Const(_) | IdDef::PtrToGlobalVarForwardRef(_) => "a constant".into(), - IdDef::Func(_) => "a function".into(), + IdDef::Func(_) | IdDef::FuncForwardRef(_) => "a function".into(), IdDef::SpvExtInstImport(name) => { format!("`OpExtInstImport {:?}`", &cx[name]) @@ -110,9 +119,95 @@ impl Module { let spv_spec = spec::Spec::get(); let wk = &spv_spec.well_known; + // HACK(eddyb) useful for embedding `Type` in `Const` whenever necessary. + let spv_type_operand_as_const = |ty| { + cx.intern(ConstDef { + attrs: AttrSet::default(), + ty: cx.intern(TypeKind::SpvTypeOperand), + kind: ConstKind::SpvTypeOperand(ty), + }) + }; + // HACK(eddyb) used to quickly check whether an `OpVariable` is global. let storage_class_function_imm = spv::Imm::Short(wk.StorageClass, wk.Function); + // HACK(eddyb) used as the `GlobalVarDecl` for an `IdDef::PtrToGlobalVarForwardRef`. + let dummy_decl_for_global_var_forward_ref = + |spv_inst: &spv::InstWithIds, type_of_ptr_to| { + assert!(spv_inst.opcode == wk.OpVariable); + + let storage_class = match spv_inst.imms[..] { + [spv::Imm::Short(kind, storage_class)] => { + assert_eq!(kind, wk.StorageClass); + storage_class + } + _ => unreachable!(), + }; + + GlobalVarDecl { + attrs: { + let mut attrs = AttrSet::default(); + attrs.push_diag( + &cx, + Diag::err([ + "global ID used as forward reference but never defined".into() + ]), + ); + attrs + }, + type_of_ptr_to, + shape: None, + addr_space: AddrSpace::SpvStorageClass(storage_class), + def: DeclDef::Imported(Import::LinkName(cx.intern(""))), + } + }; + // HACK(eddyb) no `PartialEq` on `GlobalVarDecl`. + let assert_is_dummy_decl_for_global_var_forward_ref = + |decl: &GlobalVarDecl, spv_inst: &spv::InstWithIds| { + let dummy_decl = + dummy_decl_for_global_var_forward_ref(spv_inst, decl.type_of_ptr_to); + let [expected, found] = [&dummy_decl, decl].map( + |GlobalVarDecl { attrs, type_of_ptr_to, shape, addr_space, def }| { + let DeclDef::Imported(import) = def else { + unreachable!(); + }; + (attrs, type_of_ptr_to, shape, addr_space, import) + }, + ); + assert!(expected == found); + }; + + // HACK(eddyb) used as the `FuncDecl` for an `IdDef::FuncForwardRef`. + let dummy_decl_for_func_forward_ref = FuncDecl { + attrs: { + let mut attrs = AttrSet::default(); + attrs.push_diag( + &cx, + Diag::err(["function ID used as forward reference but never defined".into()]), + ); + attrs + }, + // FIXME(eddyb) this gets simpler w/ disaggregation. + ret_type: cx.intern(TypeKind::SpvInst { + spv_inst: wk.OpTypeVoid.into(), + type_and_const_inputs: [].into_iter().collect(), + }), + params: [].into_iter().collect(), + def: DeclDef::Imported(Import::LinkName(cx.intern(""))), + }; + // HACK(eddyb) no `PartialEq` on `FuncDecl`. + let assert_is_dummy_decl_for_func_forward_ref = |decl: &FuncDecl| { + let [expected, found] = [&dummy_decl_for_func_forward_ref, decl].map( + |FuncDecl { attrs, ret_type, params, def }| { + let DeclDef::Imported(import) = def else { + unreachable!(); + }; + (attrs, ret_type, params, import) + }, + ); + assert!(expected == found); + }; + let mut module = { let [magic, version, generator_magic, id_bound, reserved_inst_schema] = parser.header; @@ -182,7 +277,8 @@ impl Module { let mut seq = None; let mut has_memory_model = false; - let mut pending_attrs = FxHashMap::::default(); + let mut pending_spv_annotations = + FxHashMap::)>>::default(); let mut pending_imports = FxHashMap::::default(); let mut pending_exports = vec![]; let mut current_dbg_src_loc = None; @@ -191,7 +287,7 @@ impl Module { let mut pending_func_bodies = vec![]; let mut current_func_body = None; - let mut spv_insts = parser.peekable(); + let mut spv_insts = parser.multipeek(); while let Some(mut inst) = spv_insts.next().transpose()? { let opcode = inst.opcode; @@ -253,8 +349,58 @@ impl Module { } current_block_id = new_block_id; - let mut attrs = - inst.result_id.and_then(|id| pending_attrs.remove(&id)).unwrap_or_default(); + let mut attrs = crate::AttrSetDef::default(); + + { + let annotations = inst + .result_id + .and_then(|id| pending_spv_annotations.remove(&id)) + .unwrap_or_default(); + + // HACK(eddyb) when `per_instance_const_inputs` is `Some` in + // `Attr::SpvAnnotation`, it must collect all "instances", + // i.e. all occurrences of the same `spv_inst` value, so this + // map papers over `Attr` not having a key/value split itself. + let mut instances_per_spv_inst: FxIndexMap> = + FxIndexMap::default(); + + for (spv_inst, operand_ids) in annotations { + if operand_ids.is_empty() { + attrs.attrs.insert(Attr::SpvAnnotation { + spv_inst, + per_instance_const_inputs: None, + }); + continue; + } + + let const_inputs = operand_ids + .iter() + .map(|&id| match id_defs.get(&id) { + Some(&IdDef::Type(ty)) => Ok(spv_type_operand_as_const(ty)), + Some(&IdDef::Const(ct)) => Ok(ct), + Some(id_def) => Err(id_def.descr(&cx)), + None => Err(format!("a forward reference to %{id}")), + }) + .map(|result| { + result.map_err(|descr| { + invalid(&format!( + "unsupported use of {descr} in `{}`", + spv_inst.opcode.name() + )) + }) + }) + .collect::>()?; + + instances_per_spv_inst.entry(spv_inst).or_default().push(const_inputs); + } + + attrs.attrs.extend(instances_per_spv_inst.into_iter().map( + |(spv_inst, instances)| Attr::SpvAnnotation { + spv_inst, + per_instance_const_inputs: Some(crate::OrdAssertEq(Rc::new(instances))), + }, + )); + } if let Some(dbg_src_loc) = current_dbg_src_loc { attrs.set_dbg_src_loc(dbg_src_loc); @@ -404,6 +550,7 @@ impl Module { // Absorb all following `OpSourceContinued` into `contents`. while let Some(Ok(cont_inst)) = spv_insts.peek() { if cont_inst.opcode != wk.OpSourceContinued { + spv_insts.reset_peek(); break; } let cont_inst = spv_insts.next().unwrap().unwrap(); @@ -477,23 +624,23 @@ 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.OpMemberDecorate, + wk.OpMemberDecorateIdEXT, wk.OpMemberDecorateString, ] .contains(&opcode) { 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")); - } + let target_id = inst.ids.remove(0); + let operand_ids = inst.ids; + let inst = inst.without_ids; match inst.imms[..] { // Special-case `OpDecorate LinkageAttributes ... Import|Export`. @@ -506,6 +653,8 @@ impl Module { && lt_kind == wk.LinkageType && [wk.Import, wk.Export].contains(&linkage_type) => { + assert_eq!(operand_ids.len(), 0); + let name = spv::extract_literal_string(name) .map_err(|e| invalid(&format!("{} in {:?}", e, e.as_bytes())))?; let name = cx.intern(name); @@ -518,11 +667,10 @@ impl Module { } _ => { - pending_attrs + pending_spv_annotations .entry(target_id) .or_default() - .attrs - .insert(Attr::SpvAnnotation(inst.without_ids)); + .push((inst, operand_ids)); } }; @@ -566,8 +714,11 @@ impl Module { .map(|&id| match id_defs.get(&id) { Some(&IdDef::Type(ty)) => Ok(TypeOrConst::Type(ty)), Some(&IdDef::Const(ct)) => Ok(TypeOrConst::Const(ct)), + None + | Some(IdDef::PtrToGlobalVarForwardRef(_) | IdDef::FuncForwardRef(_)) => { + Err(format!("a forward reference to %{id}")) + } Some(id_def) => Err(id_def.descr(&cx)), - None => Err(format!("a forward reference to %{id}")), }) .map(|result| { result.map_err(|descr| { @@ -582,6 +733,38 @@ impl Module { }); id_defs.insert(id, IdDef::Type(ty)); + Seq::TypeConstOrGlobalVar + } else if opcode == wk.OpConstantFunctionPointerINTEL { + use std::collections::hash_map::Entry; + + let id = inst.result_id.unwrap(); + + let func_id = inst.ids[0]; + let func = match id_defs.entry(func_id) { + Entry::Occupied(entry) => match entry.get() { + &IdDef::FuncForwardRef(func) => Ok(func), + id_def => Err(id_def.descr(&cx)), + }, + Entry::Vacant(entry) => { + let func = + module.funcs.define(&cx, dummy_decl_for_func_forward_ref.clone()); + entry.insert(IdDef::FuncForwardRef(func)); + Ok(func) + } + } + .map_err(|descr| { + invalid(&format!( + "unsupported use of {descr} as the `OpConstantFunctionPointerINTEL` operand" + )) + })?; + + let ct = cx.intern(ConstDef { + attrs: mem::take(&mut attrs), + ty: result_type.unwrap(), + kind: ConstKind::PtrToFunc(func), + }); + id_defs.insert(id, IdDef::Const(ct)); + Seq::TypeConstOrGlobalVar } else if inst_category == spec::InstructionCategory::Const || opcode == wk.OpUndef { let id = inst.result_id.unwrap(); @@ -589,9 +772,45 @@ impl Module { .ids .iter() .map(|&id| match id_defs.get(&id) { - Some(&IdDef::Const(ct)) => Ok(ct), + Some(&IdDef::Type(ty)) => Ok(spv_type_operand_as_const(ty)), + Some(&IdDef::Const(ct) | &IdDef::PtrToGlobalVarForwardRef(ct)) => Ok(ct), Some(id_def) => Err(id_def.descr(&cx)), - None => Err(format!("a forward reference to %{id}")), + None => { + // HACK(eddyb) search for a matching `OpVariable` + // later on, just in case this is a cycle caused + // by the initializer value of a global. + let mut found = None; + while let Some(Ok(later_inst)) = spv_insts.peek() { + if later_inst.opcode == wk.OpFunction { + break; + } + if later_inst.opcode == wk.OpVariable + && later_inst.result_id == Some(id) + && let Some(&IdDef::Type(ty)) = + id_defs.get(&later_inst.result_type_id.unwrap()) + { + let global_var = module.global_vars.define( + &cx, + dummy_decl_for_global_var_forward_ref(later_inst, ty), + ); + let ptr_to_global_var = cx.intern(ConstDef { + attrs: AttrSet::default(), + ty, + kind: ConstKind::PtrToGlobalVar(global_var), + }); + id_defs.insert( + id, + IdDef::PtrToGlobalVarForwardRef(ptr_to_global_var), + ); + found = Some(ptr_to_global_var); + break; + } + } + + let ct = + found.ok_or_else(|| format!("a forward reference to %{id}"))?; + Ok(ct) + } }) .map(|result| { result.map_err(|descr| { @@ -640,8 +859,11 @@ impl Module { let initializer = initializer .map(|id| match id_defs.get(&id) { Some(&IdDef::Const(ct)) => Ok(ct), + None + | Some(IdDef::PtrToGlobalVarForwardRef(_) | IdDef::FuncForwardRef(_)) => { + Err(format!("a forward reference to %{id}")) + } Some(id_def) => Err(id_def.descr(&cx)), - None => Err(format!("a forward reference to %{id}")), }) .transpose() .map_err(|descr| { @@ -663,22 +885,48 @@ impl Module { None => DeclDef::Present(GlobalVarDefBody { initializer }), }; - let global_var = module.global_vars.define( - &cx, - GlobalVarDecl { - attrs: mem::take(&mut attrs), - type_of_ptr_to: type_of_ptr_to_global_var, - shape: None, - addr_space: AddrSpace::SpvStorageClass(storage_class), - def, - }, - ); - let ptr_to_global_var = cx.intern(ConstDef { - attrs: AttrSet::default(), - ty: type_of_ptr_to_global_var, - kind: ConstKind::PtrToGlobalVar(global_var), - }); - id_defs.insert(global_var_id, IdDef::Const(ptr_to_global_var)); + let decl = GlobalVarDecl { + attrs: mem::take(&mut attrs), + type_of_ptr_to: type_of_ptr_to_global_var, + shape: None, + addr_space: AddrSpace::SpvStorageClass(storage_class), + def, + }; + + { + use std::collections::hash_map::Entry; + + match id_defs.entry(global_var_id) { + Entry::Occupied(mut entry) => match entry.get() { + &IdDef::PtrToGlobalVarForwardRef(ct) => { + let ConstKind::PtrToGlobalVar(global_var) = cx[ct].kind else { + unreachable!(); + }; + let decl_slot = &mut module.global_vars[global_var]; + assert_is_dummy_decl_for_global_var_forward_ref(decl_slot, &inst); + *decl_slot = decl; + + entry.insert(IdDef::Const(ct)); + } + id_def => { + return Err(invalid(&format!( + "invalid redefinition of {} as a new global", + id_def.descr(&cx) + ))); + } + }, + Entry::Vacant(entry) => { + let ptr_to_global_var = cx.intern(ConstDef { + attrs: AttrSet::default(), + ty: type_of_ptr_to_global_var, + kind: ConstKind::PtrToGlobalVar( + module.global_vars.define(&cx, decl), + ), + }); + entry.insert(IdDef::Const(ptr_to_global_var)); + } + } + } Seq::TypeConstOrGlobalVar } else if opcode == wk.OpFunction { @@ -754,19 +1002,40 @@ impl Module { }) } }; + let decl = FuncDecl { + attrs: mem::take(&mut attrs), + ret_type: func_ret_type, + params: func_type_param_types + .map(|ty| FuncParam { attrs: AttrSet::default(), ty }) + .collect(), + def, + }; - let func = module.funcs.define( - &cx, - FuncDecl { - attrs: mem::take(&mut attrs), - ret_type: func_ret_type, - params: func_type_param_types - .map(|ty| FuncParam { attrs: AttrSet::default(), ty }) - .collect(), - def, - }, - ); - id_defs.insert(func_id, IdDef::Func(func)); + let func = { + use std::collections::hash_map::Entry; + + match id_defs.entry(func_id) { + Entry::Occupied(mut entry) => match entry.get() { + &IdDef::FuncForwardRef(func) => { + let decl_slot = &mut module.funcs[func]; + assert_is_dummy_decl_for_func_forward_ref(decl_slot); + *decl_slot = decl; + + entry.insert(IdDef::Func(func)); + Ok(func) + } + id_def => Err(id_def.descr(&cx)), + }, + Entry::Vacant(entry) => { + let func = module.funcs.define(&cx, decl); + entry.insert(IdDef::Func(func)); + Ok(func) + } + } + .map_err(|descr| { + invalid(&format!("invalid redefinition of {descr} as a new function")) + })? + }; current_func_body = Some(FuncBody { func_id, func, insts: vec![] }); @@ -817,9 +1086,9 @@ impl Module { return Err(invalid("missing OpMemoryModel")); } - if !pending_attrs.is_empty() { - let ids = pending_attrs.keys().collect::>(); - return Err(invalid(&format!("decorated IDs never defined: {ids:?}"))); + if !pending_spv_annotations.is_empty() { + let ids = pending_spv_annotations.keys().collect::>(); + return Err(invalid(&format!("annotated IDs never defined: {ids:?}"))); } if current_func_body.is_some() { @@ -1135,46 +1404,47 @@ impl Module { // FIXME(eddyb) find a more compact name and/or make this a method. // FIXME(eddyb) this returns `LocalIdDef` even for global values. - let lookup_global_or_local_id_for_data_or_control_inst_input = - |id| match id_defs.get(&id) { - Some(&IdDef::Const(ct)) => Ok(LocalIdDef::Value(Value::Const(ct))), - Some(id_def @ IdDef::Type(_)) => Err(invalid(&format!( - "unsupported use of {} as an operand for \ - an instruction in a function", - id_def.descr(&cx), - ))), - Some(id_def @ IdDef::Func(_)) => Err(invalid(&format!( - "unsupported use of {} outside `OpFunctionCall`", - id_def.descr(&cx), - ))), - Some(id_def @ IdDef::SpvDebugString(s)) => { - if opcode == wk.OpExtInst { - // HACK(eddyb) intern `OpString`s as `Const`s on - // the fly, as it's a less likely usage than the - // `OpLine` one. - let ct = cx.intern(ConstDef { - attrs: AttrSet::default(), - ty: cx.intern(TypeKind::SpvStringLiteralForExtInst), - kind: ConstKind::SpvStringLiteralForExtInst(*s), - }); - Ok(LocalIdDef::Value(Value::Const(ct))) - } else { - Err(invalid(&format!( - "unsupported use of {} outside `OpSource`, \ + let lookup_global_or_local_id_for_data_or_control_inst_input = |id| match id_defs + .get(&id) + { + Some(&IdDef::Type(ty)) => { + Ok(LocalIdDef::Value(Value::Const(spv_type_operand_as_const(ty)))) + } + Some(&IdDef::Const(ct)) => Ok(LocalIdDef::Value(Value::Const(ct))), + Some(id_def @ IdDef::Func(_)) => Err(invalid(&format!( + "unsupported use of {} outside `OpFunctionCall`", + id_def.descr(&cx), + ))), + Some(id_def @ IdDef::SpvDebugString(s)) => { + if opcode == wk.OpExtInst { + // HACK(eddyb) intern `OpString`s as `Const`s on + // the fly, as it's a less likely usage than the + // `OpLine` one. + let ct = cx.intern(ConstDef { + attrs: AttrSet::default(), + ty: cx.intern(TypeKind::SpvStringLiteralForExtInst), + kind: ConstKind::SpvStringLiteralForExtInst(*s), + }); + Ok(LocalIdDef::Value(Value::Const(ct))) + } else { + Err(invalid(&format!( + "unsupported use of {} outside `OpSource`, \ `OpLine`, or `OpExtInst`", - id_def.descr(&cx), - ))) - } + id_def.descr(&cx), + ))) } - Some(id_def @ IdDef::SpvExtInstImport(_)) => Err(invalid(&format!( - "unsupported use of {} outside `OpExtInst`", - id_def.descr(&cx), - ))), - None => local_id_defs + } + Some(id_def @ IdDef::SpvExtInstImport(_)) => Err(invalid(&format!( + "unsupported use of {} outside `OpExtInst`", + id_def.descr(&cx), + ))), + None | Some(IdDef::PtrToGlobalVarForwardRef(_) | IdDef::FuncForwardRef(_)) => { + local_id_defs .get(&id) .copied() - .ok_or_else(|| invalid(&format!("undefined ID %{id}",))), - }; + .ok_or_else(|| invalid(&format!("undefined ID %{id}",))) + } + }; if opcode == wk.OpFunctionParameter { if current_block.is_some() { @@ -1221,13 +1491,12 @@ impl Module { details, // HACK(eddyb) reuse `shadowed_local_id_defs` storage. - shadowed_local_id_defs: current_block - .take() - .map(|CurrentBlock { mut shadowed_local_id_defs, .. }| { + shadowed_local_id_defs: current_block.take().map_or_default( + |CurrentBlock { mut shadowed_local_id_defs, .. }| { shadowed_local_id_defs.clear(); shadowed_local_id_defs - }) - .unwrap_or_default(), + }, + ), }); continue; } diff --git a/src/spv/mod.rs b/src/spv/mod.rs index bd9e7f50..a2d58f09 100644 --- a/src/spv/mod.rs +++ b/src/spv/mod.rs @@ -148,16 +148,14 @@ pub fn encode_literal_string(s: &str) -> impl Iterator + '_ { let bytes = s.as_bytes(); - // FIXME(eddyb) replace with `array_chunks` once that is stabilized. - let full_words = bytes.chunks_exact(4).map(|w| <[u8; 4]>::try_from(w).unwrap()); + let (full_words, leftover_bytes) = bytes.as_chunks::<4>(); - let leftover_bytes = &bytes[full_words.len() * 4..]; let mut last_word = [0; 4]; last_word[..leftover_bytes.len()].copy_from_slice(leftover_bytes); let total_words = full_words.len() + 1; - full_words.chain(iter::once(last_word)).map(u32::from_le_bytes).enumerate().map( + full_words.iter().copied().chain(iter::once(last_word)).map(u32::from_le_bytes).enumerate().map( move |(i, word)| { let kind = wk.LiteralString; match (i, total_words) { diff --git a/src/spv/print.rs b/src/spv/print.rs index 1fc99dd6..29b51e93 100644 --- a/src/spv/print.rs +++ b/src/spv/print.rs @@ -77,6 +77,9 @@ impl TokensForOperand { // FIXME(eddyb) keep a `&'static spec::Spec` if that can even speed up anything. struct OperandPrinter, ID, IDS: Iterator> { + // FIXME(eddyb) use a field like this to interpret `Opcode`/`OperandKind`, too. + wk: &'static spv::spec::WellKnown, + /// Input immediate operands to print from (may be grouped e.g. into literals). imms: iter::Peekable, @@ -123,7 +126,41 @@ impl, ID, IDS: Iterator> OperandPrint let def = kind.def(); assert!(matches!(def, spec::OperandKindDef::Literal { .. })); - let literal_token = if kind == spec::Spec::get().well_known.LiteralString { + let literal_token = if kind == self.wk.LiteralSpecConstantOpInteger { + assert_eq!(words.len(), 1); + let (_, inner_name, inner_def) = match u16::try_from(first_word) + .ok() + .and_then(spec::Opcode::try_from_u16_with_name_and_def) + { + Some(opcode_name_and_def) => opcode_name_and_def, + None => { + self.out.tokens.push(Token::Error(format!( + "/* {first_word} not a valid `OpSpecConstantOp` opcode */" + ))); + return; + } + }; + + // FIXME(eddyb) deduplicate this with `enumerant_params`. + self.out.tokens.push(Token::EnumerandName(inner_name)); + + let mut first = true; + for (inner_mode, inner_name_and_kind) in inner_def.all_operands_with_names() { + if inner_mode == spec::OperandMode::Optional && self.is_exhausted() { + break; + } + + self.out.tokens.push(Token::Punctuation(if first { "(" } else { ", " })); + first = false; + + let (inner_name, inner_kind) = inner_name_and_kind.name_and_kind(); + self.operand(inner_name, inner_kind); + } + if !first { + self.out.tokens.push(Token::Punctuation(")")); + } + return; + } else if kind == self.wk.LiteralString { // FIXME(eddyb) deduplicate with `spv::extract_literal_string`. let bytes: SmallVec<[u8; 64]> = words .into_iter() @@ -213,8 +250,7 @@ impl, ID, IDS: Iterator> OperandPrint None => return emit_missing_error(self), }; - let (variant_name, variant_def) = - variants.get_named(word.try_into().unwrap()).unwrap(); + let (variant_name, variant_def) = variants.get_named(word).unwrap(); self.out.tokens.extend([ Token::OperandKindNamespacePrefix(name), Token::EnumerandName(variant_name), @@ -256,12 +292,16 @@ impl, ID, IDS: Iterator> OperandPrint } } -/// Print a single SPIR-V operand from only immediates, potentially composed of -/// an enumerand with parameters (which consumes more immediates). -pub fn operand_from_imms(imms: impl IntoIterator) -> TokensForOperand { +/// Print a single SPIR-V operand from `imms` and `ids`, described by `imms[0]`, +/// but which may consume more immediates/IDs (e.g. for enumerand parameters). +pub fn operand( + imms: impl IntoIterator, + ids: impl IntoIterator, +) -> TokensForOperand { let mut printer = OperandPrinter { + wk: &spec::Spec::get().well_known, imms: imms.into_iter().peekable(), - ids: iter::empty().peekable(), + ids: ids.into_iter().peekable(), out: TokensForOperand::default(), }; let &kind = match printer.imms.peek().unwrap() { @@ -270,6 +310,7 @@ pub fn operand_from_imms(imms: impl IntoIterator) -> TokensF }; printer.operand("", kind); assert!(printer.imms.next().is_none()); + assert!(printer.ids.next().is_none()); printer.out } @@ -282,6 +323,7 @@ pub fn inst_operands( ids: impl IntoIterator, ) -> impl Iterator> { OperandPrinter { + wk: &spec::Spec::get().well_known, imms: imms.into_iter().peekable(), ids: ids.into_iter().peekable(), out: TokensForOperand::default(), diff --git a/src/spv/read.rs b/src/spv/read.rs index 87c27738..8b8eb124 100644 --- a/src/spv/read.rs +++ b/src/spv/read.rs @@ -28,6 +28,9 @@ impl KnownIdDef { // FIXME(eddyb) keep a `&'static spec::Spec` if that can even speed up anything. struct InstParser<'a> { + // FIXME(eddyb) use a field like this to interpret `Opcode`/`OperandKind`, too. + wk: &'static spv::spec::WellKnown, + /// IDs defined so far in the module. known_ids: &'a FxHashMap, @@ -60,6 +63,9 @@ enum InstParseError { /// The type of a `LiteralContextDependentNumber` was not a supported type /// (one of either `OpTypeInt` or `OpTypeFloat`). UnsupportedContextSensitiveLiteralType { type_opcode: spec::Opcode }, + + /// Unsupported `OpSpecConstantOp` (`LiteralSpecConstantOpInteger`) opcode. + UnsupportedSpecConstantOpOpcode(u32), } impl InstParseError { @@ -94,6 +100,9 @@ impl InstParseError { Self::UnsupportedContextSensitiveLiteralType { type_opcode } => { format!("{} is not a supported literal type", type_opcode.name()).into() } + Self::UnsupportedSpecConstantOpOpcode(opcode) => { + format!("{opcode} is not a supported opcode (for `OpSpecConstantOp`)").into() + } } } } @@ -133,10 +142,8 @@ impl InstParser<'_> { spec::OperandKindDef::ValueEnum { variants } => { self.inst.imms.push(spv::Imm::Short(kind, word)); - let variant_def = u16::try_from(word) - .ok() - .and_then(|v| variants.get(v)) - .ok_or(Error::UnsupportedEnumerand(kind, word))?; + let variant_def = + variants.get(word).ok_or(Error::UnsupportedEnumerand(kind, word))?; self.enumerant_params(variant_def)?; } @@ -198,6 +205,22 @@ impl InstParser<'_> { } } + // HACK(eddyb) this isn't cleanly uniform because it's an odd special case. + if kind == self.wk.LiteralSpecConstantOpInteger { + // FIXME(eddyb) this partially duplicates the main instruction parsing. + let (_, _, inner_def) = u16::try_from(word) + .ok() + .and_then(spec::Opcode::try_from_u16_with_name_and_def) + .ok_or(Error::UnsupportedSpecConstantOpOpcode(word))?; + + for (inner_mode, inner_kind) in inner_def.all_operands() { + if inner_mode == spec::OperandMode::Optional && self.is_exhausted() { + break; + } + self.operand(inner_kind)?; + } + } + Ok(()) } @@ -324,6 +347,7 @@ impl Iterator for ModuleParser { } let parser = InstParser { + wk: &spec::Spec::get().well_known, known_ids: &self.known_ids, words: words[1..inst_len].iter().copied(), inst: spv::InstWithIds { diff --git a/src/spv/spec.rs b/src/spv/spec.rs index ef59ee6d..2e2539c3 100644 --- a/src/spv/spec.rs +++ b/src/spv/spec.rs @@ -103,9 +103,10 @@ def_well_known! { OpModuleProcessed, OpDecorate, - OpMemberDecorate, OpDecorateId, OpDecorateString, + OpMemberDecorate, + OpMemberDecorateIdEXT, OpMemberDecorateString, // Deprecated in favor of `OpDecorate`/`OpMemberDecorate`. @@ -137,6 +138,7 @@ def_well_known! { OpConstantTrue, OpConstant, OpUndef, + OpConstantFunctionPointerINTEL, OpVariable, @@ -183,6 +185,7 @@ def_well_known! { LiteralExtInstInteger, LiteralString, LiteralContextDependentNumber, + LiteralSpecConstantOpInteger, ], // FIXME(eddyb) find a way to namespace these to avoid conflicts. addressing_model: u32 = [ @@ -200,6 +203,8 @@ def_well_known! { HitAttributeKHR, RayPayloadKHR, CallableDataKHR, + + CodeSectionINTEL, ], decoration: u32 = [ LinkageAttributes, @@ -268,7 +273,7 @@ pub struct InstructionDef { pub has_result_id: bool, pub req_operands: ArrayVec, - pub opt_operands: ArrayVec, + pub opt_operands: ArrayVec, pub rest_operands: Option, } @@ -372,7 +377,7 @@ impl OperandKind { } // HACK(eddyb) only needed because there are more than 256 unique operand names, -// but less than 64 `OperandKind`s, so we can split 16 kind:name bits as 6:10. +// but less than 128 `OperandKind`s, so we can split 16 kind:name bits as 7:9. #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct PackedOperandNameAndKind(u16); @@ -393,14 +398,18 @@ impl PackedOperandNameAndKind { #[inline] fn pack(name_idx: usize, kind: OperandKind) -> Self { - let packed = Self(((name_idx as u16) << 6) | (kind.0 as u16)); - assert_eq!(packed.unpack(), (name_idx, kind)); + let packed = Self(((name_idx as u16) << 7) | (kind.0 as u16)); + assert!( + packed.unpack() == (name_idx, kind), + "cannot pack ({name_idx}, {}) in `u16`", + kind.0 + ); packed } #[inline] fn unpack(self) -> (usize, OperandKind) { - ((self.0 >> 6) as usize, OperandKind((self.0 & ((1 << 6) - 1)) as u8)) + ((self.0 >> 7) as usize, OperandKind((self.0 & ((1 << 7) - 1)) as u8)) } /// Unpack this `PackedOperandNameAndKind` into just its `OperandKind`. @@ -424,7 +433,7 @@ pub enum OperandKindDef { }, ValueEnum { - variants: indexed::NamedIdxMap, + variants: indexed::NamedIdxMap, }, Id, @@ -515,18 +524,25 @@ fn sanitize_operand_name<'a>(name: &Option>) -> &'a str { name.as_ref() .and_then(|name| match name { &raw::CowStr::Borrowed(s) => { - s.strip_prefix('\'')?.strip_suffix('\'').filter(|s| { - // HACK(eddyb) it's pretty bad that SPIR-V uses spaces - // in operand names, but by constraining the rest of - // the character set (to be identifier-like), we get - // to remove spaces (to get `FooBar`), or even replace - // them with `_` (to get `Foo_Bar` or even `foo_bar`). - s.starts_with(|c: char| c.is_ascii_alphabetic()) - && s.chars().all(|c| c.is_ascii_alphanumeric() || c == ' ') - }) + let s = if s.ends_with('\'') { + // HACK(eddyb) work around a mistake in `OpAbortKHR`. + assert_eq!(s, "Message'"); + s.strip_suffix('\'').unwrap() + } else { + s + }; + + // HACK(eddyb) it's pretty bad that SPIR-V uses spaces + // in operand names, but by constraining the rest of + // the character set (to be identifier-like), we get + // to remove spaces (to get `FooBar`), or even replace + // them with `_` (to get `Foo_Bar` or even `foo_bar`). + (s.starts_with(|c: char| c.is_ascii_alphabetic()) + && s.chars().all(|c| c.is_ascii_alphanumeric() || c == ' ')) + .then_some(s) } raw::CowStr::Owned(s) => { - assert!(s.contains("', +\n'"), "unexpected non-zero-copy {s:?}"); + assert!(s.contains(", +\n"), "unexpected non-zero-copy {s:?}"); None } }) @@ -620,23 +636,6 @@ impl Spec { /// Implementation detail of [`Spec::get`], indexes the raw data to produce a [`Spec`]. fn from_raw(raw_core_grammar: raw::CoreGrammar<'static>) -> Self { - /// Helper for picking a name when the same index has multiple names. - fn preferred_name_between_dups<'a>(a: &'a str, b: &'a str) -> &'a str { - // Prefer standard / Khronos extensions over vendor extensions. - let is_khr_and_vnd = |khr: &str, vnd: &str| { - let base = khr.trim_end_matches("KHR"); - vnd.starts_with(base) && vnd.len() > base.len() - }; - if is_khr_and_vnd(a, b) { - a - } else if is_khr_and_vnd(b, a) { - b - } else { - // Worst case, use the first in alphabetical order. - a.min(b) - } - } - // HACK(eddyb) ad-hoc interning, to reduce the cost of tracking operand names // down to a single extra byte per operand (see `PackedOperandNameAndKind`). let mut operand_names = FxIndexSet::default(); @@ -702,12 +701,7 @@ impl Spec { if e.value == 0 { assert!(e.parameters.is_empty()); - empty_name = Some(match empty_name { - None => new_name, - Some(prev_name) => { - preferred_name_between_dups(prev_name, new_name) - } - }); + assert!(empty_name.replace(new_name).is_none()); continue; } @@ -721,27 +715,8 @@ impl Spec { if i >= bits.len() { bits.resize_with(i + 1, || None); } - let slot = &mut bits[i]; - - *slot = Some(match slot.take() { - None => (new_name, new_enumerant), - Some((prev_name, prev_enumerant)) => { - // Only allow aliases that do not meaningfully differ. - assert!( - prev_enumerant == new_enumerant, - "{} bits {} and {} share a bit index \ - but differ in definition", - o.kind, - prev_name, - new_name, - ); - - ( - preferred_name_between_dups(prev_name, new_name), - new_enumerant, - ) - } - }); + + assert!(bits[i].replace((new_name, new_enumerant)).is_none()); } // FIXME(eddyb) automate this in `indexed::NamedIdxMap`. @@ -762,29 +737,16 @@ impl Spec { let enumerants = o.enumerants.as_ref().unwrap(); let variants = indexed::KhrSegmentedVec::from_in_order_iter( - enumerants.iter().map(|e| { - (e.value.try_into().unwrap(), (e.enumerant, enumerant_from_raw(e))) - }), - // `merge_duplicates` closure: - |(prev_name, prev_enumerant), (new_name, new_enumerant)| { - // Only allow aliases that do not meaningfully differ. - assert!( - prev_enumerant == new_enumerant, - "{} variants {} and {} share a value but differ in definition", - o.kind, - prev_name, - new_name, - ); - - (preferred_name_between_dups(prev_name, new_name), new_enumerant) - }, + enumerants + .iter() + .map(|e| (e.value, (e.enumerant, enumerant_from_raw(e)))), ); // FIXME(eddyb) automate this in `indexed::NamedIdxMap`. let variants = indexed::NamedIdxMap { idx_by_name: enumerants .iter() - .map(|e| (e.enumerant, e.value.try_into().unwrap())) + .map(|e| (e.enumerant, e.value)) .collect(), storage: variants, }; @@ -984,18 +946,8 @@ impl Spec { assert!(def.has_result_id); } - (inst.opcode, (inst.opname, def)) + (inst.opcode.into(), (inst.opname, def)) }), - // `merge_duplicates` closure: - |(prev_name, prev_def), (new_name, new_def)| { - // Only allow aliases that do not meaningfully differ. - assert!( - prev_def == new_def, - "instructions {prev_name} and {new_name} share an opcode but differ in definition", - ); - - (preferred_name_between_dups(prev_name, new_name), new_def) - }, ); // FIXME(eddyb) automate this in `indexed::NamedIdxMap`. @@ -1031,10 +983,10 @@ impl Spec { let well_known = WellKnown::lookup_with(PerWellKnownGroup { opcode: |name| instructions.lookup(name).unwrap(), operand_kind: |name| operand_kinds.lookup(name).unwrap(), - addressing_model: |name| addressing_models.lookup(name).unwrap().into(), - storage_class: |name| storage_classes.lookup(name).unwrap().into(), - decoration: |name| decorations.lookup(name).unwrap().into(), - linkage_type: |name| linkage_types.lookup(name).unwrap().into(), + addressing_model: |name| addressing_models.lookup(name).unwrap(), + storage_class: |name| storage_classes.lookup(name).unwrap(), + decoration: |name| decorations.lookup(name).unwrap(), + linkage_type: |name| linkage_types.lookup(name).unwrap(), }); Self { @@ -1080,8 +1032,8 @@ pub mod raw { #[serde(borrow)] pub copyright: Option>>, - pub version: Option, - pub revision: u8, + pub version: Option, + pub revision: u32, pub instructions: Vec>, #[serde(default)] @@ -1105,6 +1057,16 @@ pub mod raw { #[serde(default)] pub operands: Vec>, + // FIXME(eddyb) the fields below this point are common between this and + // `OperandKindEnumerant` (almost as if "Opcode" were an operand kind), + // even `(opname, opcode, operands)` fits `(enumerant, value, parameters)` + // (except those field names differ), but can't be deduplicated due to + // `#[serde(flatten)]` not supporting `#[serde(deny_unknown_fields)]`. + #[serde(default)] + pub aliases: SmallVec<[&'a str; 1]>, + + // FIXME(eddyb) expose this information in some efficient form, so that + // it may be used in e.g. validation. #[serde(default)] pub extensions: SmallVec<[&'a str; 1]>, #[serde(default)] @@ -1112,6 +1074,8 @@ pub mod raw { // HACK(eddyb) some `extinst.*.json` use this form. pub capability: Option<&'a str>, + #[serde(default)] + pub provisional: bool, pub version: Option<&'a str>, #[serde(rename = "lastVersion")] pub last_version: Option<&'a str>, @@ -1168,11 +1132,23 @@ pub mod raw { #[serde(default)] pub parameters: Vec>, + // FIXME(eddyb) the fields below this point are common between this and + // `Instruction` (almost as if "Opcode" were an operand kind), + // even `(opname, opcode, operands)` fits `(enumerant, value, parameters)` + // (except those field names differ), but can't be deduplicated due to + // `#[serde(flatten)]` not supporting `#[serde(deny_unknown_fields)]`. + #[serde(default)] + pub aliases: SmallVec<[&'a str; 1]>, + + // FIXME(eddyb) expose this information in some efficient form, so that + // it may be used in e.g. validation. #[serde(default)] pub extensions: SmallVec<[&'a str; 1]>, #[serde(default)] pub capabilities: SmallVec<[&'a str; 1]>, + #[serde(default)] + pub provisional: bool, pub version: Option<&'a str>, #[serde(rename = "lastVersion")] pub last_version: Option<&'a str>, @@ -1252,6 +1228,7 @@ pub mod raw { pub mod indexed { use rustc_hash::FxHashMap; use smallvec::SmallVec; + use std::collections::BTreeMap; pub trait StorageShape { type Storage; @@ -1268,6 +1245,13 @@ pub mod indexed { } } + impl FlatIdx for u32 { + fn to_usize(self) -> usize { + // HACK(eddyb) this should cost nothing on 32-bit and 64-bit hosts. + self.try_into().unwrap() + } + } + /// Flat array ([`Vec`]) storage, likely used with compact indices. pub enum Flat {} @@ -1311,6 +1295,14 @@ pub mod indexed { /// For example, if an index `i >= 4096` is present, its value can be /// found at `flattened[block_starts[(i - 4096) / 64] + (i % 64)]`. block_starts: SmallVec<[u16; 8]>, + + // HACK(eddyb) all indices used to fit in `u16` (and have decently dense + // `64`-sized/aligned block distribution above 4096), but the operand kind + // `ComponentType` copied Vulkan's `enum` convention for extensions, + // ending up with enumerands like `1000491000` (for extension 491), + // so this map holds all such stragglers, however few, and is only used + // for indices that do not fit in `u16` (which is cheap to test for). + outside_16bit_range: BTreeMap, } impl KhrSegmentedVec { @@ -1340,10 +1332,14 @@ pub mod indexed { } /// Add a new value, with an index greater than all previous indices. - /// - /// An exception is made for duplicates, which have to be handled by the - /// `merge_duplicates` closure, instead of being outright disallowed. - fn insert_in_order(&mut self, idx: u16, value: T, merge_duplicates: impl Fn(T, T) -> T) { + fn insert_in_order(&mut self, idx: u32, value: T) { + let Ok(idx) = u16::try_from(idx) else { + // HACK(eddyb) special-case the rare cases that don't follow the + // `64`-sized/aligned block pattern, to keep everything else fast. + assert!(self.outside_16bit_range.insert(idx, value).is_none()); + return; + }; + let last_idx_plus_one = self.block_starts.len().checked_sub(1).map_or( self.flattened.len(), |last_block_idx| { @@ -1351,14 +1347,12 @@ pub mod indexed { + (self.flattened.len() - usize::from(self.block_starts[last_block_idx])) }, ); - if let Some(last_idx) = last_idx_plus_one.checked_sub(1) { - // HACK(eddyb) the condition being `<` instead of `<=` allows - // for special handling of duplicates (via `merge_duplicates`). - if usize::from(idx) < last_idx { - panic!( - "KhrSegmentedVec::insert_in_order: out of order indices ({idx} after {last_idx})", - ); - } + if let Some(last_idx) = last_idx_plus_one.checked_sub(1) + && usize::from(idx) <= last_idx + { + panic!( + "KhrSegmentedVec::insert_in_order: out of order indices ({idx} after {last_idx})", + ); } // Reserve new blocks if needed (so `idx_to_segmented` can't fail). @@ -1380,22 +1374,11 @@ pub mod indexed { if needed_slots > self.flattened.len() { self.flattened.resize_with(needed_slots, || None); } - let slot = &mut self.flattened[slot_idx]; - if let Some(prev) = slot.take() { - *slot = Some(merge_duplicates(prev, value)); - } else { - *slot = Some(value); - } + assert!(self.flattened[slot_idx].replace(value).is_none()); } /// Construct a [`KhrSegmentedVec`] out of an iterator with ordered indices. - /// - /// An exception is made for duplicates, which have to be handled by the - /// `merge_duplicates` closure, instead of being outright disallowed. - pub fn from_in_order_iter( - it: impl IntoIterator, - merge_duplicates: impl Fn(T, T) -> T, - ) -> Self { + pub fn from_in_order_iter(it: impl IntoIterator) -> Self { let iter = it.into_iter(); let mut this = Self { @@ -1403,12 +1386,13 @@ pub mod indexed { iter.size_hint().0.checked_next_power_of_two().unwrap_or(0), ), block_starts: SmallVec::new(), + outside_16bit_range: BTreeMap::new(), }; for (idx, value) in iter { // FIXME(eddyb) the check at the start of `insert_in_order` may // be less efficient than if we checked the ordering here instead. - this.insert_in_order(idx, value, &merge_duplicates); + this.insert_in_order(idx, value); } this @@ -1418,8 +1402,15 @@ pub mod indexed { impl StorageShape for KhrSegmented { type Storage = KhrSegmentedVec; fn get_by_idx(storage: &Self::Storage, idx: I) -> Option<&T> { - let (seg_range, intra_seg_idx) = - storage.idx_to_segmented(idx.to_usize().try_into().ok()?)?; + let idx = u32::try_from(idx.to_usize()).ok()?; + + let Ok(idx) = u16::try_from(idx) else { + // HACK(eddyb) special-case the rare cases that don't follow the + // `64`-sized/aligned block pattern, to keep everything else fast. + return storage.outside_16bit_range.get(&idx); + }; + + let (seg_range, intra_seg_idx) = storage.idx_to_segmented(idx)?; storage.flattened.get(seg_range)?.get(intra_seg_idx)?.as_ref() } diff --git a/src/spv/write.rs b/src/spv/write.rs index 38c96d7f..760823a2 100644 --- a/src/spv/write.rs +++ b/src/spv/write.rs @@ -7,6 +7,9 @@ use std::{fs, io, iter, slice}; // FIXME(eddyb) keep a `&'static spec::Spec` if that can even speed up anything. struct OperandEmitter<'a> { + // FIXME(eddyb) use a field like this to interpret `Opcode`/`OperandKind`, too. + wk: &'static spv::spec::WellKnown, + /// Input immediate operands of an instruction. imms: iter::Copied>, @@ -32,6 +35,9 @@ enum OperandEmitError { /// Unsupported enumerand value. UnsupportedEnumerand(spec::OperandKind, u32), + + /// Unsupported `OpSpecConstantOp` (`LiteralSpecConstantOpInteger`) opcode. + UnsupportedSpecConstantOpOpcode(u32), } impl OperandEmitError { @@ -60,6 +66,9 @@ impl OperandEmitError { _ => unreachable!(), } } + Self::UnsupportedSpecConstantOpOpcode(opcode) => { + format!("{opcode} is not a supported opcode (for `OpSpecConstantOp`)").into() + } } } } @@ -109,10 +118,8 @@ impl OperandEmitter<'_> { let word = get_enum_word()?; self.out.push(word); - let variant_def = u16::try_from(word) - .ok() - .and_then(|v| variants.get(v)) - .ok_or(Error::UnsupportedEnumerand(kind, word))?; + let variant_def = + variants.get(word).ok_or(Error::UnsupportedEnumerand(kind, word))?; self.enumerant_params(variant_def)?; } spec::OperandKindDef::Id => { @@ -140,6 +147,23 @@ impl OperandEmitter<'_> { } } + // HACK(eddyb) this isn't cleanly uniform because it's an odd special case. + if kind == self.wk.LiteralSpecConstantOpInteger { + // FIXME(eddyb) this partially duplicates the main instruction emission. + let &word = self.out.last().unwrap(); + let (_, _, inner_def) = u16::try_from(word) + .ok() + .and_then(spec::Opcode::try_from_u16_with_name_and_def) + .ok_or(Error::UnsupportedSpecConstantOpOpcode(word))?; + + for (inner_mode, inner_kind) in inner_def.all_operands() { + if inner_mode == spec::OperandMode::Optional && self.is_exhausted() { + break; + } + self.operand(inner_kind)?; + } + } + Ok(()) } @@ -221,6 +245,7 @@ impl ModuleEmitter { ); OperandEmitter { + wk: &spec::Spec::get().well_known, imms: inst.imms.iter().copied(), ids: inst.ids.iter().copied(), out: &mut self.words, diff --git a/src/transform.rs b/src/transform.rs index 74670d34..475d8c2c 100644 --- a/src/transform.rs +++ b/src/transform.rs @@ -1,7 +1,8 @@ //! Mutable IR traversal. use crate::func_at::FuncAtMut; -use crate::qptr::{self, QPtrAttr, QPtrMemUsage, QPtrMemUsageKind, QPtrOp, QPtrUsage}; +use crate::mem::{DataHapp, DataHappKind, MemAccesses, MemAttr, MemOp}; +use crate::qptr::{QPtrAttr, QPtrOp}; use crate::{ AddrSpace, Attr, AttrSet, AttrSetDef, Const, ConstDef, ConstKind, DataInst, DataInstDef, DataInstKind, DbgSrcLoc, DeclDef, EntityListIter, ExportKey, Exportee, Func, FuncDecl, @@ -316,9 +317,7 @@ impl InnerTransform for AttrSetDef { impl InnerTransform for Attr { fn inner_transform_with(&self, transformer: &mut impl Transformer) -> Transformed { match self { - Attr::Diagnostics(_) | Attr::SpvAnnotation(_) | Attr::SpvBitflagsOperand(_) => { - Transformed::Unchanged - } + Attr::Diagnostics(_) | Attr::SpvBitflagsOperand(_) => Transformed::Unchanged, &Attr::DbgSrcLoc(OrdAssertEq(DbgSrcLoc { file_path, @@ -343,13 +342,31 @@ impl InnerTransform for Attr { }))) } - Attr::QPtr(attr) => transform!({ + Attr::Mem(attr) => transform!({ attr -> match attr { - &QPtrAttr::ToSpvPtrInput { input_idx, pointee } => transform!({ + MemAttr::Accesses(OrdAssertEq(accesses)) => transform!({ + accesses -> match accesses { + &MemAccesses::Handles(crate::mem::shapes::Handle::Opaque(ty)) => transform!({ + ty -> transformer.transform_type_use(ty), + } => MemAccesses::Handles(crate::mem::shapes::Handle::Opaque(ty))), + MemAccesses::Handles(crate::mem::shapes::Handle::Buffer(addr_space, data_happ)) => transform!({ + data_happ -> data_happ.inner_transform_with(transformer), + } => MemAccesses::Handles(crate::mem::shapes::Handle::Buffer(*addr_space, data_happ))), + MemAccesses::Data(happ) => transform!({ + happ -> happ.inner_transform_with(transformer), + } => MemAccesses::Data(happ)), + } + } => MemAttr::Accesses(OrdAssertEq(accesses))), + } + } => Attr::Mem(attr)), + + Attr::QPtr(attr) => transform!({ + attr -> match *attr { + QPtrAttr::ToSpvPtrInput { input_idx, pointee } => transform!({ pointee -> transformer.transform_type_use(pointee.0).map(OrdAssertEq), } => QPtrAttr::ToSpvPtrInput { input_idx, pointee }), - &QPtrAttr::FromSpvPtrOutput { + QPtrAttr::FromSpvPtrOutput { addr_space, pointee, } => transform!({ @@ -358,22 +375,30 @@ impl InnerTransform for Attr { addr_space, pointee, }), - - QPtrAttr::Usage(OrdAssertEq(usage)) => transform!({ - usage -> match usage { - &QPtrUsage::Handles(qptr::shapes::Handle::Opaque(ty)) => transform!({ - ty -> transformer.transform_type_use(ty), - } => QPtrUsage::Handles(qptr::shapes::Handle::Opaque(ty))), - QPtrUsage::Handles(qptr::shapes::Handle::Buffer(addr_space, data_usage)) => transform!({ - data_usage -> data_usage.inner_transform_with(transformer), - } => QPtrUsage::Handles(qptr::shapes::Handle::Buffer(*addr_space, data_usage))), - QPtrUsage::Memory(usage) => transform!({ - usage -> usage.inner_transform_with(transformer), - } => QPtrUsage::Memory(usage)), - } - } => QPtrAttr::Usage(OrdAssertEq(usage))), } } => Attr::QPtr(attr)), + + Attr::SpvAnnotation { spv_inst, per_instance_const_inputs } => { + // FIXME(eddyb) this should be replaced with an impl of `InnerTransform` + // for `Option` or some other helper, to avoid "manual transpose". + transform!({ + per_instance_const_inputs -> per_instance_const_inputs + .as_ref() + .map(|OrdAssertEq(instances)| { + Transformed::map_iter(instances.iter(), |const_inputs| { + Transformed::map_iter(const_inputs.iter(), |&ct| { + transformer.transform_const_use(ct) + }) + .map(|new_iter| new_iter.collect()) + }) + .map(|new_iter| OrdAssertEq(Rc::new(new_iter.collect()))) + }) + .map_or(Transformed::Unchanged, |t| t.map(Some)), + } => Attr::SpvAnnotation { + spv_inst: spv_inst.clone(), + per_instance_const_inputs, + }) + } } } } @@ -385,7 +410,7 @@ impl InnerTransform for Rc { } } -impl InnerTransform for QPtrMemUsage { +impl InnerTransform for DataHapp { fn inner_transform_with(&self, transformer: &mut impl Transformer) -> Transformed { let Self { max_size, kind } = self; @@ -398,28 +423,28 @@ impl InnerTransform for QPtrMemUsage { } } -impl InnerTransform for QPtrMemUsageKind { +impl InnerTransform for DataHappKind { fn inner_transform_with(&self, transformer: &mut impl Transformer) -> Transformed { match self { - Self::Unused => Transformed::Unchanged, + Self::Dead => Transformed::Unchanged, &Self::StrictlyTyped(ty) => transform!({ ty -> transformer.transform_type_use(ty), } => Self::StrictlyTyped(ty)), - &Self::DirectAccess(ty) => transform!({ + &Self::Direct(ty) => transform!({ ty -> transformer.transform_type_use(ty), - } => Self::DirectAccess(ty)), - Self::OffsetBase(entries) => transform!({ - entries -> Transformed::map_iter(entries.values(), |sub_usage| { - sub_usage.inner_transform_with(transformer) + } => Self::Direct(ty)), + Self::Disjoint(entries) => transform!({ + entries -> Transformed::map_iter(entries.values(), |sub_happ| { + sub_happ.inner_transform_with(transformer) }).map(|new_iter| { // HACK(eddyb) this is a bit inefficient but `Transformed::map_iter` // limits us here in how it handles the whole `Clone` thing. entries.keys().copied().zip(new_iter).collect() }).map(Rc::new) - } => Self::OffsetBase(entries)), - Self::DynOffsetBase { element, stride } => transform!({ + } => Self::Disjoint(entries)), + Self::Repeated { element, stride } => transform!({ element -> element.inner_transform_with(transformer), - } => Self::DynOffsetBase { element, stride: *stride }), + } => Self::Repeated { element, stride: *stride }), } } } @@ -431,7 +456,9 @@ impl InnerTransform for TypeDef { transform!({ attrs -> transformer.transform_attr_set_use(*attrs), kind -> match kind { - TypeKind::QPtr | TypeKind::SpvStringLiteralForExtInst => Transformed::Unchanged, + TypeKind::QPtr + | TypeKind::SpvTypeOperand + | TypeKind::SpvStringLiteralForExtInst => Transformed::Unchanged, TypeKind::SpvInst { spv_inst, type_and_const_inputs } => Transformed::map_iter( type_and_const_inputs.iter(), @@ -468,6 +495,10 @@ impl InnerTransform for ConstDef { gv -> transformer.transform_global_var_use(*gv), } => ConstKind::PtrToGlobalVar(gv)), + ConstKind::PtrToFunc(func) => transform!({ + func -> transformer.transform_func_use(*func), + } => ConstKind::PtrToFunc(func)), + ConstKind::SpvInst { spv_inst_and_const_inputs } => { let (spv_inst, const_inputs) = &**spv_inst_and_const_inputs; Transformed::map_iter( @@ -477,6 +508,11 @@ impl InnerTransform for ConstDef { spv_inst_and_const_inputs: Rc::new((spv_inst.clone(), new_iter.collect())), }) } + + ConstKind::SpvTypeOperand(ty) => transform!({ + ty -> transformer.transform_type_use(*ty), + } => ConstKind::SpvTypeOperand(ty)), + ConstKind::SpvStringLiteralForExtInst(_) => Transformed::Unchanged }, } => Self { @@ -506,11 +542,11 @@ impl InnerInPlaceTransform for GlobalVarDecl { transformer.transform_type_use(*type_of_ptr_to).apply_to(type_of_ptr_to); if let Some(shape) = shape { match shape { - qptr::shapes::GlobalVarShape::TypedInterface(ty) => { + crate::mem::shapes::GlobalVarShape::TypedInterface(ty) => { transformer.transform_type_use(*ty).apply_to(ty); } - qptr::shapes::GlobalVarShape::Handles { .. } - | qptr::shapes::GlobalVarShape::UntypedData(_) => {} + crate::mem::shapes::GlobalVarShape::Handles { .. } + | crate::mem::shapes::GlobalVarShape::UntypedData(_) => {} } } match addr_space { @@ -716,15 +752,15 @@ impl InnerInPlaceTransform for DataInstKind { fn inner_in_place_transform_with(&mut self, transformer: &mut impl Transformer) { match self { DataInstKind::FuncCall(func) => transformer.transform_func_use(*func).apply_to(func), + DataInstKind::Mem(op) => match op { + MemOp::FuncLocalVar(_) | MemOp::Load | MemOp::Store => {} + }, DataInstKind::QPtr(op) => match op { - QPtrOp::FuncLocalVar(_) - | QPtrOp::HandleArrayIndex + QPtrOp::HandleArrayIndex | QPtrOp::BufferData | QPtrOp::BufferDynLen { .. } | QPtrOp::Offset(_) - | QPtrOp::DynOffset { .. } - | QPtrOp::Load - | QPtrOp::Store => {} + | QPtrOp::DynOffset { .. } => {} }, DataInstKind::SpvInst(_) | DataInstKind::SpvExtInst { .. } => {} } diff --git a/src/visit.rs b/src/visit.rs index 1829c466..5b72a024 100644 --- a/src/visit.rs +++ b/src/visit.rs @@ -1,7 +1,8 @@ //! Immutable IR traversal. use crate::func_at::FuncAt; -use crate::qptr::{self, QPtrAttr, QPtrMemUsage, QPtrMemUsageKind, QPtrOp, QPtrUsage}; +use crate::mem::{DataHapp, DataHappKind, MemAccesses, MemAttr, MemOp}; +use crate::qptr::{QPtrAttr, QPtrOp}; use crate::{ AddrSpace, Attr, AttrSet, AttrSetDef, Const, ConstDef, ConstKind, DataInstDef, DataInstKind, DbgSrcLoc, DeclDef, DiagMsgPart, EntityListIter, ExportKey, Exportee, Func, FuncDecl, @@ -232,7 +233,7 @@ impl InnerVisit for AttrSetDef { impl InnerVisit for Attr { fn inner_visit_with<'a>(&'a self, visitor: &mut impl Visitor<'a>) { match self { - Attr::Diagnostics(_) | Attr::SpvAnnotation(_) | Attr::SpvBitflagsOperand(_) => {} + Attr::Diagnostics(_) | Attr::SpvBitflagsOperand(_) => {} &Attr::DbgSrcLoc(OrdAssertEq(DbgSrcLoc { file_path: _, @@ -245,14 +246,26 @@ impl InnerVisit for Attr { } } + Attr::Mem(attr) => match attr { + MemAttr::Accesses(accesses) => accesses.0.inner_visit_with(visitor), + }, + Attr::QPtr(attr) => match attr { QPtrAttr::ToSpvPtrInput { input_idx: _, pointee } | QPtrAttr::FromSpvPtrOutput { addr_space: _, pointee } => { visitor.visit_type_use(pointee.0); } - - QPtrAttr::Usage(usage) => usage.0.inner_visit_with(visitor), }, + + Attr::SpvAnnotation { spv_inst: _, per_instance_const_inputs } => { + if let Some(per_instance_const_inputs) = per_instance_const_inputs { + for const_inputs in &per_instance_const_inputs.0[..] { + for &ct in const_inputs { + visitor.visit_const_use(ct); + } + } + } + } } } } @@ -267,46 +280,46 @@ impl InnerVisit for Vec { &DiagMsgPart::Attrs(attrs) => visitor.visit_attr_set_use(attrs), &DiagMsgPart::Type(ty) => visitor.visit_type_use(ty), &DiagMsgPart::Const(ct) => visitor.visit_const_use(ct), - DiagMsgPart::QPtrUsage(usage) => usage.inner_visit_with(visitor), + DiagMsgPart::MemAccesses(accesses) => accesses.inner_visit_with(visitor), } } } } -impl InnerVisit for QPtrUsage { +impl InnerVisit for MemAccesses { fn inner_visit_with<'a>(&'a self, visitor: &mut impl Visitor<'a>) { match self { - &QPtrUsage::Handles(qptr::shapes::Handle::Opaque(ty)) => { + &MemAccesses::Handles(crate::mem::shapes::Handle::Opaque(ty)) => { visitor.visit_type_use(ty); } - QPtrUsage::Handles(qptr::shapes::Handle::Buffer(_, data_usage)) => { - data_usage.inner_visit_with(visitor); + MemAccesses::Handles(crate::mem::shapes::Handle::Buffer(_, data_happ)) => { + data_happ.inner_visit_with(visitor); } - QPtrUsage::Memory(usage) => usage.inner_visit_with(visitor), + MemAccesses::Data(happ) => happ.inner_visit_with(visitor), } } } -impl InnerVisit for QPtrMemUsage { +impl InnerVisit for DataHapp { fn inner_visit_with<'a>(&'a self, visitor: &mut impl Visitor<'a>) { let Self { max_size: _, kind } = self; kind.inner_visit_with(visitor); } } -impl InnerVisit for QPtrMemUsageKind { +impl InnerVisit for DataHappKind { fn inner_visit_with<'a>(&'a self, visitor: &mut impl Visitor<'a>) { match self { - Self::Unused => {} - &Self::StrictlyTyped(ty) | &Self::DirectAccess(ty) => { + Self::Dead => {} + &Self::StrictlyTyped(ty) | &Self::Direct(ty) => { visitor.visit_type_use(ty); } - Self::OffsetBase(entries) => { - for sub_usage in entries.values() { - sub_usage.inner_visit_with(visitor); + Self::Disjoint(entries) => { + for sub_happ in entries.values() { + sub_happ.inner_visit_with(visitor); } } - Self::DynOffsetBase { element, stride: _ } => { + Self::Repeated { element, stride: _ } => { element.inner_visit_with(visitor); } } @@ -319,7 +332,7 @@ impl InnerVisit for TypeDef { visitor.visit_attr_set_use(*attrs); match kind { - TypeKind::QPtr | TypeKind::SpvStringLiteralForExtInst => {} + TypeKind::QPtr | TypeKind::SpvTypeOperand | TypeKind::SpvStringLiteralForExtInst => {} TypeKind::SpvInst { spv_inst: _, type_and_const_inputs } => { for &ty_or_ct in type_and_const_inputs { @@ -341,12 +354,16 @@ impl InnerVisit for ConstDef { visitor.visit_type_use(*ty); match kind { &ConstKind::PtrToGlobalVar(gv) => visitor.visit_global_var_use(gv), + &ConstKind::PtrToFunc(func) => visitor.visit_func_use(func), ConstKind::SpvInst { spv_inst_and_const_inputs } => { let (_spv_inst, const_inputs) = &**spv_inst_and_const_inputs; for &ct in const_inputs { visitor.visit_const_use(ct); } } + + ConstKind::SpvTypeOperand(ty) => visitor.visit_type_use(*ty), + ConstKind::SpvStringLiteralForExtInst(_) => {} } } @@ -369,9 +386,11 @@ impl InnerVisit for GlobalVarDecl { visitor.visit_type_use(*type_of_ptr_to); if let Some(shape) = shape { match shape { - qptr::shapes::GlobalVarShape::TypedInterface(ty) => visitor.visit_type_use(*ty), - qptr::shapes::GlobalVarShape::Handles { .. } - | qptr::shapes::GlobalVarShape::UntypedData(_) => {} + crate::mem::shapes::GlobalVarShape::TypedInterface(ty) => { + visitor.visit_type_use(*ty); + } + crate::mem::shapes::GlobalVarShape::Handles { .. } + | crate::mem::shapes::GlobalVarShape::UntypedData(_) => {} } } match addr_space { @@ -534,15 +553,15 @@ impl InnerVisit for DataInstKind { fn inner_visit_with<'a>(&'a self, visitor: &mut impl Visitor<'a>) { match self { &DataInstKind::FuncCall(func) => visitor.visit_func_use(func), + DataInstKind::Mem(op) => match *op { + MemOp::FuncLocalVar(_) | MemOp::Load | MemOp::Store => {} + }, DataInstKind::QPtr(op) => match *op { - QPtrOp::FuncLocalVar(_) - | QPtrOp::HandleArrayIndex + QPtrOp::HandleArrayIndex | QPtrOp::BufferData | QPtrOp::BufferDynLen { .. } | QPtrOp::Offset(_) - | QPtrOp::DynOffset { .. } - | QPtrOp::Load - | QPtrOp::Store => {} + | QPtrOp::DynOffset { .. } => {} }, DataInstKind::SpvInst(_) | DataInstKind::SpvExtInst { .. } => {} }