| 1 |
use alloc::{ |
| 2 |
borrow::Cow, |
| 3 |
string::{String, ToString}, |
| 4 |
}; |
| 5 |
use core::mem; |
| 6 |
|
| 7 |
use hashbrown::HashSet; |
| 8 |
use thiserror::Error; |
| 9 |
|
| 10 |
use super::PipelineConstants; |
| 11 |
use crate::{ |
| 12 |
arena::HandleVec, |
| 13 |
proc::{ConstantEvaluator, ConstantEvaluatorError, Emitter}, |
| 14 |
valid::{Capabilities, ModuleInfo, ValidationError, ValidationFlags, Validator}, |
| 15 |
Arena, Block, Constant, Expression, Function, Handle, Literal, Module, Override, Range, Scalar, |
| 16 |
Span, Statement, TypeInner, WithSpan, |
| 17 |
}; |
| 18 |
|
| 19 |
#[cfg(no_std)] |
| 20 |
use num_traits::float::FloatCore as _; |
| 21 |
|
| 22 |
#[derive(Error, Debug, Clone)] |
| 23 |
#[cfg_attr(test, derive(PartialEq))] |
| 24 |
pub enum PipelineConstantError { |
| 25 |
#[error("Missing value for pipeline-overridable constant with identifier string: '{0}'")] |
| 26 |
MissingValue(String), |
| 27 |
#[error( |
| 28 |
"Source f64 value needs to be finite ({}) for number destinations", |
| 29 |
"NaNs and Inifinites are not allowed" |
| 30 |
)] |
| 31 |
SrcNeedsToBeFinite, |
| 32 |
#[error("Source f64 value doesn't fit in destination")] |
| 33 |
DstRangeTooSmall, |
| 34 |
#[error(transparent)] |
| 35 |
ConstantEvaluatorError(#[from] ConstantEvaluatorError), |
| 36 |
#[error(transparent)] |
| 37 |
ValidationError(#[from] WithSpan<ValidationError>), |
| 38 |
#[error("workgroup_size override isn't strictly positive")] |
| 39 |
NegativeWorkgroupSize, |
| 40 |
} |
| 41 |
|
| 42 |
/// Replace all overrides in `module` with constants. |
| 43 |
/// |
| 44 |
/// If no changes are needed, this just returns `Cow::Borrowed` |
| 45 |
/// references to `module` and `module_info`. Otherwise, it clones |
| 46 |
/// `module`, edits its [`global_expressions`] arena to contain only |
| 47 |
/// fully-evaluated expressions, and returns `Cow::Owned` values |
| 48 |
/// holding the simplified module and its validation results. |
| 49 |
/// |
| 50 |
/// In either case, the module returned has an empty `overrides` |
| 51 |
/// arena, and the `global_expressions` arena contains only |
| 52 |
/// fully-evaluated expressions. |
| 53 |
/// |
| 54 |
/// [`global_expressions`]: Module::global_expressions |
| 55 |
pub fn process_overrides<'a>( |
| 56 |
module: &'a Module, |
| 57 |
module_info: &'a ModuleInfo, |
| 58 |
pipeline_constants: &PipelineConstants, |
| 59 |
) -> Result<(Cow<'a, Module>, Cow<'a, ModuleInfo>), PipelineConstantError> { |
| 60 |
if module.overrides.is_empty() { |
| 61 |
return Ok((Cow::Borrowed(module), Cow::Borrowed(module_info))); |
| 62 |
} |
| 63 |
|
| 64 |
let mut module = module.clone(); |
| 65 |
|
| 66 |
// A map from override handles to the handles of the constants |
| 67 |
// we've replaced them with. |
| 68 |
let mut override_map = HandleVec::with_capacity(module.overrides.len()); |
| 69 |
|
| 70 |
// A map from `module`'s original global expression handles to |
| 71 |
// handles in the new, simplified global expression arena. |
| 72 |
let mut adjusted_global_expressions = HandleVec::with_capacity(module.global_expressions.len()); |
| 73 |
|
| 74 |
// The set of constants whose initializer handles we've already |
| 75 |
// updated to refer to the newly built global expression arena. |
| 76 |
// |
| 77 |
// All constants in `module` must have their `init` handles |
| 78 |
// updated to point into the new, simplified global expression |
| 79 |
// arena. Some of these we can most easily handle as a side effect |
| 80 |
// during the simplification process, but we must handle the rest |
| 81 |
// in a final fixup pass, guided by `adjusted_global_expressions`. We |
| 82 |
// add their handles to this set, so that the final fixup step can |
| 83 |
// leave them alone. |
| 84 |
let mut adjusted_constant_initializers = HashSet::with_capacity(module.constants.len()); |
| 85 |
|
| 86 |
let mut global_expression_kind_tracker = crate::proc::ExpressionKindTracker::new(); |
| 87 |
let mut layouter = crate::proc::Layouter::default(); |
| 88 |
|
| 89 |
// An iterator through the original overrides table, consumed in |
| 90 |
// approximate tandem with the global expressions. |
| 91 |
let mut overrides = mem::take(&mut module.overrides); |
| 92 |
let mut override_iter = overrides.iter_mut_span(); |
| 93 |
|
| 94 |
// Do two things in tandem: |
| 95 |
// |
| 96 |
// - Rebuild the global expression arena from scratch, fully |
| 97 |
// evaluating all expressions, and replacing each `Override` |
| 98 |
// expression in `module.global_expressions` with a `Constant` |
| 99 |
// expression. |
| 100 |
// |
| 101 |
// - Build a new `Constant` in `module.constants` to take the |
| 102 |
// place of each `Override`. |
| 103 |
// |
| 104 |
// Build a map from old global expression handles to their |
| 105 |
// fully-evaluated counterparts in `adjusted_global_expressions` as we |
| 106 |
// go. |
| 107 |
// |
| 108 |
// Why in tandem? Overrides refer to expressions, and expressions |
| 109 |
// refer to overrides, so we can't disentangle the two into |
| 110 |
// separate phases. However, we can take advantage of the fact |
| 111 |
// that the overrides and expressions must form a DAG, and work |
| 112 |
// our way from the leaves to the roots, replacing and evaluating |
| 113 |
// as we go. |
| 114 |
// |
| 115 |
// Although the two loops are nested, this is really two |
| 116 |
// alternating phases: we adjust and evaluate constant expressions |
| 117 |
// until we hit an `Override` expression, at which point we switch |
| 118 |
// to building `Constant`s for `Overrides` until we've handled the |
| 119 |
// one used by the expression. Then we switch back to processing |
| 120 |
// expressions. Because we know they form a DAG, we know the |
| 121 |
// `Override` expressions we encounter can only have initializers |
| 122 |
// referring to global expressions we've already simplified. |
| 123 |
for (old_h, expr, span) in module.global_expressions.drain() { |
| 124 |
let mut expr = match expr { |
| 125 |
Expression::Override(h) => { |
| 126 |
let c_h = if let Some(new_h) = override_map.get(h) { |
| 127 |
*new_h |
| 128 |
} else { |
| 129 |
let mut new_h = None; |
| 130 |
for entry in override_iter.by_ref() { |
| 131 |
let stop = entry.0 == h; |
| 132 |
new_h = Some(process_override( |
| 133 |
entry, |
| 134 |
pipeline_constants, |
| 135 |
&mut module, |
| 136 |
&mut override_map, |
| 137 |
&adjusted_global_expressions, |
| 138 |
&mut adjusted_constant_initializers, |
| 139 |
&mut global_expression_kind_tracker, |
| 140 |
)?); |
| 141 |
if stop { |
| 142 |
break; |
| 143 |
} |
| 144 |
} |
| 145 |
new_h.unwrap() |
| 146 |
}; |
| 147 |
Expression::Constant(c_h) |
| 148 |
} |
| 149 |
Expression::Constant(c_h) => { |
| 150 |
if adjusted_constant_initializers.insert(c_h) { |
| 151 |
let init = &mut module.constants[c_h].init; |
| 152 |
*init = adjusted_global_expressions[*init]; |
| 153 |
} |
| 154 |
expr |
| 155 |
} |
| 156 |
expr => expr, |
| 157 |
}; |
| 158 |
let mut evaluator = ConstantEvaluator::for_wgsl_module( |
| 159 |
&mut module, |
| 160 |
&mut global_expression_kind_tracker, |
| 161 |
&mut layouter, |
| 162 |
false, |
| 163 |
); |
| 164 |
adjust_expr(&adjusted_global_expressions, &mut expr); |
| 165 |
let h = evaluator.try_eval_and_append(expr, span)?; |
| 166 |
adjusted_global_expressions.insert(old_h, h); |
| 167 |
} |
| 168 |
|
| 169 |
// Finish processing any overrides we didn't visit in the loop above. |
| 170 |
for entry in override_iter { |
| 171 |
match *entry.1 { |
| 172 |
Override { name: Some(_), .. } | Override { id: Some(_), .. } => { |
| 173 |
process_override( |
| 174 |
entry, |
| 175 |
pipeline_constants, |
| 176 |
&mut module, |
| 177 |
&mut override_map, |
| 178 |
&adjusted_global_expressions, |
| 179 |
&mut adjusted_constant_initializers, |
| 180 |
&mut global_expression_kind_tracker, |
| 181 |
)?; |
| 182 |
} |
| 183 |
Override { |
| 184 |
init: Some(ref mut init), |
| 185 |
.. |
| 186 |
} => { |
| 187 |
*init = adjusted_global_expressions[*init]; |
| 188 |
} |
| 189 |
_ => {} |
| 190 |
} |
| 191 |
} |
| 192 |
|
| 193 |
// Update the initialization expression handles of all `Constant`s |
| 194 |
// and `GlobalVariable`s. Skip `Constant`s we'd already updated en |
| 195 |
// passant. |
| 196 |
for (_, c) in module |
| 197 |
.constants |
| 198 |
.iter_mut() |
| 199 |
.filter(|&(c_h, _)| !adjusted_constant_initializers.contains(&c_h)) |
| 200 |
{ |
| 201 |
c.init = adjusted_global_expressions[c.init]; |
| 202 |
} |
| 203 |
|
| 204 |
for (_, v) in module.global_variables.iter_mut() { |
| 205 |
if let Some(ref mut init) = v.init { |
| 206 |
*init = adjusted_global_expressions[*init]; |
| 207 |
} |
| 208 |
} |
| 209 |
|
| 210 |
let mut functions = mem::take(&mut module.functions); |
| 211 |
for (_, function) in functions.iter_mut() { |
| 212 |
process_function(&mut module, &override_map, &mut layouter, function)?; |
| 213 |
} |
| 214 |
module.functions = functions; |
| 215 |
|
| 216 |
let mut entry_points = mem::take(&mut module.entry_points); |
| 217 |
for ep in entry_points.iter_mut() { |
| 218 |
process_function(&mut module, &override_map, &mut layouter, &mut ep.function)?; |
| 219 |
process_workgroup_size_override(&mut module, &adjusted_global_expressions, ep)?; |
| 220 |
} |
| 221 |
module.entry_points = entry_points; |
| 222 |
module.overrides = overrides; |
| 223 |
|
| 224 |
// Now that we've rewritten all the expressions, we need to |
| 225 |
// recompute their types and other metadata. For the time being, |
| 226 |
// do a full re-validation. |
| 227 |
let mut validator = Validator::new(ValidationFlags::all(), Capabilities::all()); |
| 228 |
let module_info = validator.validate_resolved_overrides(&module)?; |
| 229 |
|
| 230 |
Ok((Cow::Owned(module), Cow::Owned(module_info))) |
| 231 |
} |
| 232 |
|
| 233 |
fn process_workgroup_size_override( |
| 234 |
module: &mut Module, |
| 235 |
adjusted_global_expressions: &HandleVec<Expression, Handle<Expression>>, |
| 236 |
ep: &mut crate::EntryPoint, |
| 237 |
) -> Result<(), PipelineConstantError> { |
| 238 |
match ep.workgroup_size_overrides { |
| 239 |
None => {} |
| 240 |
Some(overrides) => { |
| 241 |
overrides.iter().enumerate().try_for_each( |
| 242 |
|(i, overridden)| -> Result<(), PipelineConstantError> { |
| 243 |
match *overridden { |
| 244 |
None => Ok(()), |
| 245 |
Some(h) => { |
| 246 |
ep.workgroup_size[i] = module |
| 247 |
.to_ctx() |
| 248 |
.eval_expr_to_u32(adjusted_global_expressions[h]) |
| 249 |
.map(|n| { |
| 250 |
if n == 0 { |
| 251 |
Err(PipelineConstantError::NegativeWorkgroupSize) |
| 252 |
} else { |
| 253 |
Ok(n) |
| 254 |
} |
| 255 |
}) |
| 256 |
.map_err(|_| PipelineConstantError::NegativeWorkgroupSize)??; |
| 257 |
Ok(()) |
| 258 |
} |
| 259 |
} |
| 260 |
}, |
| 261 |
)?; |
| 262 |
ep.workgroup_size_overrides = None; |
| 263 |
} |
| 264 |
} |
| 265 |
Ok(()) |
| 266 |
} |
| 267 |
|
| 268 |
/// Add a [`Constant`] to `module` for the override `old_h`. |
| 269 |
/// |
| 270 |
/// Add the new `Constant` to `override_map` and `adjusted_constant_initializers`. |
| 271 |
fn process_override( |
| 272 |
(old_h, r#override, span): (Handle<Override>, &mut Override, &Span), |
| 273 |
pipeline_constants: &PipelineConstants, |
| 274 |
module: &mut Module, |
| 275 |
override_map: &mut HandleVec<Override, Handle<Constant>>, |
| 276 |
adjusted_global_expressions: &HandleVec<Expression, Handle<Expression>>, |
| 277 |
adjusted_constant_initializers: &mut HashSet<Handle<Constant>>, |
| 278 |
global_expression_kind_tracker: &mut crate::proc::ExpressionKindTracker, |
| 279 |
) -> Result<Handle<Constant>, PipelineConstantError> { |
| 280 |
// Determine which key to use for `r#override` in `pipeline_constants`. |
| 281 |
let key = if let Some(id) = r#override.id { |
| 282 |
Cow::Owned(id.to_string()) |
| 283 |
} else if let Some(ref name) = r#override.name { |
| 284 |
Cow::Borrowed(name) |
| 285 |
} else { |
| 286 |
unreachable!(); |
| 287 |
}; |
| 288 |
|
| 289 |
// Generate a global expression for `r#override`'s value, either |
| 290 |
// from the provided `pipeline_constants` table or its initializer |
| 291 |
// in the module. |
| 292 |
let init = if let Some(value) = pipeline_constants.get::<str>(&key) { |
| 293 |
let literal = match module.types[r#override.ty].inner { |
| 294 |
TypeInner::Scalar(scalar) => map_value_to_literal(*value, scalar)?, |
| 295 |
_ => unreachable!(), |
| 296 |
}; |
| 297 |
let expr = module |
| 298 |
.global_expressions |
| 299 |
.append(Expression::Literal(literal), Span::UNDEFINED); |
| 300 |
global_expression_kind_tracker.insert(expr, crate::proc::ExpressionKind::Const); |
| 301 |
expr |
| 302 |
} else if let Some(init) = r#override.init { |
| 303 |
adjusted_global_expressions[init] |
| 304 |
} else { |
| 305 |
return Err(PipelineConstantError::MissingValue(key.to_string())); |
| 306 |
}; |
| 307 |
|
| 308 |
// Generate a new `Constant` to represent the override's value. |
| 309 |
let constant = Constant { |
| 310 |
name: r#override.name.clone(), |
| 311 |
ty: r#override.ty, |
| 312 |
init, |
| 313 |
}; |
| 314 |
let h = module.constants.append(constant, *span); |
| 315 |
override_map.insert(old_h, h); |
| 316 |
adjusted_constant_initializers.insert(h); |
| 317 |
r#override.init = Some(init); |
| 318 |
Ok(h) |
| 319 |
} |
| 320 |
|
| 321 |
/// Replace all override expressions in `function` with fully-evaluated constants. |
| 322 |
/// |
| 323 |
/// Replace all `Expression::Override`s in `function`'s expression arena with |
| 324 |
/// the corresponding `Expression::Constant`s, as given in `override_map`. |
| 325 |
/// Replace any expressions whose values are now known with their fully |
| 326 |
/// evaluated form. |
| 327 |
/// |
| 328 |
/// If `h` is a `Handle<Override>`, then `override_map[h]` is the |
| 329 |
/// `Handle<Constant>` for the override's final value. |
| 330 |
fn process_function( |
| 331 |
module: &mut Module, |
| 332 |
override_map: &HandleVec<Override, Handle<Constant>>, |
| 333 |
layouter: &mut crate::proc::Layouter, |
| 334 |
function: &mut Function, |
| 335 |
) -> Result<(), ConstantEvaluatorError> { |
| 336 |
// A map from original local expression handles to |
| 337 |
// handles in the new, local expression arena. |
| 338 |
let mut adjusted_local_expressions = HandleVec::with_capacity(function.expressions.len()); |
| 339 |
|
| 340 |
let mut local_expression_kind_tracker = crate::proc::ExpressionKindTracker::new(); |
| 341 |
|
| 342 |
let mut expressions = mem::take(&mut function.expressions); |
| 343 |
|
| 344 |
// Dummy `emitter` and `block` for the constant evaluator. |
| 345 |
// We can ignore the concept of emitting expressions here since |
| 346 |
// expressions have already been covered by a `Statement::Emit` |
| 347 |
// in the frontend. |
| 348 |
// The only thing we might have to do is remove some expressions |
| 349 |
// that have been covered by a `Statement::Emit`. See the docs of |
| 350 |
// `filter_emits_in_block` for the reasoning. |
| 351 |
let mut emitter = Emitter::default(); |
| 352 |
let mut block = Block::new(); |
| 353 |
|
| 354 |
let mut evaluator = ConstantEvaluator::for_wgsl_function( |
| 355 |
module, |
| 356 |
&mut function.expressions, |
| 357 |
&mut local_expression_kind_tracker, |
| 358 |
layouter, |
| 359 |
&mut emitter, |
| 360 |
&mut block, |
| 361 |
false, |
| 362 |
); |
| 363 |
|
| 364 |
for (old_h, mut expr, span) in expressions.drain() { |
| 365 |
if let Expression::Override(h) = expr { |
| 366 |
expr = Expression::Constant(override_map[h]); |
| 367 |
} |
| 368 |
adjust_expr(&adjusted_local_expressions, &mut expr); |
| 369 |
let h = evaluator.try_eval_and_append(expr, span)?; |
| 370 |
adjusted_local_expressions.insert(old_h, h); |
| 371 |
} |
| 372 |
|
| 373 |
adjust_block(&adjusted_local_expressions, &mut function.body); |
| 374 |
|
| 375 |
filter_emits_in_block(&mut function.body, &function.expressions); |
| 376 |
|
| 377 |
// Update local expression initializers. |
| 378 |
for (_, local) in function.local_variables.iter_mut() { |
| 379 |
if let &mut Some(ref mut init) = &mut local.init { |
| 380 |
*init = adjusted_local_expressions[*init]; |
| 381 |
} |
| 382 |
} |
| 383 |
|
| 384 |
// We've changed the keys of `function.named_expression`, so we have to |
| 385 |
// rebuild it from scratch. |
| 386 |
let named_expressions = mem::take(&mut function.named_expressions); |
| 387 |
for (expr_h, name) in named_expressions { |
| 388 |
function |
| 389 |
.named_expressions |
| 390 |
.insert(adjusted_local_expressions[expr_h], name); |
| 391 |
} |
| 392 |
|
| 393 |
Ok(()) |
| 394 |
} |
| 395 |
|
| 396 |
/// Replace every expression handle in `expr` with its counterpart |
| 397 |
/// given by `new_pos`. |
| 398 |
fn adjust_expr(new_pos: &HandleVec<Expression, Handle<Expression>>, expr: &mut Expression) { |
| 399 |
let adjust = |expr: &mut Handle<Expression>| { |
| 400 |
*expr = new_pos[*expr]; |
| 401 |
}; |
| 402 |
match *expr { |
| 403 |
Expression::Compose { |
| 404 |
ref mut components, |
| 405 |
ty: _, |
| 406 |
} => { |
| 407 |
for c in components.iter_mut() { |
| 408 |
adjust(c); |
| 409 |
} |
| 410 |
} |
| 411 |
Expression::Access { |
| 412 |
ref mut base, |
| 413 |
ref mut index, |
| 414 |
} => { |
| 415 |
adjust(base); |
| 416 |
adjust(index); |
| 417 |
} |
| 418 |
Expression::AccessIndex { |
| 419 |
ref mut base, |
| 420 |
index: _, |
| 421 |
} => { |
| 422 |
adjust(base); |
| 423 |
} |
| 424 |
Expression::Splat { |
| 425 |
ref mut value, |
| 426 |
size: _, |
| 427 |
} => { |
| 428 |
adjust(value); |
| 429 |
} |
| 430 |
Expression::Swizzle { |
| 431 |
ref mut vector, |
| 432 |
size: _, |
| 433 |
pattern: _, |
| 434 |
} => { |
| 435 |
adjust(vector); |
| 436 |
} |
| 437 |
Expression::Load { ref mut pointer } => { |
| 438 |
adjust(pointer); |
| 439 |
} |
| 440 |
Expression::ImageSample { |
| 441 |
ref mut image, |
| 442 |
ref mut sampler, |
| 443 |
ref mut coordinate, |
| 444 |
ref mut array_index, |
| 445 |
ref mut offset, |
| 446 |
ref mut level, |
| 447 |
ref mut depth_ref, |
| 448 |
gather: _, |
| 449 |
} => { |
| 450 |
adjust(image); |
| 451 |
adjust(sampler); |
| 452 |
adjust(coordinate); |
| 453 |
if let Some(e) = array_index.as_mut() { |
| 454 |
adjust(e); |
| 455 |
} |
| 456 |
if let Some(e) = offset.as_mut() { |
| 457 |
adjust(e); |
| 458 |
} |
| 459 |
match *level { |
| 460 |
crate::SampleLevel::Exact(ref mut expr) |
| 461 |
| crate::SampleLevel::Bias(ref mut expr) => { |
| 462 |
adjust(expr); |
| 463 |
} |
| 464 |
crate::SampleLevel::Gradient { |
| 465 |
ref mut x, |
| 466 |
ref mut y, |
| 467 |
} => { |
| 468 |
adjust(x); |
| 469 |
adjust(y); |
| 470 |
} |
| 471 |
_ => {} |
| 472 |
} |
| 473 |
if let Some(e) = depth_ref.as_mut() { |
| 474 |
adjust(e); |
| 475 |
} |
| 476 |
} |
| 477 |
Expression::ImageLoad { |
| 478 |
ref mut image, |
| 479 |
ref mut coordinate, |
| 480 |
ref mut array_index, |
| 481 |
ref mut sample, |
| 482 |
ref mut level, |
| 483 |
} => { |
| 484 |
adjust(image); |
| 485 |
adjust(coordinate); |
| 486 |
if let Some(e) = array_index.as_mut() { |
| 487 |
adjust(e); |
| 488 |
} |
| 489 |
if let Some(e) = sample.as_mut() { |
| 490 |
adjust(e); |
| 491 |
} |
| 492 |
if let Some(e) = level.as_mut() { |
| 493 |
adjust(e); |
| 494 |
} |
| 495 |
} |
| 496 |
Expression::ImageQuery { |
| 497 |
ref mut image, |
| 498 |
ref mut query, |
| 499 |
} => { |
| 500 |
adjust(image); |
| 501 |
match *query { |
| 502 |
crate::ImageQuery::Size { ref mut level } => { |
| 503 |
if let Some(e) = level.as_mut() { |
| 504 |
adjust(e); |
| 505 |
} |
| 506 |
} |
| 507 |
crate::ImageQuery::NumLevels |
| 508 |
| crate::ImageQuery::NumLayers |
| 509 |
| crate::ImageQuery::NumSamples => {} |
| 510 |
} |
| 511 |
} |
| 512 |
Expression::Unary { |
| 513 |
ref mut expr, |
| 514 |
op: _, |
| 515 |
} => { |
| 516 |
adjust(expr); |
| 517 |
} |
| 518 |
Expression::Binary { |
| 519 |
ref mut left, |
| 520 |
ref mut right, |
| 521 |
op: _, |
| 522 |
} => { |
| 523 |
adjust(left); |
| 524 |
adjust(right); |
| 525 |
} |
| 526 |
Expression::Select { |
| 527 |
ref mut condition, |
| 528 |
ref mut accept, |
| 529 |
ref mut reject, |
| 530 |
} => { |
| 531 |
adjust(condition); |
| 532 |
adjust(accept); |
| 533 |
adjust(reject); |
| 534 |
} |
| 535 |
Expression::Derivative { |
| 536 |
ref mut expr, |
| 537 |
axis: _, |
| 538 |
ctrl: _, |
| 539 |
} => { |
| 540 |
adjust(expr); |
| 541 |
} |
| 542 |
Expression::Relational { |
| 543 |
ref mut argument, |
| 544 |
fun: _, |
| 545 |
} => { |
| 546 |
adjust(argument); |
| 547 |
} |
| 548 |
Expression::Math { |
| 549 |
ref mut arg, |
| 550 |
ref mut arg1, |
| 551 |
ref mut arg2, |
| 552 |
ref mut arg3, |
| 553 |
fun: _, |
| 554 |
} => { |
| 555 |
adjust(arg); |
| 556 |
if let Some(e) = arg1.as_mut() { |
| 557 |
adjust(e); |
| 558 |
} |
| 559 |
if let Some(e) = arg2.as_mut() { |
| 560 |
adjust(e); |
| 561 |
} |
| 562 |
if let Some(e) = arg3.as_mut() { |
| 563 |
adjust(e); |
| 564 |
} |
| 565 |
} |
| 566 |
Expression::As { |
| 567 |
ref mut expr, |
| 568 |
kind: _, |
| 569 |
convert: _, |
| 570 |
} => { |
| 571 |
adjust(expr); |
| 572 |
} |
| 573 |
Expression::ArrayLength(ref mut expr) => { |
| 574 |
adjust(expr); |
| 575 |
} |
| 576 |
Expression::RayQueryGetIntersection { |
| 577 |
ref mut query, |
| 578 |
committed: _, |
| 579 |
} => { |
| 580 |
adjust(query); |
| 581 |
} |
| 582 |
Expression::Literal(_) |
| 583 |
| Expression::FunctionArgument(_) |
| 584 |
| Expression::GlobalVariable(_) |
| 585 |
| Expression::LocalVariable(_) |
| 586 |
| Expression::CallResult(_) |
| 587 |
| Expression::RayQueryProceedResult |
| 588 |
| Expression::Constant(_) |
| 589 |
| Expression::Override(_) |
| 590 |
| Expression::ZeroValue(_) |
| 591 |
| Expression::AtomicResult { |
| 592 |
ty: _, |
| 593 |
comparison: _, |
| 594 |
} |
| 595 |
| Expression::WorkGroupUniformLoadResult { ty: _ } |
| 596 |
| Expression::SubgroupBallotResult |
| 597 |
| Expression::SubgroupOperationResult { .. } => {} |
| 598 |
Expression::RayQueryVertexPositions { |
| 599 |
ref mut query, |
| 600 |
committed: _, |
| 601 |
} => { |
| 602 |
adjust(query); |
| 603 |
} |
| 604 |
} |
| 605 |
} |
| 606 |
|
| 607 |
/// Replace every expression handle in `block` with its counterpart |
| 608 |
/// given by `new_pos`. |
| 609 |
fn adjust_block(new_pos: &HandleVec<Expression, Handle<Expression>>, block: &mut Block) { |
| 610 |
for stmt in block.iter_mut() { |
| 611 |
adjust_stmt(new_pos, stmt); |
| 612 |
} |
| 613 |
} |
| 614 |
|
| 615 |
/// Replace every expression handle in `stmt` with its counterpart |
| 616 |
/// given by `new_pos`. |
| 617 |
fn adjust_stmt(new_pos: &HandleVec<Expression, Handle<Expression>>, stmt: &mut Statement) { |
| 618 |
let adjust = |expr: &mut Handle<Expression>| { |
| 619 |
*expr = new_pos[*expr]; |
| 620 |
}; |
| 621 |
match *stmt { |
| 622 |
Statement::Emit(ref mut range) => { |
| 623 |
if let Some((mut first, mut last)) = range.first_and_last() { |
| 624 |
adjust(&mut first); |
| 625 |
adjust(&mut last); |
| 626 |
*range = Range::new_from_bounds(first, last); |
| 627 |
} |
| 628 |
} |
| 629 |
Statement::Block(ref mut block) => { |
| 630 |
adjust_block(new_pos, block); |
| 631 |
} |
| 632 |
Statement::If { |
| 633 |
ref mut condition, |
| 634 |
ref mut accept, |
| 635 |
ref mut reject, |
| 636 |
} => { |
| 637 |
adjust(condition); |
| 638 |
adjust_block(new_pos, accept); |
| 639 |
adjust_block(new_pos, reject); |
| 640 |
} |
| 641 |
Statement::Switch { |
| 642 |
ref mut selector, |
| 643 |
ref mut cases, |
| 644 |
} => { |
| 645 |
adjust(selector); |
| 646 |
for case in cases.iter_mut() { |
| 647 |
adjust_block(new_pos, &mut case.body); |
| 648 |
} |
| 649 |
} |
| 650 |
Statement::Loop { |
| 651 |
ref mut body, |
| 652 |
ref mut continuing, |
| 653 |
ref mut break_if, |
| 654 |
} => { |
| 655 |
adjust_block(new_pos, body); |
| 656 |
adjust_block(new_pos, continuing); |
| 657 |
if let Some(e) = break_if.as_mut() { |
| 658 |
adjust(e); |
| 659 |
} |
| 660 |
} |
| 661 |
Statement::Return { ref mut value } => { |
| 662 |
if let Some(e) = value.as_mut() { |
| 663 |
adjust(e); |
| 664 |
} |
| 665 |
} |
| 666 |
Statement::Store { |
| 667 |
ref mut pointer, |
| 668 |
ref mut value, |
| 669 |
} => { |
| 670 |
adjust(pointer); |
| 671 |
adjust(value); |
| 672 |
} |
| 673 |
Statement::ImageStore { |
| 674 |
ref mut image, |
| 675 |
ref mut coordinate, |
| 676 |
ref mut array_index, |
| 677 |
ref mut value, |
| 678 |
} => { |
| 679 |
adjust(image); |
| 680 |
adjust(coordinate); |
| 681 |
if let Some(e) = array_index.as_mut() { |
| 682 |
adjust(e); |
| 683 |
} |
| 684 |
adjust(value); |
| 685 |
} |
| 686 |
Statement::Atomic { |
| 687 |
ref mut pointer, |
| 688 |
ref mut value, |
| 689 |
ref mut result, |
| 690 |
ref mut fun, |
| 691 |
} => { |
| 692 |
adjust(pointer); |
| 693 |
adjust(value); |
| 694 |
if let Some(ref mut result) = *result { |
| 695 |
adjust(result); |
| 696 |
} |
| 697 |
match *fun { |
| 698 |
crate::AtomicFunction::Exchange { |
| 699 |
compare: Some(ref mut compare), |
| 700 |
} => { |
| 701 |
adjust(compare); |
| 702 |
} |
| 703 |
crate::AtomicFunction::Add |
| 704 |
| crate::AtomicFunction::Subtract |
| 705 |
| crate::AtomicFunction::And |
| 706 |
| crate::AtomicFunction::ExclusiveOr |
| 707 |
| crate::AtomicFunction::InclusiveOr |
| 708 |
| crate::AtomicFunction::Min |
| 709 |
| crate::AtomicFunction::Max |
| 710 |
| crate::AtomicFunction::Exchange { compare: None } => {} |
| 711 |
} |
| 712 |
} |
| 713 |
Statement::ImageAtomic { |
| 714 |
ref mut image, |
| 715 |
ref mut coordinate, |
| 716 |
ref mut array_index, |
| 717 |
fun: _, |
| 718 |
ref mut value, |
| 719 |
} => { |
| 720 |
adjust(image); |
| 721 |
adjust(coordinate); |
| 722 |
if let Some(ref mut array_index) = *array_index { |
| 723 |
adjust(array_index); |
| 724 |
} |
| 725 |
adjust(value); |
| 726 |
} |
| 727 |
Statement::WorkGroupUniformLoad { |
| 728 |
ref mut pointer, |
| 729 |
ref mut result, |
| 730 |
} => { |
| 731 |
adjust(pointer); |
| 732 |
adjust(result); |
| 733 |
} |
| 734 |
Statement::SubgroupBallot { |
| 735 |
ref mut result, |
| 736 |
ref mut predicate, |
| 737 |
} => { |
| 738 |
if let Some(ref mut predicate) = *predicate { |
| 739 |
adjust(predicate); |
| 740 |
} |
| 741 |
adjust(result); |
| 742 |
} |
| 743 |
Statement::SubgroupCollectiveOperation { |
| 744 |
ref mut argument, |
| 745 |
ref mut result, |
| 746 |
.. |
| 747 |
} => { |
| 748 |
adjust(argument); |
| 749 |
adjust(result); |
| 750 |
} |
| 751 |
Statement::SubgroupGather { |
| 752 |
ref mut mode, |
| 753 |
ref mut argument, |
| 754 |
ref mut result, |
| 755 |
} => { |
| 756 |
match *mode { |
| 757 |
crate::GatherMode::BroadcastFirst => {} |
| 758 |
crate::GatherMode::Broadcast(ref mut index) |
| 759 |
| crate::GatherMode::Shuffle(ref mut index) |
| 760 |
| crate::GatherMode::ShuffleDown(ref mut index) |
| 761 |
| crate::GatherMode::ShuffleUp(ref mut index) |
| 762 |
| crate::GatherMode::ShuffleXor(ref mut index) => { |
| 763 |
adjust(index); |
| 764 |
} |
| 765 |
} |
| 766 |
adjust(argument); |
| 767 |
adjust(result) |
| 768 |
} |
| 769 |
Statement::Call { |
| 770 |
ref mut arguments, |
| 771 |
ref mut result, |
| 772 |
function: _, |
| 773 |
} => { |
| 774 |
for argument in arguments.iter_mut() { |
| 775 |
adjust(argument); |
| 776 |
} |
| 777 |
if let Some(e) = result.as_mut() { |
| 778 |
adjust(e); |
| 779 |
} |
| 780 |
} |
| 781 |
Statement::RayQuery { |
| 782 |
ref mut query, |
| 783 |
ref mut fun, |
| 784 |
} => { |
| 785 |
adjust(query); |
| 786 |
match *fun { |
| 787 |
crate::RayQueryFunction::Initialize { |
| 788 |
ref mut acceleration_structure, |
| 789 |
ref mut descriptor, |
| 790 |
} => { |
| 791 |
adjust(acceleration_structure); |
| 792 |
adjust(descriptor); |
| 793 |
} |
| 794 |
crate::RayQueryFunction::Proceed { ref mut result } => { |
| 795 |
adjust(result); |
| 796 |
} |
| 797 |
crate::RayQueryFunction::GenerateIntersection { ref mut hit_t } => { |
| 798 |
adjust(hit_t); |
| 799 |
} |
| 800 |
crate::RayQueryFunction::ConfirmIntersection => {} |
| 801 |
crate::RayQueryFunction::Terminate => {} |
| 802 |
} |
| 803 |
} |
| 804 |
Statement::Break | Statement::Continue | Statement::Kill | Statement::Barrier(_) => {} |
| 805 |
} |
| 806 |
} |
| 807 |
|
| 808 |
/// Adjust [`Emit`] statements in `block` to skip [`needs_pre_emit`] expressions we have introduced. |
| 809 |
/// |
| 810 |
/// According to validation, [`Emit`] statements must not cover any expressions |
| 811 |
/// for which [`Expression::needs_pre_emit`] returns true. All expressions built |
| 812 |
/// by successful constant evaluation fall into that category, meaning that |
| 813 |
/// `process_function` will usually rewrite [`Override`] expressions and those |
| 814 |
/// that use their values into pre-emitted expressions, leaving any [`Emit`] |
| 815 |
/// statements that cover them invalid. |
| 816 |
/// |
| 817 |
/// This function rewrites all [`Emit`] statements into zero or more new |
| 818 |
/// [`Emit`] statements covering only those expressions in the original range |
| 819 |
/// that are not pre-emitted. |
| 820 |
/// |
| 821 |
/// [`Emit`]: Statement::Emit |
| 822 |
/// [`needs_pre_emit`]: Expression::needs_pre_emit |
| 823 |
/// [`Override`]: Expression::Override |
| 824 |
fn filter_emits_in_block(block: &mut Block, expressions: &Arena<Expression>) { |
| 825 |
let original = mem::replace(block, Block::with_capacity(block.len())); |
| 826 |
for (stmt, span) in original.span_into_iter() { |
| 827 |
match stmt { |
| 828 |
Statement::Emit(range) => { |
| 829 |
let mut current = None; |
| 830 |
for expr_h in range { |
| 831 |
if expressions[expr_h].needs_pre_emit() { |
| 832 |
if let Some((first, last)) = current { |
| 833 |
block.push(Statement::Emit(Range::new_from_bounds(first, last)), span); |
| 834 |
} |
| 835 |
|
| 836 |
current = None; |
| 837 |
} else if let Some((_, ref mut last)) = current { |
| 838 |
*last = expr_h; |
| 839 |
} else { |
| 840 |
current = Some((expr_h, expr_h)); |
| 841 |
} |
| 842 |
} |
| 843 |
if let Some((first, last)) = current { |
| 844 |
block.push(Statement::Emit(Range::new_from_bounds(first, last)), span); |
| 845 |
} |
| 846 |
} |
| 847 |
Statement::Block(mut child) => { |
| 848 |
filter_emits_in_block(&mut child, expressions); |
| 849 |
block.push(Statement::Block(child), span); |
| 850 |
} |
| 851 |
Statement::If { |
| 852 |
condition, |
| 853 |
mut accept, |
| 854 |
mut reject, |
| 855 |
} => { |
| 856 |
filter_emits_in_block(&mut accept, expressions); |
| 857 |
filter_emits_in_block(&mut reject, expressions); |
| 858 |
block.push( |
| 859 |
Statement::If { |
| 860 |
condition, |
| 861 |
accept, |
| 862 |
reject, |
| 863 |
}, |
| 864 |
span, |
| 865 |
); |
| 866 |
} |
| 867 |
Statement::Switch { |
| 868 |
selector, |
| 869 |
mut cases, |
| 870 |
} => { |
| 871 |
for case in &mut cases { |
| 872 |
filter_emits_in_block(&mut case.body, expressions); |
| 873 |
} |
| 874 |
block.push(Statement::Switch { selector, cases }, span); |
| 875 |
} |
| 876 |
Statement::Loop { |
| 877 |
mut body, |
| 878 |
mut continuing, |
| 879 |
break_if, |
| 880 |
} => { |
| 881 |
filter_emits_in_block(&mut body, expressions); |
| 882 |
filter_emits_in_block(&mut continuing, expressions); |
| 883 |
block.push( |
| 884 |
Statement::Loop { |
| 885 |
body, |
| 886 |
continuing, |
| 887 |
break_if, |
| 888 |
}, |
| 889 |
span, |
| 890 |
); |
| 891 |
} |
| 892 |
stmt => block.push(stmt.clone(), span), |
| 893 |
} |
| 894 |
} |
| 895 |
} |
| 896 |
|
| 897 |
fn map_value_to_literal(value: f64, scalar: Scalar) -> Result<Literal, PipelineConstantError> { |
| 898 |
// note that in rust 0.0 == -0.0 |
| 899 |
match scalar { |
| 900 |
Scalar::BOOL => { |
| 901 |
// https://webidl.spec.whatwg.org/#js-boolean |
| 902 |
let value = value != 0.0 && !value.is_nan(); |
| 903 |
Ok(Literal::Bool(value)) |
| 904 |
} |
| 905 |
Scalar::I32 => { |
| 906 |
// https://webidl.spec.whatwg.org/#js-long |
| 907 |
if !value.is_finite() { |
| 908 |
return Err(PipelineConstantError::SrcNeedsToBeFinite); |
| 909 |
} |
| 910 |
|
| 911 |
let value = value.trunc(); |
| 912 |
if value < f64::from(i32::MIN) || value > f64::from(i32::MAX) { |
| 913 |
return Err(PipelineConstantError::DstRangeTooSmall); |
| 914 |
} |
| 915 |
|
| 916 |
let value = value as i32; |
| 917 |
Ok(Literal::I32(value)) |
| 918 |
} |
| 919 |
Scalar::U32 => { |
| 920 |
// https://webidl.spec.whatwg.org/#js-unsigned-long |
| 921 |
if !value.is_finite() { |
| 922 |
return Err(PipelineConstantError::SrcNeedsToBeFinite); |
| 923 |
} |
| 924 |
|
| 925 |
let value = value.trunc(); |
| 926 |
if value < f64::from(u32::MIN) || value > f64::from(u32::MAX) { |
| 927 |
return Err(PipelineConstantError::DstRangeTooSmall); |
| 928 |
} |
| 929 |
|
| 930 |
let value = value as u32; |
| 931 |
Ok(Literal::U32(value)) |
| 932 |
} |
| 933 |
Scalar::F32 => { |
| 934 |
// https://webidl.spec.whatwg.org/#js-float |
| 935 |
if !value.is_finite() { |
| 936 |
return Err(PipelineConstantError::SrcNeedsToBeFinite); |
| 937 |
} |
| 938 |
|
| 939 |
let value = value as f32; |
| 940 |
if !value.is_finite() { |
| 941 |
return Err(PipelineConstantError::DstRangeTooSmall); |
| 942 |
} |
| 943 |
|
| 944 |
Ok(Literal::F32(value)) |
| 945 |
} |
| 946 |
Scalar::F64 => { |
| 947 |
// https://webidl.spec.whatwg.org/#js-double |
| 948 |
if !value.is_finite() { |
| 949 |
return Err(PipelineConstantError::SrcNeedsToBeFinite); |
| 950 |
} |
| 951 |
|
| 952 |
Ok(Literal::F64(value)) |
| 953 |
} |
| 954 |
_ => unreachable!(), |
| 955 |
} |
| 956 |
} |
| 957 |
|
| 958 |
#[test] |
| 959 |
fn test_map_value_to_literal() { |
| 960 |
let bool_test_cases = [ |
| 961 |
(0.0, false), |
| 962 |
(-0.0, false), |
| 963 |
(f64::NAN, false), |
| 964 |
(1.0, true), |
| 965 |
(f64::INFINITY, true), |
| 966 |
(f64::NEG_INFINITY, true), |
| 967 |
]; |
| 968 |
for (value, out) in bool_test_cases { |
| 969 |
let res = Ok(Literal::Bool(out)); |
| 970 |
assert_eq!(map_value_to_literal(value, Scalar::BOOL), res); |
| 971 |
} |
| 972 |
|
| 973 |
for scalar in [Scalar::I32, Scalar::U32, Scalar::F32, Scalar::F64] { |
| 974 |
for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { |
| 975 |
let res = Err(PipelineConstantError::SrcNeedsToBeFinite); |
| 976 |
assert_eq!(map_value_to_literal(value, scalar), res); |
| 977 |
} |
| 978 |
} |
| 979 |
|
| 980 |
// i32 |
| 981 |
assert_eq!( |
| 982 |
map_value_to_literal(f64::from(i32::MIN), Scalar::I32), |
| 983 |
Ok(Literal::I32(i32::MIN)) |
| 984 |
); |
| 985 |
assert_eq!( |
| 986 |
map_value_to_literal(f64::from(i32::MAX), Scalar::I32), |
| 987 |
Ok(Literal::I32(i32::MAX)) |
| 988 |
); |
| 989 |
assert_eq!( |
| 990 |
map_value_to_literal(f64::from(i32::MIN) - 1.0, Scalar::I32), |
| 991 |
Err(PipelineConstantError::DstRangeTooSmall) |
| 992 |
); |
| 993 |
assert_eq!( |
| 994 |
map_value_to_literal(f64::from(i32::MAX) + 1.0, Scalar::I32), |
| 995 |
Err(PipelineConstantError::DstRangeTooSmall) |
| 996 |
); |
| 997 |
|
| 998 |
// u32 |
| 999 |
assert_eq!( |
| 1000 |
map_value_to_literal(f64::from(u32::MIN), Scalar::U32), |
| 1001 |
Ok(Literal::U32(u32::MIN)) |
| 1002 |
); |
| 1003 |
assert_eq!( |
| 1004 |
map_value_to_literal(f64::from(u32::MAX), Scalar::U32), |
| 1005 |
Ok(Literal::U32(u32::MAX)) |
| 1006 |
); |
| 1007 |
assert_eq!( |
| 1008 |
map_value_to_literal(f64::from(u32::MIN) - 1.0, Scalar::U32), |
| 1009 |
Err(PipelineConstantError::DstRangeTooSmall) |
| 1010 |
); |
| 1011 |
assert_eq!( |
| 1012 |
map_value_to_literal(f64::from(u32::MAX) + 1.0, Scalar::U32), |
| 1013 |
Err(PipelineConstantError::DstRangeTooSmall) |
| 1014 |
); |
| 1015 |
|
| 1016 |
// f32 |
| 1017 |
assert_eq!( |
| 1018 |
map_value_to_literal(f64::from(f32::MIN), Scalar::F32), |
| 1019 |
Ok(Literal::F32(f32::MIN)) |
| 1020 |
); |
| 1021 |
assert_eq!( |
| 1022 |
map_value_to_literal(f64::from(f32::MAX), Scalar::F32), |
| 1023 |
Ok(Literal::F32(f32::MAX)) |
| 1024 |
); |
| 1025 |
assert_eq!( |
| 1026 |
map_value_to_literal(-f64::from_bits(0x47efffffefffffff), Scalar::F32), |
| 1027 |
Ok(Literal::F32(f32::MIN)) |
| 1028 |
); |
| 1029 |
assert_eq!( |
| 1030 |
map_value_to_literal(f64::from_bits(0x47efffffefffffff), Scalar::F32), |
| 1031 |
Ok(Literal::F32(f32::MAX)) |
| 1032 |
); |
| 1033 |
assert_eq!( |
| 1034 |
map_value_to_literal(-f64::from_bits(0x47effffff0000000), Scalar::F32), |
| 1035 |
Err(PipelineConstantError::DstRangeTooSmall) |
| 1036 |
); |
| 1037 |
assert_eq!( |
| 1038 |
map_value_to_literal(f64::from_bits(0x47effffff0000000), Scalar::F32), |
| 1039 |
Err(PipelineConstantError::DstRangeTooSmall) |
| 1040 |
); |
| 1041 |
|
| 1042 |
// f64 |
| 1043 |
assert_eq!( |
| 1044 |
map_value_to_literal(f64::MIN, Scalar::F64), |
| 1045 |
Ok(Literal::F64(f64::MIN)) |
| 1046 |
); |
| 1047 |
assert_eq!( |
| 1048 |
map_value_to_literal(f64::MAX, Scalar::F64), |
| 1049 |
Ok(Literal::F64(f64::MAX)) |
| 1050 |
); |
| 1051 |
} |