Implement module compaction.

Add a new Naga feature, `"compact"`, which adds a new function
`naga::compact::compact`, which removes unused expressions, types, and
constants from a `Module`.
This commit is contained in:
Jim Blandy authored and Teodor Tanasoaia committed 2023-09-20 18:46:33 +02:00
1 parent 0b7afb3943
commit 8b267218a4
77 files changed
+10199 -6305

No files matched your search

+70
View File
@@ -192,12 +192,31 @@ impl<T> Iterator for Range<T> {
}
impl<T> Range<T> {
/// Return a range enclosing handles `first` through `last`, inclusive.
pub fn new_from_bounds(first: Handle<T>, last: Handle<T>) -> Self {
Self {
inner: (first.index() as u32)..(last.index() as u32 + 1),
marker: Default::default(),
}
}
/// Return the first and last handles included in `self`.
///
/// If `self` is an empty range, there are no handles included, so
/// return `None`.
pub fn first_and_last(&self) -> Option<(Handle<T>, Handle<T>)> {
if self.inner.start < self.inner.end {
Some((
// `Range::new_from_bounds` expects a 1-based, start- and
// end-inclusive range, but `self.inner` is a zero-based,
// end-exclusive range.
Handle::new(Index::new(self.inner.start + 1).unwrap()),
Handle::new(Index::new(self.inner.end).unwrap()),
))
} else {
None
}
}
}
/// An arena holding some kind of component (e.g., type, constant,
@@ -382,6 +401,19 @@ impl<T> Arena<T> {
Ok(())
}
}
#[cfg(feature = "compact")]
pub(crate) fn retain_mut<P>(&mut self, mut predicate: P)
where
P: FnMut(Handle<T>, &mut T) -> bool,
{
let mut index = 0;
self.data.retain_mut(|elt| {
index += 1;
let handle = Handle::new(Index::new(index).unwrap());
predicate(handle, elt)
})
}
}
#[cfg(feature = "deserialize")]
@@ -544,6 +576,44 @@ impl<T> UniqueArena<T> {
Span::default()
}
}
#[cfg(feature = "compact")]
pub(crate) fn drain_all(&mut self) -> UniqueArenaDrain<T> {
UniqueArenaDrain {
inner_elts: self.set.drain(..),
#[cfg(feature = "span")]
inner_spans: self.span_info.drain(..),
index: Index::new(1).unwrap(),
}
}
}
#[cfg(feature = "compact")]
pub(crate) struct UniqueArenaDrain<'a, T> {
inner_elts: indexmap::set::Drain<'a, T>,
#[cfg(feature = "span")]
inner_spans: std::vec::Drain<'a, Span>,
index: Index,
}
#[cfg(feature = "compact")]
impl<'a, T> Iterator for UniqueArenaDrain<'a, T> {
type Item = (Handle<T>, T, Span);
fn next(&mut self) -> Option<Self::Item> {
match self.inner_elts.next() {
Some(elt) => {
let handle = Handle::new(self.index);
self.index = self.index.checked_add(1).unwrap();
#[cfg(feature = "span")]
let span = self.inner_spans.next().unwrap();
#[cfg(not(feature = "span"))]
let span = Span::default();
Some((handle, elt, span))
}
None => None,
}
}
}
impl<T: Eq + hash::Hash> UniqueArena<T> {
+395
View File
@@ -0,0 +1,395 @@
use super::{HandleMap, HandleSet, ModuleMap};
use crate::arena::{Arena, Handle, UniqueArena};
pub struct ExpressionTracer<'tracer> {
pub types: &'tracer UniqueArena<crate::Type>,
pub constants: &'tracer Arena<crate::Constant>,
/// The arena in which we are currently tracing expressions.
pub expressions: &'tracer Arena<crate::Expression>,
/// The used map for `types`.
pub types_used: &'tracer mut HandleSet<crate::Type>,
/// The used map for `constants`.
pub constants_used: &'tracer mut HandleSet<crate::Constant>,
/// The used set for `arena`.
///
/// This points to whatever arena holds the expressions we are
/// currently tracing: either a function's expression arena, or
/// the module's constant expression arena.
pub expressions_used: &'tracer mut HandleSet<crate::Expression>,
/// The constant expression arena and its used map, if we haven't
/// switched to tracing constant expressions yet.
pub const_expressions: Option<(
&'tracer Arena<crate::Expression>,
&'tracer mut HandleSet<crate::Expression>,
)>,
}
impl<'tracer> ExpressionTracer<'tracer> {
pub fn trace_expression(&mut self, expr: Handle<crate::Expression>) {
log::trace!(
"entering trace_expression of {}",
if self.const_expressions.is_some() {
"function expressions"
} else {
"const expressions"
}
);
let mut work_list = vec![expr];
while let Some(expr) = work_list.pop() {
// If we've already seen this expression, no need to trace further.
if !self.expressions_used.insert(expr) {
continue;
}
log::trace!("tracing new expression {:?}", expr);
use crate::Expression as Ex;
match self.expressions[expr] {
// Expressions that do not contain handles that need to be traced.
Ex::Literal(_)
| Ex::FunctionArgument(_)
| Ex::GlobalVariable(_)
| Ex::LocalVariable(_)
| Ex::CallResult(_)
| Ex::RayQueryProceedResult => {}
Ex::Constant(handle) => {
self.constants_used.insert(handle);
let constant = &self.constants[handle];
self.trace_type(constant.ty);
self.trace_const_expression(constant.init);
}
Ex::ZeroValue(ty) => self.trace_type(ty),
Ex::Compose { ty, ref components } => {
self.trace_type(ty);
work_list.extend(components);
}
Ex::Access { base, index } => work_list.extend([base, index]),
Ex::AccessIndex { base, index: _ } => work_list.push(base),
Ex::Splat { size: _, value } => work_list.push(value),
Ex::Swizzle {
size: _,
vector,
pattern: _,
} => work_list.push(vector),
Ex::Load { pointer } => work_list.push(pointer),
Ex::ImageSample {
image,
sampler,
gather: _,
coordinate,
array_index,
offset,
ref level,
depth_ref,
} => {
work_list.push(image);
work_list.push(sampler);
work_list.push(coordinate);
work_list.extend(array_index);
if let Some(offset) = offset {
self.trace_const_expression(offset);
}
use crate::SampleLevel as Sl;
match *level {
Sl::Auto | Sl::Zero => {}
Sl::Exact(expr) | Sl::Bias(expr) => work_list.push(expr),
Sl::Gradient { x, y } => work_list.extend([x, y]),
}
work_list.extend(depth_ref);
}
Ex::ImageLoad {
image,
coordinate,
array_index,
sample,
level,
} => {
work_list.push(image);
work_list.push(coordinate);
work_list.extend(array_index);
work_list.extend(sample);
work_list.extend(level);
}
Ex::ImageQuery { image, ref query } => {
work_list.push(image);
use crate::ImageQuery as Iq;
match *query {
Iq::Size { level } => work_list.extend(level),
Iq::NumLevels | Iq::NumLayers | Iq::NumSamples => {}
}
}
Ex::Unary { op: _, expr } => work_list.push(expr),
Ex::Binary { op: _, left, right } => work_list.extend([left, right]),
Ex::Select {
condition,
accept,
reject,
} => work_list.extend([condition, accept, reject]),
Ex::Derivative {
axis: _,
ctrl: _,
expr,
} => work_list.push(expr),
Ex::Relational { fun: _, argument } => work_list.push(argument),
Ex::Math {
fun: _,
arg,
arg1,
arg2,
arg3,
} => {
work_list.push(arg);
work_list.extend(arg1);
work_list.extend(arg2);
work_list.extend(arg3);
}
Ex::As {
expr,
kind: _,
convert: _,
} => work_list.push(expr),
Ex::AtomicResult { ty, comparison: _ } => self.trace_type(ty),
Ex::WorkGroupUniformLoadResult { ty } => self.trace_type(ty),
Ex::ArrayLength(expr) => work_list.push(expr),
Ex::RayQueryGetIntersection {
query,
committed: _,
} => work_list.push(query),
}
}
}
fn trace_type(&mut self, ty: Handle<crate::Type>) {
let mut types_used = super::types::TypeTracer {
types: self.types,
types_used: self.types_used,
};
types_used.trace_type(ty);
}
pub fn as_const_expression(&mut self) -> ExpressionTracer {
match self.const_expressions {
Some((ref mut exprs, ref mut exprs_used)) => ExpressionTracer {
expressions: exprs,
expressions_used: exprs_used,
types: self.types,
constants: self.constants,
types_used: self.types_used,
constants_used: self.constants_used,
const_expressions: None,
},
None => ExpressionTracer {
types: self.types,
constants: self.constants,
expressions: self.expressions,
types_used: self.types_used,
constants_used: self.constants_used,
expressions_used: self.expressions_used,
const_expressions: None,
},
}
}
fn trace_const_expression(&mut self, const_expr: Handle<crate::Expression>) {
self.as_const_expression().trace_expression(const_expr);
}
}
impl ModuleMap {
/// Fix up all handles in `expr`.
///
/// Use the expression handle remappings in `operand_map`, and all
/// other mappings from `self`.
pub fn adjust_expression(
&self,
expr: &mut crate::Expression,
operand_map: &HandleMap<crate::Expression>,
) {
let adjust = |expr: &mut Handle<crate::Expression>| {
operand_map.adjust(expr);
};
use crate::Expression as Ex;
match *expr {
// Expressions that do not contain handles that need to be adjusted.
Ex::Literal(_)
| Ex::FunctionArgument(_)
| Ex::GlobalVariable(_)
| Ex::LocalVariable(_)
| Ex::CallResult(_)
| Ex::RayQueryProceedResult => {}
// Expressions that contain handles that need to be adjusted.
Ex::Constant(ref mut constant) => self.constants.adjust(constant),
Ex::ZeroValue(ref mut ty) => self.types.adjust(ty),
Ex::Compose {
ref mut ty,
ref mut components,
} => {
self.types.adjust(ty);
for component in components {
adjust(component);
}
}
Ex::Access {
ref mut base,
ref mut index,
} => {
adjust(base);
adjust(index);
}
Ex::AccessIndex {
ref mut base,
index: _,
} => adjust(base),
Ex::Splat {
size: _,
ref mut value,
} => adjust(value),
Ex::Swizzle {
size: _,
ref mut vector,
pattern: _,
} => adjust(vector),
Ex::Load { ref mut pointer } => adjust(pointer),
Ex::ImageSample {
ref mut image,
ref mut sampler,
gather: _,
ref mut coordinate,
ref mut array_index,
ref mut offset,
ref mut level,
ref mut depth_ref,
} => {
adjust(image);
adjust(sampler);
adjust(coordinate);
operand_map.adjust_option(array_index);
// TEST: try adjusting this with plain operand_map
if let Some(ref mut offset) = *offset {
self.const_expressions.adjust(offset);
}
self.adjust_sample_level(level, operand_map);
operand_map.adjust_option(depth_ref);
}
Ex::ImageLoad {
ref mut image,
ref mut coordinate,
ref mut array_index,
ref mut sample,
ref mut level,
} => {
adjust(image);
adjust(coordinate);
operand_map.adjust_option(array_index);
operand_map.adjust_option(sample);
operand_map.adjust_option(level);
}
Ex::ImageQuery {
ref mut image,
ref mut query,
} => {
adjust(image);
self.adjust_image_query(query, operand_map);
}
Ex::Unary {
op: _,
ref mut expr,
} => adjust(expr),
Ex::Binary {
op: _,
ref mut left,
ref mut right,
} => {
adjust(left);
adjust(right);
}
Ex::Select {
ref mut condition,
ref mut accept,
ref mut reject,
} => {
adjust(condition);
adjust(accept);
adjust(reject);
}
Ex::Derivative {
axis: _,
ctrl: _,
ref mut expr,
} => adjust(expr),
Ex::Relational {
fun: _,
ref mut argument,
} => adjust(argument),
Ex::Math {
fun: _,
ref mut arg,
ref mut arg1,
ref mut arg2,
ref mut arg3,
} => {
adjust(arg);
operand_map.adjust_option(arg1);
operand_map.adjust_option(arg2);
operand_map.adjust_option(arg3);
}
Ex::As {
ref mut expr,
kind: _,
convert: _,
} => adjust(expr),
Ex::AtomicResult {
ref mut ty,
comparison: _,
} => self.types.adjust(ty),
Ex::WorkGroupUniformLoadResult { ref mut ty } => self.types.adjust(ty),
Ex::ArrayLength(ref mut expr) => adjust(expr),
Ex::RayQueryGetIntersection {
ref mut query,
committed: _,
} => adjust(query),
}
}
fn adjust_sample_level(
&self,
level: &mut crate::SampleLevel,
operand_map: &HandleMap<crate::Expression>,
) {
let adjust = |expr: &mut Handle<crate::Expression>| operand_map.adjust(expr);
use crate::SampleLevel as Sl;
match *level {
Sl::Auto | Sl::Zero => {}
Sl::Exact(ref mut expr) => adjust(expr),
Sl::Bias(ref mut expr) => adjust(expr),
Sl::Gradient {
ref mut x,
ref mut y,
} => {
adjust(x);
adjust(y);
}
}
}
fn adjust_image_query(
&self,
query: &mut crate::ImageQuery,
operand_map: &HandleMap<crate::Expression>,
) {
use crate::ImageQuery as Iq;
match *query {
Iq::Size { ref mut level } => operand_map.adjust_option(level),
Iq::NumLevels | Iq::NumLayers | Iq::NumSamples => {}
}
}
}
+134
View File
@@ -0,0 +1,134 @@
use super::handle_set_map::HandleSet;
use super::{FunctionMap, ModuleMap};
use crate::arena::Handle;
pub(super) struct FunctionTracer<'a> {
pub(super) module: &'a crate::Module,
pub(super) function: &'a crate::Function,
pub(super) types_used: &'a mut HandleSet<crate::Type>,
pub(super) constants_used: &'a mut HandleSet<crate::Constant>,
pub(super) const_expressions_used: &'a mut HandleSet<crate::Expression>,
/// Function-local expressions used.
pub(super) expressions_used: HandleSet<crate::Expression>,
}
impl<'a> FunctionTracer<'a> {
pub fn trace(&mut self) {
for argument in self.function.arguments.iter() {
self.trace_type(argument.ty);
}
if let Some(ref result) = self.function.result {
self.trace_type(result.ty);
}
for (_, local) in self.function.local_variables.iter() {
self.trace_type(local.ty);
if let Some(init) = local.init {
// TEST: try changing this to trace_expression
self.trace_const_expression(init);
}
}
// Treat named expressions as alive, for the sake of our test suite,
// which uses `let blah = expr;` to exercise lots of things.
for (value, _name) in &self.function.named_expressions {
self.trace_expression(*value);
}
self.trace_block(&self.function.body);
}
pub fn trace_type(&mut self, ty: Handle<crate::Type>) {
self.as_type().trace_type(ty)
}
pub fn trace_expression(&mut self, expr: Handle<crate::Expression>) {
self.as_expression().trace_expression(expr);
}
pub fn trace_const_expression(&mut self, expr: Handle<crate::Expression>) {
self.as_expression()
.as_const_expression()
.trace_expression(expr);
}
/*
pub fn trace_const_expression(&mut self, const_expr: Handle<crate::Expression>) {
self.as_expression().as_const_expression().trace_expression(const_expr);
}
*/
fn as_type(&mut self) -> super::types::TypeTracer {
super::types::TypeTracer {
types: &self.module.types,
types_used: self.types_used,
}
}
fn as_expression(&mut self) -> super::expressions::ExpressionTracer {
super::expressions::ExpressionTracer {
types: &self.module.types,
constants: &self.module.constants,
expressions: &self.function.expressions,
types_used: self.types_used,
constants_used: self.constants_used,
expressions_used: &mut self.expressions_used,
const_expressions: Some((
&self.module.const_expressions,
&mut self.const_expressions_used,
)),
}
}
}
impl FunctionMap {
pub fn compact(
&self,
function: &mut crate::Function,
module_map: &ModuleMap,
reuse: &mut crate::NamedExpressions,
) {
assert!(reuse.is_empty());
for argument in function.arguments.iter_mut() {
module_map.types.adjust(&mut argument.ty);
}
if let Some(ref mut result) = function.result {
module_map.types.adjust(&mut result.ty);
}
for (_, local) in function.local_variables.iter_mut() {
log::trace!("adjusting local variable {:?}", local.name);
module_map.types.adjust(&mut local.ty);
if let Some(ref mut init) = local.init {
module_map.const_expressions.adjust(init);
}
}
// Drop unused expressions, reusing existing storage.
function.expressions.retain_mut(|handle, expr| {
if self.expressions.used(handle) {
module_map.adjust_expression(expr, &self.expressions);
true
} else {
false
}
});
// Adjust named expressions.
for (mut handle, name) in function.named_expressions.drain(..) {
self.expressions.adjust(&mut handle);
reuse.insert(handle, name);
}
std::mem::swap(&mut function.named_expressions, reuse);
assert!(reuse.is_empty());
// Adjust statements.
self.adjust_block(&mut function.body);
}
}
+125
View File
@@ -0,0 +1,125 @@
use crate::arena::{Arena, Handle, UniqueArena};
type Index = std::num::NonZeroU32;
/// A set of `Handle<T>` values.
pub struct HandleSet<T> {
/// Bound on zero-based indexes of handles stored in this set.
len: usize,
/// `members[i]` is true if the handle with zero-based index `i`
/// is a member.
members: bit_set::BitSet,
/// This type is indexed by values of type `T`.
as_keys: std::marker::PhantomData<T>,
}
impl<T> HandleSet<T> {
pub fn for_arena(arena: &impl ArenaType<T>) -> Self {
let len = arena.len();
Self {
len,
members: bit_set::BitSet::with_capacity(len),
as_keys: std::marker::PhantomData,
}
}
/// Add `handle` to the set.
///
/// Return `true` if the handle was not already in the set. In
/// other words, return true if it was newly inserted.
pub fn insert(&mut self, handle: Handle<T>) -> bool {
// Note that, oddly, `Handle::index` does not return a 1-based
// `Index`, but rather a zero-based `usize`.
self.members.insert(handle.index())
}
}
pub trait ArenaType<T> {
fn len(&self) -> usize;
}
impl<T> ArenaType<T> for Arena<T> {
fn len(&self) -> usize {
self.len()
}
}
impl<T: std::hash::Hash + Eq> ArenaType<T> for UniqueArena<T> {
fn len(&self) -> usize {
self.len()
}
}
/// A map from old handle indices to new, compressed handle indices.
pub struct HandleMap<T> {
/// The indices assigned to handles in the compacted module.
///
/// If `new_index[i]` is `Some(n)`, then `n` is the 1-based
/// `Index` of the compacted `Handle` corresponding to the
/// pre-compacted `Handle` whose zero-based index is `i`. ("Clear
/// as mud.")
new_index: Vec<Option<Index>>,
/// This type is indexed by values of type `T`.
as_keys: std::marker::PhantomData<T>,
}
impl<T: 'static> HandleMap<T> {
pub fn from_set(set: HandleSet<T>) -> Self {
let mut next_index = Index::new(1).unwrap();
Self {
new_index: (0..set.len)
.map(|zero_based_index| {
if set.members.contains(zero_based_index) {
// This handle will be retained in the compacted version,
// so assign it a new index.
let this = next_index;
next_index = next_index.checked_add(1).unwrap();
Some(this)
} else {
// This handle will be omitted in the compacted version.
None
}
})
.collect(),
as_keys: std::marker::PhantomData,
}
}
/// Return true if `old` is used in the compacted module.
pub fn used(&self, old: Handle<T>) -> bool {
self.new_index[old.index()].is_some()
}
/// Return the counterpart to `old` in the compacted module.
///
/// If we thought `old` wouldn't be used in the compacted module, return
/// `None`.
pub fn try_adjust(&self, old: Handle<T>) -> Option<Handle<T>> {
log::trace!(
"adjusting {} handle [{}] -> [{:?}]",
std::any::type_name::<T>(),
old.index() + 1,
self.new_index[old.index()]
);
// Note that `Handle::index` returns a zero-based index,
// but `Handle::new` accepts a 1-based `Index`.
self.new_index[old.index()].map(Handle::new)
}
/// Return the counterpart to `old` in the compacted module.
///
/// If we thought `old` wouldn't be used in the compacted module, panic.
pub fn adjust(&self, handle: &mut Handle<T>) {
*handle = self.try_adjust(*handle).unwrap();
}
/// Like `adjust`, but for optional handles.
pub fn adjust_option(&self, handle: &mut Option<Handle<T>>) {
if let Some(ref mut handle) = *handle {
self.adjust(handle);
}
}
}
+286
View File
@@ -0,0 +1,286 @@
mod expressions;
mod functions;
mod handle_set_map;
mod statements;
mod types;
use crate::{arena, compact::functions::FunctionTracer};
use handle_set_map::{HandleMap, HandleSet};
/// Remove unused types, expressions, and constants from `module`.
///
/// Assuming that all globals, named constants, special types,
/// functions and entry points in `module` are used, determine which
/// types, constants, and expressions (both function-local and global
/// constant expressions) are actually used, and remove the rest,
/// adjusting all handles as necessary. The result should be a module
/// functionally identical to the original.
///
/// This may be useful to apply to modules generated in the snapshot
/// tests. Our backends often generate temporary names based on handle
/// indices, which means that adding or removing unused arena entries
/// can affect the output even though they have no semantic effect.
/// Such meaningless changes add noise to snapshot diffs, making
/// accurate patch review difficult. Compacting the modules before
/// generating snapshots makes the output independent of unused arena
/// entries.
///
/// # Panics
///
/// If `module` has not passed validation, this may panic.
pub fn compact(module: &mut crate::Module) {
let mut module_tracer = ModuleTracer::new(module);
// We treat all globals as used by definition.
log::trace!("tracing global variables");
{
for (_, global) in module.global_variables.iter() {
log::trace!("tracing global {:?}", global.name);
module_tracer.as_type().trace_type(global.ty);
if let Some(init) = global.init {
module_tracer.as_const_expression().trace_expression(init);
}
}
}
// We treat all special types as used by definition.
module_tracer.trace_special_types(&module.special_types);
// We treat all named constants as used by definition.
for (handle, constant) in module.constants.iter() {
if constant.name.is_some() {
module_tracer.constants_used.insert(handle);
module_tracer.as_type().trace_type(constant.ty);
module_tracer
.as_const_expression()
.trace_expression(constant.init);
}
}
// We assume that all functions are used.
//
// Observe which types, constant expressions, constants, and
// expressions each function uses, and produce maps from
// pre-compaction to post-compaction handles.
log::trace!("tracing functions");
let function_maps: Vec<FunctionMap> = module
.functions
.iter()
.map(|(_, f)| {
log::trace!("tracing function {:?}", f.name);
let mut function_tracer = module_tracer.enter_function(f);
function_tracer.trace();
FunctionMap::from(function_tracer)
})
.collect();
// Similiarly, observe what each entry point actually uses.
log::trace!("tracing entry points");
let entry_point_maps: Vec<FunctionMap> = module
.entry_points
.iter()
.map(|e| {
log::trace!("tracing entry point {:?}", e.function.name);
let mut used = module_tracer.enter_function(&e.function);
used.trace();
FunctionMap::from(used)
})
.collect();
// Now that we know what is used and what is never touched,
// produce maps from the `Handle`s that appear in `module` now to
// the corresponding `Handle`s that will refer to the same items
// in the compacted module.
let module_map = ModuleMap::from(module_tracer);
// Drop unused types from the type arena.
//
// `IndexSet`s don't have an underlying Vec<T> that we can steal, compact in
// place, and then rebuild the `IndexSet` from. So we have to rebuild the
// type arena from scratch.
log::trace!("compacting types");
let mut new_types = arena::UniqueArena::new();
for (old_handle, mut ty, span) in module.types.drain_all() {
if let Some(expected_new_handle) = module_map.types.try_adjust(old_handle) {
module_map.adjust_type(&mut ty);
let actual_new_handle = new_types.insert(ty, span);
assert_eq!(actual_new_handle, expected_new_handle);
}
}
module.types = new_types;
log::trace!("adjusting special types");
module_map.adjust_special_types(&mut module.special_types);
// Drop unused constant expressions, reusing existing storage.
log::trace!("adjusting constant expressions");
module.const_expressions.retain_mut(|handle, expr| {
if module_map.const_expressions.used(handle) {
module_map.adjust_expression(expr, &module_map.const_expressions);
true
} else {
false
}
});
// Drop unused constants in place, reusing existing storage.
log::trace!("adjusting constants");
module.constants.retain_mut(|handle, constant| {
if module_map.constants.used(handle) {
module_map.types.adjust(&mut constant.ty);
module_map.const_expressions.adjust(&mut constant.init);
true
} else {
false
}
});
// Adjust global variables' types and initializers.
log::trace!("adjusting global variables");
for (_, global) in module.global_variables.iter_mut() {
log::trace!("adjusting global {:?}", global.name);
module_map.types.adjust(&mut global.ty);
if let Some(ref mut init) = global.init {
module_map.const_expressions.adjust(init);
}
}
// Temporary storage to help us reuse allocations of existing
// named expression tables.
let mut reused_named_expressions = crate::NamedExpressions::default();
// Compact each function.
for ((_, function), map) in module.functions.iter_mut().zip(function_maps.iter()) {
log::trace!("compacting function {:?}", function.name);
map.compact(function, &module_map, &mut reused_named_expressions);
}
// Compact each entry point.
for (entry, map) in module.entry_points.iter_mut().zip(entry_point_maps.iter()) {
log::trace!("compacting entry point {:?}", entry.function.name);
map.compact(
&mut entry.function,
&module_map,
&mut reused_named_expressions,
);
}
}
struct ModuleTracer<'module> {
module: &'module crate::Module,
types_used: HandleSet<crate::Type>,
constants_used: HandleSet<crate::Constant>,
const_expressions_used: HandleSet<crate::Expression>,
}
impl<'module> ModuleTracer<'module> {
fn new(module: &'module crate::Module) -> Self {
Self {
module,
types_used: HandleSet::for_arena(&module.types),
constants_used: HandleSet::for_arena(&module.constants),
const_expressions_used: HandleSet::for_arena(&module.const_expressions),
}
}
fn trace_special_types(&mut self, special_types: &crate::SpecialTypes) {
let crate::SpecialTypes {
ref ray_desc,
ref ray_intersection,
ref predeclared_types,
} = *special_types;
let mut type_tracer = self.as_type();
if let Some(ray_desc) = *ray_desc {
type_tracer.trace_type(ray_desc);
}
if let Some(ray_intersection) = *ray_intersection {
type_tracer.trace_type(ray_intersection);
}
for (_, &handle) in predeclared_types {
type_tracer.trace_type(handle);
}
}
fn as_type(&mut self) -> types::TypeTracer {
types::TypeTracer {
types: &self.module.types,
types_used: &mut self.types_used,
}
}
fn as_const_expression(&mut self) -> expressions::ExpressionTracer {
expressions::ExpressionTracer {
types: &self.module.types,
constants: &self.module.constants,
expressions: &self.module.const_expressions,
types_used: &mut self.types_used,
constants_used: &mut self.constants_used,
expressions_used: &mut self.const_expressions_used,
const_expressions: None,
}
}
pub fn enter_function<'tracer>(
&'tracer mut self,
function: &'tracer crate::Function,
) -> FunctionTracer<'tracer> {
FunctionTracer {
module: self.module,
function,
types_used: &mut self.types_used,
constants_used: &mut self.constants_used,
const_expressions_used: &mut self.const_expressions_used,
expressions_used: HandleSet::for_arena(&function.expressions),
}
}
}
struct ModuleMap {
types: HandleMap<crate::Type>,
constants: HandleMap<crate::Constant>,
const_expressions: HandleMap<crate::Expression>,
}
impl From<ModuleTracer<'_>> for ModuleMap {
fn from(used: ModuleTracer) -> Self {
ModuleMap {
types: HandleMap::from_set(used.types_used),
constants: HandleMap::from_set(used.constants_used),
const_expressions: HandleMap::from_set(used.const_expressions_used),
}
}
}
impl ModuleMap {
fn adjust_special_types(&self, special: &mut crate::SpecialTypes) {
let crate::SpecialTypes {
ref mut ray_desc,
ref mut ray_intersection,
ref mut predeclared_types,
} = *special;
if let Some(ref mut ray_desc) = *ray_desc {
self.types.adjust(ray_desc);
}
if let Some(ref mut ray_intersection) = *ray_intersection {
self.types.adjust(ray_intersection);
}
for handle in predeclared_types.values_mut() {
self.types.adjust(handle);
}
}
}
struct FunctionMap {
expressions: HandleMap<crate::Expression>,
}
impl From<FunctionTracer<'_>> for FunctionMap {
fn from(used: FunctionTracer) -> Self {
FunctionMap {
expressions: HandleMap::from_set(used.expressions_used),
}
}
}
+302
View File
@@ -0,0 +1,302 @@
use super::functions::FunctionTracer;
use super::FunctionMap;
use crate::arena::Handle;
impl FunctionTracer<'_> {
pub fn trace_block(&mut self, block: &[crate::Statement]) {
let mut worklist: Vec<&[crate::Statement]> = vec![block];
while let Some(last) = worklist.pop() {
for stmt in last {
use crate::Statement as St;
match *stmt {
St::Emit(ref range) => {
for expr in range.clone() {
log::trace!("trace emitted expression {:?}", expr);
self.trace_expression(expr);
}
}
St::Block(ref block) => worklist.push(block),
St::If {
condition,
ref accept,
ref reject,
} => {
self.trace_expression(condition);
worklist.push(accept);
worklist.push(reject);
}
St::Switch {
selector,
ref cases,
} => {
self.trace_expression(selector);
for case in cases {
worklist.push(&case.body);
}
}
St::Loop {
ref body,
ref continuing,
break_if,
} => {
if let Some(break_if) = break_if {
self.trace_expression(break_if);
}
worklist.push(body);
worklist.push(continuing);
}
St::Return { value: Some(value) } => self.trace_expression(value),
St::Store { pointer, value } => {
self.trace_expression(pointer);
self.trace_expression(value);
}
St::ImageStore {
image,
coordinate,
array_index,
value,
} => {
self.trace_expression(image);
self.trace_expression(coordinate);
if let Some(array_index) = array_index {
self.trace_expression(array_index);
}
self.trace_expression(value);
}
St::Atomic {
pointer,
ref fun,
value,
result,
} => {
self.trace_expression(pointer);
self.trace_atomic_function(fun);
self.trace_expression(value);
self.trace_expression(result);
}
St::WorkGroupUniformLoad { pointer, result } => {
self.trace_expression(pointer);
self.trace_expression(result);
}
St::Call {
function: _,
ref arguments,
result,
} => {
for expr in arguments {
self.trace_expression(*expr);
}
if let Some(result) = result {
self.trace_expression(result);
}
}
St::RayQuery { query, ref fun } => {
self.trace_expression(query);
self.trace_ray_query_function(fun);
}
// Trivial statements.
St::Break
| St::Continue
| St::Kill
| St::Barrier(_)
| St::Return { value: None } => {}
}
}
}
}
fn trace_atomic_function(&mut self, fun: &crate::AtomicFunction) {
use crate::AtomicFunction as Af;
match *fun {
Af::Exchange {
compare: Some(expr),
} => self.trace_expression(expr),
Af::Exchange { compare: None }
| Af::Add
| Af::Subtract
| Af::And
| Af::ExclusiveOr
| Af::InclusiveOr
| Af::Min
| Af::Max => {}
}
}
fn trace_ray_query_function(&mut self, fun: &crate::RayQueryFunction) {
use crate::RayQueryFunction as Qf;
match *fun {
Qf::Initialize {
acceleration_structure,
descriptor,
} => {
self.trace_expression(acceleration_structure);
self.trace_expression(descriptor);
}
Qf::Proceed { result } => self.trace_expression(result),
Qf::Terminate => {}
}
}
}
impl FunctionMap {
pub fn adjust_block(&self, block: &mut [crate::Statement]) {
let mut worklist: Vec<&mut [crate::Statement]> = vec![block];
let adjust = |handle: &mut Handle<crate::Expression>| {
self.expressions.adjust(handle);
};
while let Some(last) = worklist.pop() {
for stmt in last {
use crate::Statement as St;
match *stmt {
St::Emit(ref mut range) => {
// Fortunately, compaction doesn't arbitrarily scramble
// the expressions in the arena, but instead preserves
// the order of the elements while squeezing out unused
// ones. That means that a contiguous range in the
// pre-compacted arena always maps to a contiguous range
// in the post-compacted arena. So we just need to
// adjust the endpoints.
let (mut first, mut last) = range.first_and_last().unwrap();
self.expressions.adjust(&mut first);
self.expressions.adjust(&mut last);
*range = crate::arena::Range::new_from_bounds(first, last);
}
St::Block(ref mut block) => worklist.push(block),
St::If {
ref mut condition,
ref mut accept,
ref mut reject,
} => {
adjust(condition);
worklist.push(accept);
worklist.push(reject);
}
St::Switch {
ref mut selector,
ref mut cases,
} => {
adjust(selector);
for case in cases {
worklist.push(&mut case.body);
}
}
St::Loop {
ref mut body,
ref mut continuing,
ref mut break_if,
} => {
if let Some(ref mut break_if) = *break_if {
adjust(break_if);
}
worklist.push(body);
worklist.push(continuing);
}
St::Return {
value: Some(ref mut value),
} => adjust(value),
St::Store {
ref mut pointer,
ref mut value,
} => {
adjust(pointer);
adjust(value);
}
St::ImageStore {
ref mut image,
ref mut coordinate,
ref mut array_index,
ref mut value,
} => {
adjust(image);
adjust(coordinate);
if let Some(ref mut array_index) = *array_index {
adjust(array_index);
}
adjust(value);
}
St::Atomic {
ref mut pointer,
ref mut fun,
ref mut value,
ref mut result,
} => {
adjust(pointer);
self.adjust_atomic_function(fun);
adjust(value);
adjust(result);
}
St::WorkGroupUniformLoad {
ref mut pointer,
ref mut result,
} => {
adjust(pointer);
adjust(result);
}
St::Call {
function: _,
ref mut arguments,
ref mut result,
} => {
for expr in arguments {
adjust(expr);
}
if let Some(ref mut result) = *result {
adjust(result);
}
}
St::RayQuery {
ref mut query,
ref mut fun,
} => {
adjust(query);
self.adjust_ray_query_function(fun);
}
// Trivial statements.
St::Break
| St::Continue
| St::Kill
| St::Barrier(_)
| St::Return { value: None } => {}
}
}
}
}
fn adjust_atomic_function(&self, fun: &mut crate::AtomicFunction) {
use crate::AtomicFunction as Af;
match *fun {
Af::Exchange {
compare: Some(ref mut expr),
} => {
self.expressions.adjust(expr);
}
Af::Exchange { compare: None }
| Af::Add
| Af::Subtract
| Af::And
| Af::ExclusiveOr
| Af::InclusiveOr
| Af::Min
| Af::Max => {}
}
}
fn adjust_ray_query_function(&self, fun: &mut crate::RayQueryFunction) {
use crate::RayQueryFunction as Qf;
match *fun {
Qf::Initialize {
ref mut acceleration_structure,
ref mut descriptor,
} => {
self.expressions.adjust(acceleration_structure);
self.expressions.adjust(descriptor);
}
Qf::Proceed { ref mut result } => {
self.expressions.adjust(result);
}
Qf::Terminate => {}
}
}
}
+93
View File
@@ -0,0 +1,93 @@
use super::{HandleSet, ModuleMap};
use crate::{Handle, UniqueArena};
pub struct TypeTracer<'a> {
pub types: &'a UniqueArena<crate::Type>,
pub types_used: &'a mut HandleSet<crate::Type>,
}
impl<'a> TypeTracer<'a> {
pub fn trace_type(&mut self, ty: Handle<crate::Type>) {
let mut work_list = vec![ty];
while let Some(ty) = work_list.pop() {
// If we've already seen this type, no need to traverse further.
if !self.types_used.insert(ty) {
continue;
}
use crate::TypeInner as Ti;
match self.types[ty].inner {
// Types that do not contain handles.
Ti::Scalar { .. }
| Ti::Vector { .. }
| Ti::Matrix { .. }
| Ti::Atomic { .. }
| Ti::ValuePointer { .. }
| Ti::Image { .. }
| Ti::Sampler { .. }
| Ti::AccelerationStructure
| Ti::RayQuery => {}
// Types that do contain handles.
Ti::Pointer { base, space: _ } => work_list.push(base),
Ti::Array {
base,
size: _,
stride: _,
} => work_list.push(base),
Ti::Struct {
ref members,
span: _,
} => {
work_list.extend(members.iter().map(|m| m.ty));
}
Ti::BindingArray { base, size: _ } => work_list.push(base),
}
}
}
}
impl ModuleMap {
pub fn adjust_type(&self, ty: &mut crate::Type) {
let adjust = |ty: &mut Handle<crate::Type>| self.types.adjust(ty);
use crate::TypeInner as Ti;
match ty.inner {
// Types that do not contain handles.
Ti::Scalar { .. }
| Ti::Vector { .. }
| Ti::Matrix { .. }
| Ti::Atomic { .. }
| Ti::ValuePointer { .. }
| Ti::Image { .. }
| Ti::Sampler { .. }
| Ti::AccelerationStructure
| Ti::RayQuery => {}
// Types that do contain handles.
Ti::Pointer {
ref mut base,
space: _,
} => adjust(base),
Ti::Array {
ref mut base,
size: _,
stride: _,
} => adjust(base),
Ti::Struct {
ref mut members,
span: _,
} => {
for member in members {
self.types.adjust(&mut member.ty);
}
}
Ti::BindingArray {
ref mut base,
size: _,
} => {
adjust(base);
}
};
}
}
+2
View File
@@ -279,6 +279,8 @@ An override expression can be evaluated at pipeline creation time.
mod arena;
pub mod back;
mod block;
#[cfg(feature = "compact")]
pub mod compact;
pub mod front;
pub mod keywords;
pub mod proc;