| 1 |
/*! |
| 2 |
Implementations for `BlockContext` methods. |
| 3 |
*/ |
| 4 |
|
| 5 |
use alloc::vec::Vec; |
| 6 |
|
| 7 |
use arrayvec::ArrayVec; |
| 8 |
use spirv::Word; |
| 9 |
|
| 10 |
use super::{ |
| 11 |
index::BoundsCheckResult, selection::Selection, Block, BlockContext, Dimension, Error, |
| 12 |
Instruction, LocalType, LookupType, NumericType, ResultMember, WrappedFunction, Writer, |
| 13 |
WriterFlags, |
| 14 |
}; |
| 15 |
use crate::{arena::Handle, proc::index::GuardedIndex, Statement}; |
| 16 |
|
| 17 |
fn get_dimension(type_inner: &crate::TypeInner) -> Dimension { |
| 18 |
match *type_inner { |
| 19 |
crate::TypeInner::Scalar(_) => Dimension::Scalar, |
| 20 |
crate::TypeInner::Vector { .. } => Dimension::Vector, |
| 21 |
crate::TypeInner::Matrix { .. } => Dimension::Matrix, |
| 22 |
_ => unreachable!(), |
| 23 |
} |
| 24 |
} |
| 25 |
|
| 26 |
/// How to derive the type of `OpAccessChain` instructions from Naga IR. |
| 27 |
/// |
| 28 |
/// Most of the time, we compile Naga IR to SPIR-V instructions whose result |
| 29 |
/// types are simply the direct SPIR-V analog of the Naga IR's. But in some |
| 30 |
/// cases, the Naga IR and SPIR-V types need to diverge. |
| 31 |
/// |
| 32 |
/// This enum specifies how [`BlockContext::write_access_chain`] should |
| 33 |
/// choose a SPIR-V result type for the `OpAccessChain` it generates, based on |
| 34 |
/// the type of the given Naga IR [`Expression`] it's generating code for. |
| 35 |
/// |
| 36 |
/// [`Expression`]: crate::Expression |
| 37 |
enum AccessTypeAdjustment { |
| 38 |
/// No adjustment needed: the SPIR-V type should be the direct |
| 39 |
/// analog of the Naga IR expression type. |
| 40 |
/// |
| 41 |
/// For most access chains, this is the right thing: the Naga IR access |
| 42 |
/// expression produces a [`Pointer`] to the element / component, and the |
| 43 |
/// SPIR-V `OpAccessChain` instruction does the same. |
| 44 |
/// |
| 45 |
/// [`Pointer`]: crate::TypeInner::Pointer |
| 46 |
None, |
| 47 |
|
| 48 |
/// The SPIR-V type should be an `OpPointer` to the direct analog of the |
| 49 |
/// Naga IR expression's type. |
| 50 |
/// |
| 51 |
/// This is necessary for indexing binding arrays in the [`Handle`] address |
| 52 |
/// space: |
| 53 |
/// |
| 54 |
/// - In Naga IR, referencing a binding array [`GlobalVariable`] in the |
| 55 |
/// [`Handle`] address space produces a value of type [`BindingArray`], |
| 56 |
/// not a pointer to such. And [`Access`] and [`AccessIndex`] expressions |
| 57 |
/// operate on handle binding arrays by value, and produce handle values, |
| 58 |
/// not pointers. |
| 59 |
/// |
| 60 |
/// - In SPIR-V, a binding array `OpVariable` produces a pointer to an |
| 61 |
/// array, and `OpAccessChain` instructions operate on pointers, |
| 62 |
/// regardless of whether the elements are opaque types or not. |
| 63 |
/// |
| 64 |
/// See also the documentation for [`BindingArray`]. |
| 65 |
/// |
| 66 |
/// [`Handle`]: crate::AddressSpace::Handle |
| 67 |
/// [`GlobalVariable`]: crate::GlobalVariable |
| 68 |
/// [`BindingArray`]: crate::TypeInner::BindingArray |
| 69 |
/// [`Access`]: crate::Expression::Access |
| 70 |
/// [`AccessIndex`]: crate::Expression::AccessIndex |
| 71 |
IntroducePointer(spirv::StorageClass), |
| 72 |
} |
| 73 |
|
| 74 |
/// The results of emitting code for a left-hand-side expression. |
| 75 |
/// |
| 76 |
/// On success, `write_access_chain` returns one of these. |
| 77 |
enum ExpressionPointer { |
| 78 |
/// The pointer to the expression's value is available, as the value of the |
| 79 |
/// expression with the given id. |
| 80 |
Ready { pointer_id: Word }, |
| 81 |
|
| 82 |
/// The access expression must be conditional on the value of `condition`, a boolean |
| 83 |
/// expression that is true if all indices are in bounds. If `condition` is true, then |
| 84 |
/// `access` is an `OpAccessChain` instruction that will compute a pointer to the |
| 85 |
/// expression's value. If `condition` is false, then executing `access` would be |
| 86 |
/// undefined behavior. |
| 87 |
Conditional { |
| 88 |
condition: Word, |
| 89 |
access: Instruction, |
| 90 |
}, |
| 91 |
} |
| 92 |
|
| 93 |
/// The termination statement to be added to the end of the block |
| 94 |
enum BlockExit { |
| 95 |
/// Generates an OpReturn (void return) |
| 96 |
Return, |
| 97 |
/// Generates an OpBranch to the specified block |
| 98 |
Branch { |
| 99 |
/// The branch target block |
| 100 |
target: Word, |
| 101 |
}, |
| 102 |
/// Translates a loop `break if` into an `OpBranchConditional` to the |
| 103 |
/// merge block if true (the merge block is passed through [`LoopContext::break_id`] |
| 104 |
/// or else to the loop header (passed through [`preamble_id`]) |
| 105 |
/// |
| 106 |
/// [`preamble_id`]: Self::BreakIf::preamble_id |
| 107 |
BreakIf { |
| 108 |
/// The condition of the `break if` |
| 109 |
condition: Handle<crate::Expression>, |
| 110 |
/// The loop header block id |
| 111 |
preamble_id: Word, |
| 112 |
}, |
| 113 |
} |
| 114 |
|
| 115 |
/// What code generation did with a provided [`BlockExit`] value. |
| 116 |
/// |
| 117 |
/// A function that accepts a [`BlockExit`] argument should return a value of |
| 118 |
/// this type, to indicate whether the code it generated ended up using the |
| 119 |
/// provided exit, or ignored it and did a non-local exit of some other kind |
| 120 |
/// (say, [`Break`] or [`Continue`]). Some callers must use this information to |
| 121 |
/// decide whether to generate the target block at all. |
| 122 |
/// |
| 123 |
/// [`Break`]: Statement::Break |
| 124 |
/// [`Continue`]: Statement::Continue |
| 125 |
#[must_use] |
| 126 |
enum BlockExitDisposition { |
| 127 |
/// The generated code used the provided `BlockExit` value. If it included a |
| 128 |
/// block label, the caller should be sure to actually emit the block it |
| 129 |
/// refers to. |
| 130 |
Used, |
| 131 |
|
| 132 |
/// The generated code did not use the provided `BlockExit` value. If it |
| 133 |
/// included a block label, the caller should not bother to actually emit |
| 134 |
/// the block it refers to, unless it knows the block is needed for |
| 135 |
/// something else. |
| 136 |
Discarded, |
| 137 |
} |
| 138 |
|
| 139 |
#[derive(Clone, Copy, Default)] |
| 140 |
struct LoopContext { |
| 141 |
continuing_id: Option<Word>, |
| 142 |
break_id: Option<Word>, |
| 143 |
} |
| 144 |
|
| 145 |
#[derive(Debug)] |
| 146 |
pub(crate) struct DebugInfoInner<'a> { |
| 147 |
pub source_code: &'a str, |
| 148 |
pub source_file_id: Word, |
| 149 |
} |
| 150 |
|
| 151 |
impl Writer { |
| 152 |
// Flip Y coordinate to adjust for coordinate space difference |
| 153 |
// between SPIR-V and our IR. |
| 154 |
// The `position_id` argument is a pointer to a `vecN<f32>`, |
| 155 |
// whose `y` component we will negate. |
| 156 |
fn write_epilogue_position_y_flip( |
| 157 |
&mut self, |
| 158 |
position_id: Word, |
| 159 |
body: &mut Vec<Instruction>, |
| 160 |
) -> Result<(), Error> { |
| 161 |
let float_ptr_type_id = self.get_f32_pointer_type_id(spirv::StorageClass::Output); |
| 162 |
let index_y_id = self.get_index_constant(1); |
| 163 |
let access_id = self.id_gen.next(); |
| 164 |
body.push(Instruction::access_chain( |
| 165 |
float_ptr_type_id, |
| 166 |
access_id, |
| 167 |
position_id, |
| 168 |
&[index_y_id], |
| 169 |
)); |
| 170 |
|
| 171 |
let float_type_id = self.get_f32_type_id(); |
| 172 |
let load_id = self.id_gen.next(); |
| 173 |
body.push(Instruction::load(float_type_id, load_id, access_id, None)); |
| 174 |
|
| 175 |
let neg_id = self.id_gen.next(); |
| 176 |
body.push(Instruction::unary( |
| 177 |
spirv::Op::FNegate, |
| 178 |
float_type_id, |
| 179 |
neg_id, |
| 180 |
load_id, |
| 181 |
)); |
| 182 |
|
| 183 |
body.push(Instruction::store(access_id, neg_id, None)); |
| 184 |
Ok(()) |
| 185 |
} |
| 186 |
|
| 187 |
// Clamp fragment depth between 0 and 1. |
| 188 |
fn write_epilogue_frag_depth_clamp( |
| 189 |
&mut self, |
| 190 |
frag_depth_id: Word, |
| 191 |
body: &mut Vec<Instruction>, |
| 192 |
) -> Result<(), Error> { |
| 193 |
let float_type_id = self.get_f32_type_id(); |
| 194 |
let zero_scalar_id = self.get_constant_scalar(crate::Literal::F32(0.0)); |
| 195 |
let one_scalar_id = self.get_constant_scalar(crate::Literal::F32(1.0)); |
| 196 |
|
| 197 |
let original_id = self.id_gen.next(); |
| 198 |
body.push(Instruction::load( |
| 199 |
float_type_id, |
| 200 |
original_id, |
| 201 |
frag_depth_id, |
| 202 |
None, |
| 203 |
)); |
| 204 |
|
| 205 |
let clamp_id = self.id_gen.next(); |
| 206 |
body.push(Instruction::ext_inst( |
| 207 |
self.gl450_ext_inst_id, |
| 208 |
spirv::GLOp::FClamp, |
| 209 |
float_type_id, |
| 210 |
clamp_id, |
| 211 |
&[original_id, zero_scalar_id, one_scalar_id], |
| 212 |
)); |
| 213 |
|
| 214 |
body.push(Instruction::store(frag_depth_id, clamp_id, None)); |
| 215 |
Ok(()) |
| 216 |
} |
| 217 |
|
| 218 |
fn write_entry_point_return( |
| 219 |
&mut self, |
| 220 |
value_id: Word, |
| 221 |
ir_result: &crate::FunctionResult, |
| 222 |
result_members: &[ResultMember], |
| 223 |
body: &mut Vec<Instruction>, |
| 224 |
) -> Result<(), Error> { |
| 225 |
for (index, res_member) in result_members.iter().enumerate() { |
| 226 |
let member_value_id = match ir_result.binding { |
| 227 |
Some(_) => value_id, |
| 228 |
None => { |
| 229 |
let member_value_id = self.id_gen.next(); |
| 230 |
body.push(Instruction::composite_extract( |
| 231 |
res_member.type_id, |
| 232 |
member_value_id, |
| 233 |
value_id, |
| 234 |
&[index as u32], |
| 235 |
)); |
| 236 |
member_value_id |
| 237 |
} |
| 238 |
}; |
| 239 |
|
| 240 |
body.push(Instruction::store(res_member.id, member_value_id, None)); |
| 241 |
|
| 242 |
match res_member.built_in { |
| 243 |
Some(crate::BuiltIn::Position { .. }) |
| 244 |
if self.flags.contains(WriterFlags::ADJUST_COORDINATE_SPACE) => |
| 245 |
{ |
| 246 |
self.write_epilogue_position_y_flip(res_member.id, body)?; |
| 247 |
} |
| 248 |
Some(crate::BuiltIn::FragDepth) |
| 249 |
if self.flags.contains(WriterFlags::CLAMP_FRAG_DEPTH) => |
| 250 |
{ |
| 251 |
self.write_epilogue_frag_depth_clamp(res_member.id, body)?; |
| 252 |
} |
| 253 |
_ => {} |
| 254 |
} |
| 255 |
} |
| 256 |
Ok(()) |
| 257 |
} |
| 258 |
} |
| 259 |
|
| 260 |
impl BlockContext<'_> { |
| 261 |
/// Generates code to ensure that a loop is bounded. Should be called immediately |
| 262 |
/// after adding the OpLoopMerge instruction to `block`. This function will |
| 263 |
/// [`consume()`](crate::back::spv::Function::consume) `block` and append its |
| 264 |
/// instructions to a new [`Block`], which will be returned to the caller for it to |
| 265 |
/// consumed prior to writing the loop body. |
| 266 |
/// |
| 267 |
/// Additionally this function will populate [`force_loop_bounding_vars`](crate::back::spv::Function::force_loop_bounding_vars), |
| 268 |
/// ensuring that [`Function::to_words()`](crate::back::spv::Function::to_words) will |
| 269 |
/// declare the required variables. |
| 270 |
/// |
| 271 |
/// See [`crate::back::msl::Writer::gen_force_bounded_loop_statements`] for details |
| 272 |
/// of why this is required. |
| 273 |
fn write_force_bounded_loop_instructions(&mut self, mut block: Block, merge_id: Word) -> Block { |
| 274 |
let uint_type_id = self.writer.get_u32_type_id(); |
| 275 |
let uint2_type_id = self.writer.get_vec2u_type_id(); |
| 276 |
let uint2_ptr_type_id = self |
| 277 |
.writer |
| 278 |
.get_vec2u_pointer_type_id(spirv::StorageClass::Function); |
| 279 |
let bool_type_id = self.writer.get_bool_type_id(); |
| 280 |
let bool2_type_id = self.writer.get_vec2_bool_type_id(); |
| 281 |
let zero_uint_const_id = self.writer.get_constant_scalar(crate::Literal::U32(0)); |
| 282 |
let zero_uint2_const_id = self.writer.get_constant_composite( |
| 283 |
LookupType::Local(LocalType::Numeric(NumericType::Vector { |
| 284 |
size: crate::VectorSize::Bi, |
| 285 |
scalar: crate::Scalar::U32, |
| 286 |
})), |
| 287 |
&[zero_uint_const_id, zero_uint_const_id], |
| 288 |
); |
| 289 |
let one_uint_const_id = self.writer.get_constant_scalar(crate::Literal::U32(1)); |
| 290 |
let max_uint_const_id = self |
| 291 |
.writer |
| 292 |
.get_constant_scalar(crate::Literal::U32(u32::MAX)); |
| 293 |
let max_uint2_const_id = self.writer.get_constant_composite( |
| 294 |
LookupType::Local(LocalType::Numeric(NumericType::Vector { |
| 295 |
size: crate::VectorSize::Bi, |
| 296 |
scalar: crate::Scalar::U32, |
| 297 |
})), |
| 298 |
&[max_uint_const_id, max_uint_const_id], |
| 299 |
); |
| 300 |
|
| 301 |
let loop_counter_var_id = self.gen_id(); |
| 302 |
if self.writer.flags.contains(WriterFlags::DEBUG) { |
| 303 |
self.writer |
| 304 |
.debugs |
| 305 |
.push(Instruction::name(loop_counter_var_id, "loop_bound")); |
| 306 |
} |
| 307 |
let var = super::LocalVariable { |
| 308 |
id: loop_counter_var_id, |
| 309 |
instruction: Instruction::variable( |
| 310 |
uint2_ptr_type_id, |
| 311 |
loop_counter_var_id, |
| 312 |
spirv::StorageClass::Function, |
| 313 |
Some(max_uint2_const_id), |
| 314 |
), |
| 315 |
}; |
| 316 |
self.function.force_loop_bounding_vars.push(var); |
| 317 |
|
| 318 |
let break_if_block = self.gen_id(); |
| 319 |
|
| 320 |
self.function |
| 321 |
.consume(block, Instruction::branch(break_if_block)); |
| 322 |
block = Block::new(break_if_block); |
| 323 |
|
| 324 |
// Load the current loop counter value from its variable. We use a vec2<u32> to |
| 325 |
// simulate a 64-bit counter. |
| 326 |
let load_id = self.gen_id(); |
| 327 |
block.body.push(Instruction::load( |
| 328 |
uint2_type_id, |
| 329 |
load_id, |
| 330 |
loop_counter_var_id, |
| 331 |
None, |
| 332 |
)); |
| 333 |
|
| 334 |
// If both the high and low u32s have reached 0 then break. ie |
| 335 |
// if (all(eq(loop_counter, vec2(0)))) { break; } |
| 336 |
let eq_id = self.gen_id(); |
| 337 |
block.body.push(Instruction::binary( |
| 338 |
spirv::Op::IEqual, |
| 339 |
bool2_type_id, |
| 340 |
eq_id, |
| 341 |
zero_uint2_const_id, |
| 342 |
load_id, |
| 343 |
)); |
| 344 |
let all_eq_id = self.gen_id(); |
| 345 |
block.body.push(Instruction::relational( |
| 346 |
spirv::Op::All, |
| 347 |
bool_type_id, |
| 348 |
all_eq_id, |
| 349 |
eq_id, |
| 350 |
)); |
| 351 |
|
| 352 |
let inc_counter_block_id = self.gen_id(); |
| 353 |
block.body.push(Instruction::selection_merge( |
| 354 |
inc_counter_block_id, |
| 355 |
spirv::SelectionControl::empty(), |
| 356 |
)); |
| 357 |
self.function.consume( |
| 358 |
block, |
| 359 |
Instruction::branch_conditional(all_eq_id, merge_id, inc_counter_block_id), |
| 360 |
); |
| 361 |
block = Block::new(inc_counter_block_id); |
| 362 |
|
| 363 |
// To simulate a 64-bit counter we always decrement the low u32, and decrement |
| 364 |
// the high u32 when the low u32 overflows. ie |
| 365 |
// counter -= vec2(select(0u, 1u, counter.y == 0), 1u); |
| 366 |
// Count down from u32::MAX rather than up from 0 to avoid hang on |
| 367 |
// certain Intel drivers. See <https://github.com/gfx-rs/wgpu/issues/7319>. |
| 368 |
let low_id = self.gen_id(); |
| 369 |
block.body.push(Instruction::composite_extract( |
| 370 |
uint_type_id, |
| 371 |
low_id, |
| 372 |
load_id, |
| 373 |
&[1], |
| 374 |
)); |
| 375 |
let low_overflow_id = self.gen_id(); |
| 376 |
block.body.push(Instruction::binary( |
| 377 |
spirv::Op::IEqual, |
| 378 |
bool_type_id, |
| 379 |
low_overflow_id, |
| 380 |
low_id, |
| 381 |
zero_uint_const_id, |
| 382 |
)); |
| 383 |
let carry_bit_id = self.gen_id(); |
| 384 |
block.body.push(Instruction::select( |
| 385 |
uint_type_id, |
| 386 |
carry_bit_id, |
| 387 |
low_overflow_id, |
| 388 |
one_uint_const_id, |
| 389 |
zero_uint_const_id, |
| 390 |
)); |
| 391 |
let decrement_id = self.gen_id(); |
| 392 |
block.body.push(Instruction::composite_construct( |
| 393 |
uint2_type_id, |
| 394 |
decrement_id, |
| 395 |
&[carry_bit_id, one_uint_const_id], |
| 396 |
)); |
| 397 |
let result_id = self.gen_id(); |
| 398 |
block.body.push(Instruction::binary( |
| 399 |
spirv::Op::ISub, |
| 400 |
uint2_type_id, |
| 401 |
result_id, |
| 402 |
load_id, |
| 403 |
decrement_id, |
| 404 |
)); |
| 405 |
block |
| 406 |
.body |
| 407 |
.push(Instruction::store(loop_counter_var_id, result_id, None)); |
| 408 |
|
| 409 |
block |
| 410 |
} |
| 411 |
|
| 412 |
/// Cache an expression for a value. |
| 413 |
pub(super) fn cache_expression_value( |
| 414 |
&mut self, |
| 415 |
expr_handle: Handle<crate::Expression>, |
| 416 |
block: &mut Block, |
| 417 |
) -> Result<(), Error> { |
| 418 |
let is_named_expression = self |
| 419 |
.ir_function |
| 420 |
.named_expressions |
| 421 |
.contains_key(&expr_handle); |
| 422 |
|
| 423 |
if self.fun_info[expr_handle].ref_count == 0 && !is_named_expression { |
| 424 |
return Ok(()); |
| 425 |
} |
| 426 |
|
| 427 |
let result_type_id = self.get_expression_type_id(&self.fun_info[expr_handle].ty); |
| 428 |
let id = match self.ir_function.expressions[expr_handle] { |
| 429 |
crate::Expression::Literal(literal) => self.writer.get_constant_scalar(literal), |
| 430 |
crate::Expression::Constant(handle) => { |
| 431 |
let init = self.ir_module.constants[handle].init; |
| 432 |
self.writer.constant_ids[init] |
| 433 |
} |
| 434 |
crate::Expression::Override(_) => return Err(Error::Override), |
| 435 |
crate::Expression::ZeroValue(_) => self.writer.get_constant_null(result_type_id), |
| 436 |
crate::Expression::Compose { ty, ref components } => { |
| 437 |
self.temp_list.clear(); |
| 438 |
if self.expression_constness.is_const(expr_handle) { |
| 439 |
self.temp_list.extend( |
| 440 |
crate::proc::flatten_compose( |
| 441 |
ty, |
| 442 |
components, |
| 443 |
&self.ir_function.expressions, |
| 444 |
&self.ir_module.types, |
| 445 |
) |
| 446 |
.map(|component| self.cached[component]), |
| 447 |
); |
| 448 |
self.writer |
| 449 |
.get_constant_composite(LookupType::Handle(ty), &self.temp_list) |
| 450 |
} else { |
| 451 |
self.temp_list |
| 452 |
.extend(components.iter().map(|&component| self.cached[component])); |
| 453 |
|
| 454 |
let id = self.gen_id(); |
| 455 |
block.body.push(Instruction::composite_construct( |
| 456 |
result_type_id, |
| 457 |
id, |
| 458 |
&self.temp_list, |
| 459 |
)); |
| 460 |
id |
| 461 |
} |
| 462 |
} |
| 463 |
crate::Expression::Splat { size, value } => { |
| 464 |
let value_id = self.cached[value]; |
| 465 |
let components = &[value_id; 4][..size as usize]; |
| 466 |
|
| 467 |
if self.expression_constness.is_const(expr_handle) { |
| 468 |
let ty = self |
| 469 |
.writer |
| 470 |
.get_expression_lookup_type(&self.fun_info[expr_handle].ty); |
| 471 |
self.writer.get_constant_composite(ty, components) |
| 472 |
} else { |
| 473 |
let id = self.gen_id(); |
| 474 |
block.body.push(Instruction::composite_construct( |
| 475 |
result_type_id, |
| 476 |
id, |
| 477 |
components, |
| 478 |
)); |
| 479 |
id |
| 480 |
} |
| 481 |
} |
| 482 |
crate::Expression::Access { base, index } => { |
| 483 |
let base_ty_inner = self.fun_info[base].ty.inner_with(&self.ir_module.types); |
| 484 |
match *base_ty_inner { |
| 485 |
crate::TypeInner::Pointer { .. } | crate::TypeInner::ValuePointer { .. } => { |
| 486 |
// When we have a chain of `Access` and `AccessIndex` expressions |
| 487 |
// operating on pointers, we want to generate a single |
| 488 |
// `OpAccessChain` instruction for the whole chain. Put off |
| 489 |
// generating any code for this until we find the `Expression` |
| 490 |
// that actually dereferences the pointer. |
| 491 |
0 |
| 492 |
} |
| 493 |
_ if self.function.spilled_accesses.contains(base) => { |
| 494 |
// As far as Naga IR is concerned, this expression does not yield |
| 495 |
// a pointer (we just checked, above), but this backend spilled it |
| 496 |
// to a temporary variable, so SPIR-V thinks we're accessing it |
| 497 |
// via a pointer. |
| 498 |
|
| 499 |
// Since the base expression was spilled, mark this access to it |
| 500 |
// as spilled, too. |
| 501 |
self.function.spilled_accesses.insert(expr_handle); |
| 502 |
self.maybe_access_spilled_composite(expr_handle, block, result_type_id)? |
| 503 |
} |
| 504 |
crate::TypeInner::Vector { .. } => { |
| 505 |
self.write_vector_access(expr_handle, base, index, block)? |
| 506 |
} |
| 507 |
crate::TypeInner::Array { .. } | crate::TypeInner::Matrix { .. } => { |
| 508 |
// See if `index` is known at compile time. |
| 509 |
match GuardedIndex::from_expression( |
| 510 |
index, |
| 511 |
&self.ir_function.expressions, |
| 512 |
self.ir_module, |
| 513 |
) { |
| 514 |
GuardedIndex::Known(value) => { |
| 515 |
// If `index` is known and in bounds, we can just use |
| 516 |
// `OpCompositeExtract`. |
| 517 |
// |
| 518 |
// At the moment, validation rejects programs if this |
| 519 |
// index is out of bounds, so we don't need bounds checks. |
| 520 |
// However, that rejection is incorrect, since WGSL says |
| 521 |
// that `let` bindings are not constant expressions |
| 522 |
// (#6396). So eventually we will need to emulate bounds |
| 523 |
// checks here. |
| 524 |
let id = self.gen_id(); |
| 525 |
let base_id = self.cached[base]; |
| 526 |
block.body.push(Instruction::composite_extract( |
| 527 |
result_type_id, |
| 528 |
id, |
| 529 |
base_id, |
| 530 |
&[value], |
| 531 |
)); |
| 532 |
id |
| 533 |
} |
| 534 |
GuardedIndex::Expression(_) => { |
| 535 |
// We are subscripting an array or matrix that is not |
| 536 |
// behind a pointer, using an index computed at runtime. |
| 537 |
// SPIR-V has no instructions that do this, so the best we |
| 538 |
// can do is spill the value to a new temporary variable, |
| 539 |
// at which point we can get a pointer to that and just |
| 540 |
// use `OpAccessChain` in the usual way. |
| 541 |
self.spill_to_internal_variable(base, block); |
| 542 |
|
| 543 |
// Since the base was spilled, mark this access to it as |
| 544 |
// spilled, too. |
| 545 |
self.function.spilled_accesses.insert(expr_handle); |
| 546 |
self.maybe_access_spilled_composite( |
| 547 |
expr_handle, |
| 548 |
block, |
| 549 |
result_type_id, |
| 550 |
)? |
| 551 |
} |
| 552 |
} |
| 553 |
} |
| 554 |
crate::TypeInner::BindingArray { |
| 555 |
base: binding_type, .. |
| 556 |
} => { |
| 557 |
// Only binding arrays in the `Handle` address space will take |
| 558 |
// this path, since we handled the `Pointer` case above. |
| 559 |
let result_id = match self.write_access_chain( |
| 560 |
expr_handle, |
| 561 |
block, |
| 562 |
AccessTypeAdjustment::IntroducePointer( |
| 563 |
spirv::StorageClass::UniformConstant, |
| 564 |
), |
| 565 |
)? { |
| 566 |
ExpressionPointer::Ready { pointer_id } => pointer_id, |
| 567 |
ExpressionPointer::Conditional { .. } => { |
| 568 |
return Err(Error::FeatureNotImplemented( |
| 569 |
"Texture array out-of-bounds handling", |
| 570 |
)); |
| 571 |
} |
| 572 |
}; |
| 573 |
|
| 574 |
let binding_type_id = self.get_handle_type_id(binding_type); |
| 575 |
|
| 576 |
let load_id = self.gen_id(); |
| 577 |
block.body.push(Instruction::load( |
| 578 |
binding_type_id, |
| 579 |
load_id, |
| 580 |
result_id, |
| 581 |
None, |
| 582 |
)); |
| 583 |
|
| 584 |
// Subsequent image operations require the image/sampler to be decorated as NonUniform |
| 585 |
// if the image/sampler binding array was accessed with a non-uniform index |
| 586 |
// see VUID-RuntimeSpirv-NonUniform-06274 |
| 587 |
if self.fun_info[index].uniformity.non_uniform_result.is_some() { |
| 588 |
self.writer |
| 589 |
.decorate_non_uniform_binding_array_access(load_id)?; |
| 590 |
} |
| 591 |
|
| 592 |
load_id |
| 593 |
} |
| 594 |
ref other => { |
| 595 |
log::error!( |
| 596 |
"Unable to access base {:?} of type {:?}", |
| 597 |
self.ir_function.expressions[base], |
| 598 |
other |
| 599 |
); |
| 600 |
return Err(Error::Validation( |
| 601 |
"only vectors and arrays may be dynamically indexed by value", |
| 602 |
)); |
| 603 |
} |
| 604 |
} |
| 605 |
} |
| 606 |
crate::Expression::AccessIndex { base, index } => { |
| 607 |
match *self.fun_info[base].ty.inner_with(&self.ir_module.types) { |
| 608 |
crate::TypeInner::Pointer { .. } | crate::TypeInner::ValuePointer { .. } => { |
| 609 |
// When we have a chain of `Access` and `AccessIndex` expressions |
| 610 |
// operating on pointers, we want to generate a single |
| 611 |
// `OpAccessChain` instruction for the whole chain. Put off |
| 612 |
// generating any code for this until we find the `Expression` |
| 613 |
// that actually dereferences the pointer. |
| 614 |
0 |
| 615 |
} |
| 616 |
_ if self.function.spilled_accesses.contains(base) => { |
| 617 |
// As far as Naga IR is concerned, this expression does not yield |
| 618 |
// a pointer (we just checked, above), but this backend spilled it |
| 619 |
// to a temporary variable, so SPIR-V thinks we're accessing it |
| 620 |
// via a pointer. |
| 621 |
|
| 622 |
// Since the base expression was spilled, mark this access to it |
| 623 |
// as spilled, too. |
| 624 |
self.function.spilled_accesses.insert(expr_handle); |
| 625 |
self.maybe_access_spilled_composite(expr_handle, block, result_type_id)? |
| 626 |
} |
| 627 |
crate::TypeInner::Vector { .. } |
| 628 |
| crate::TypeInner::Matrix { .. } |
| 629 |
| crate::TypeInner::Array { .. } |
| 630 |
| crate::TypeInner::Struct { .. } => { |
| 631 |
// We never need bounds checks here: dynamically sized arrays can |
| 632 |
// only appear behind pointers, and are thus handled by the |
| 633 |
// `is_intermediate` case above. Everything else's size is |
| 634 |
// statically known and checked in validation. |
| 635 |
let id = self.gen_id(); |
| 636 |
let base_id = self.cached[base]; |
| 637 |
block.body.push(Instruction::composite_extract( |
| 638 |
result_type_id, |
| 639 |
id, |
| 640 |
base_id, |
| 641 |
&[index], |
| 642 |
)); |
| 643 |
id |
| 644 |
} |
| 645 |
crate::TypeInner::BindingArray { |
| 646 |
base: binding_type, .. |
| 647 |
} => { |
| 648 |
// Only binding arrays in the `Handle` address space will take |
| 649 |
// this path, since we handled the `Pointer` case above. |
| 650 |
let result_id = match self.write_access_chain( |
| 651 |
expr_handle, |
| 652 |
block, |
| 653 |
AccessTypeAdjustment::IntroducePointer( |
| 654 |
spirv::StorageClass::UniformConstant, |
| 655 |
), |
| 656 |
)? { |
| 657 |
ExpressionPointer::Ready { pointer_id } => pointer_id, |
| 658 |
ExpressionPointer::Conditional { .. } => { |
| 659 |
return Err(Error::FeatureNotImplemented( |
| 660 |
"Texture array out-of-bounds handling", |
| 661 |
)); |
| 662 |
} |
| 663 |
}; |
| 664 |
|
| 665 |
let binding_type_id = self.get_handle_type_id(binding_type); |
| 666 |
|
| 667 |
let load_id = self.gen_id(); |
| 668 |
block.body.push(Instruction::load( |
| 669 |
binding_type_id, |
| 670 |
load_id, |
| 671 |
result_id, |
| 672 |
None, |
| 673 |
)); |
| 674 |
|
| 675 |
load_id |
| 676 |
} |
| 677 |
ref other => { |
| 678 |
log::error!("Unable to access index of {:?}", other); |
| 679 |
return Err(Error::FeatureNotImplemented("access index for type")); |
| 680 |
} |
| 681 |
} |
| 682 |
} |
| 683 |
crate::Expression::GlobalVariable(handle) => { |
| 684 |
self.writer.global_variables[handle].access_id |
| 685 |
} |
| 686 |
crate::Expression::Swizzle { |
| 687 |
size, |
| 688 |
vector, |
| 689 |
pattern, |
| 690 |
} => { |
| 691 |
let vector_id = self.cached[vector]; |
| 692 |
self.temp_list.clear(); |
| 693 |
for &sc in pattern[..size as usize].iter() { |
| 694 |
self.temp_list.push(sc as Word); |
| 695 |
} |
| 696 |
let id = self.gen_id(); |
| 697 |
block.body.push(Instruction::vector_shuffle( |
| 698 |
result_type_id, |
| 699 |
id, |
| 700 |
vector_id, |
| 701 |
vector_id, |
| 702 |
&self.temp_list, |
| 703 |
)); |
| 704 |
id |
| 705 |
} |
| 706 |
crate::Expression::Unary { op, expr } => { |
| 707 |
let id = self.gen_id(); |
| 708 |
let expr_id = self.cached[expr]; |
| 709 |
let expr_ty_inner = self.fun_info[expr].ty.inner_with(&self.ir_module.types); |
| 710 |
|
| 711 |
let spirv_op = match op { |
| 712 |
crate::UnaryOperator::Negate => match expr_ty_inner.scalar_kind() { |
| 713 |
Some(crate::ScalarKind::Float) => spirv::Op::FNegate, |
| 714 |
Some(crate::ScalarKind::Sint) => spirv::Op::SNegate, |
| 715 |
_ => return Err(Error::Validation("Unexpected kind for negation")), |
| 716 |
}, |
| 717 |
crate::UnaryOperator::LogicalNot => spirv::Op::LogicalNot, |
| 718 |
crate::UnaryOperator::BitwiseNot => spirv::Op::Not, |
| 719 |
}; |
| 720 |
|
| 721 |
block |
| 722 |
.body |
| 723 |
.push(Instruction::unary(spirv_op, result_type_id, id, expr_id)); |
| 724 |
id |
| 725 |
} |
| 726 |
crate::Expression::Binary { op, left, right } => { |
| 727 |
let id = self.gen_id(); |
| 728 |
let left_id = self.cached[left]; |
| 729 |
let right_id = self.cached[right]; |
| 730 |
let left_type_id = self.get_expression_type_id(&self.fun_info[left].ty); |
| 731 |
let right_type_id = self.get_expression_type_id(&self.fun_info[right].ty); |
| 732 |
|
| 733 |
if let Some(function_id) = |
| 734 |
self.writer |
| 735 |
.wrapped_functions |
| 736 |
.get(&WrappedFunction::BinaryOp { |
| 737 |
op, |
| 738 |
left_type_id, |
| 739 |
right_type_id, |
| 740 |
}) |
| 741 |
{ |
| 742 |
block.body.push(Instruction::function_call( |
| 743 |
result_type_id, |
| 744 |
id, |
| 745 |
*function_id, |
| 746 |
&[left_id, right_id], |
| 747 |
)); |
| 748 |
} else { |
| 749 |
let left_ty_inner = self.fun_info[left].ty.inner_with(&self.ir_module.types); |
| 750 |
let right_ty_inner = self.fun_info[right].ty.inner_with(&self.ir_module.types); |
| 751 |
|
| 752 |
let left_dimension = get_dimension(left_ty_inner); |
| 753 |
let right_dimension = get_dimension(right_ty_inner); |
| 754 |
|
| 755 |
let mut reverse_operands = false; |
| 756 |
|
| 757 |
let spirv_op = match op { |
| 758 |
crate::BinaryOperator::Add => match *left_ty_inner { |
| 759 |
crate::TypeInner::Scalar(scalar) |
| 760 |
| crate::TypeInner::Vector { scalar, .. } => match scalar.kind { |
| 761 |
crate::ScalarKind::Float => spirv::Op::FAdd, |
| 762 |
_ => spirv::Op::IAdd, |
| 763 |
}, |
| 764 |
crate::TypeInner::Matrix { |
| 765 |
columns, |
| 766 |
rows, |
| 767 |
scalar, |
| 768 |
} => { |
| 769 |
self.write_matrix_matrix_column_op( |
| 770 |
block, |
| 771 |
id, |
| 772 |
result_type_id, |
| 773 |
left_id, |
| 774 |
right_id, |
| 775 |
columns, |
| 776 |
rows, |
| 777 |
scalar.width, |
| 778 |
spirv::Op::FAdd, |
| 779 |
); |
| 780 |
|
| 781 |
self.cached[expr_handle] = id; |
| 782 |
return Ok(()); |
| 783 |
} |
| 784 |
_ => unimplemented!(), |
| 785 |
}, |
| 786 |
crate::BinaryOperator::Subtract => match *left_ty_inner { |
| 787 |
crate::TypeInner::Scalar(scalar) |
| 788 |
| crate::TypeInner::Vector { scalar, .. } => match scalar.kind { |
| 789 |
crate::ScalarKind::Float => spirv::Op::FSub, |
| 790 |
_ => spirv::Op::ISub, |
| 791 |
}, |
| 792 |
crate::TypeInner::Matrix { |
| 793 |
columns, |
| 794 |
rows, |
| 795 |
scalar, |
| 796 |
} => { |
| 797 |
self.write_matrix_matrix_column_op( |
| 798 |
block, |
| 799 |
id, |
| 800 |
result_type_id, |
| 801 |
left_id, |
| 802 |
right_id, |
| 803 |
columns, |
| 804 |
rows, |
| 805 |
scalar.width, |
| 806 |
spirv::Op::FSub, |
| 807 |
); |
| 808 |
|
| 809 |
self.cached[expr_handle] = id; |
| 810 |
return Ok(()); |
| 811 |
} |
| 812 |
_ => unimplemented!(), |
| 813 |
}, |
| 814 |
crate::BinaryOperator::Multiply => { |
| 815 |
match (left_dimension, right_dimension) { |
| 816 |
(Dimension::Scalar, Dimension::Vector) => { |
| 817 |
self.write_vector_scalar_mult( |
| 818 |
block, |
| 819 |
id, |
| 820 |
result_type_id, |
| 821 |
right_id, |
| 822 |
left_id, |
| 823 |
right_ty_inner, |
| 824 |
); |
| 825 |
|
| 826 |
self.cached[expr_handle] = id; |
| 827 |
return Ok(()); |
| 828 |
} |
| 829 |
(Dimension::Vector, Dimension::Scalar) => { |
| 830 |
self.write_vector_scalar_mult( |
| 831 |
block, |
| 832 |
id, |
| 833 |
result_type_id, |
| 834 |
left_id, |
| 835 |
right_id, |
| 836 |
left_ty_inner, |
| 837 |
); |
| 838 |
|
| 839 |
self.cached[expr_handle] = id; |
| 840 |
return Ok(()); |
| 841 |
} |
| 842 |
(Dimension::Vector, Dimension::Matrix) => { |
| 843 |
spirv::Op::VectorTimesMatrix |
| 844 |
} |
| 845 |
(Dimension::Matrix, Dimension::Scalar) => { |
| 846 |
spirv::Op::MatrixTimesScalar |
| 847 |
} |
| 848 |
(Dimension::Scalar, Dimension::Matrix) => { |
| 849 |
reverse_operands = true; |
| 850 |
spirv::Op::MatrixTimesScalar |
| 851 |
} |
| 852 |
(Dimension::Matrix, Dimension::Vector) => { |
| 853 |
spirv::Op::MatrixTimesVector |
| 854 |
} |
| 855 |
(Dimension::Matrix, Dimension::Matrix) => { |
| 856 |
spirv::Op::MatrixTimesMatrix |
| 857 |
} |
| 858 |
(Dimension::Vector, Dimension::Vector) |
| 859 |
| (Dimension::Scalar, Dimension::Scalar) |
| 860 |
if left_ty_inner.scalar_kind() |
| 861 |
== Some(crate::ScalarKind::Float) => |
| 862 |
{ |
| 863 |
spirv::Op::FMul |
| 864 |
} |
| 865 |
(Dimension::Vector, Dimension::Vector) |
| 866 |
| (Dimension::Scalar, Dimension::Scalar) => spirv::Op::IMul, |
| 867 |
} |
| 868 |
} |
| 869 |
crate::BinaryOperator::Divide => match left_ty_inner.scalar_kind() { |
| 870 |
Some(crate::ScalarKind::Sint) => spirv::Op::SDiv, |
| 871 |
Some(crate::ScalarKind::Uint) => spirv::Op::UDiv, |
| 872 |
Some(crate::ScalarKind::Float) => spirv::Op::FDiv, |
| 873 |
_ => unimplemented!(), |
| 874 |
}, |
| 875 |
crate::BinaryOperator::Modulo => match left_ty_inner.scalar_kind() { |
| 876 |
// TODO: handle undefined behavior |
| 877 |
// if right == 0 return ? see https://github.com/gpuweb/gpuweb/issues/2798 |
| 878 |
Some(crate::ScalarKind::Float) => spirv::Op::FRem, |
| 879 |
Some(crate::ScalarKind::Sint | crate::ScalarKind::Uint) => { |
| 880 |
unreachable!("Should have been handled by wrapped function") |
| 881 |
} |
| 882 |
_ => unimplemented!(), |
| 883 |
}, |
| 884 |
crate::BinaryOperator::Equal => match left_ty_inner.scalar_kind() { |
| 885 |
Some(crate::ScalarKind::Sint | crate::ScalarKind::Uint) => { |
| 886 |
spirv::Op::IEqual |
| 887 |
} |
| 888 |
Some(crate::ScalarKind::Float) => spirv::Op::FOrdEqual, |
| 889 |
Some(crate::ScalarKind::Bool) => spirv::Op::LogicalEqual, |
| 890 |
_ => unimplemented!(), |
| 891 |
}, |
| 892 |
crate::BinaryOperator::NotEqual => match left_ty_inner.scalar_kind() { |
| 893 |
Some(crate::ScalarKind::Sint | crate::ScalarKind::Uint) => { |
| 894 |
spirv::Op::INotEqual |
| 895 |
} |
| 896 |
Some(crate::ScalarKind::Float) => spirv::Op::FOrdNotEqual, |
| 897 |
Some(crate::ScalarKind::Bool) => spirv::Op::LogicalNotEqual, |
| 898 |
_ => unimplemented!(), |
| 899 |
}, |
| 900 |
crate::BinaryOperator::Less => match left_ty_inner.scalar_kind() { |
| 901 |
Some(crate::ScalarKind::Sint) => spirv::Op::SLessThan, |
| 902 |
Some(crate::ScalarKind::Uint) => spirv::Op::ULessThan, |
| 903 |
Some(crate::ScalarKind::Float) => spirv::Op::FOrdLessThan, |
| 904 |
_ => unimplemented!(), |
| 905 |
}, |
| 906 |
crate::BinaryOperator::LessEqual => match left_ty_inner.scalar_kind() { |
| 907 |
Some(crate::ScalarKind::Sint) => spirv::Op::SLessThanEqual, |
| 908 |
Some(crate::ScalarKind::Uint) => spirv::Op::ULessThanEqual, |
| 909 |
Some(crate::ScalarKind::Float) => spirv::Op::FOrdLessThanEqual, |
| 910 |
_ => unimplemented!(), |
| 911 |
}, |
| 912 |
crate::BinaryOperator::Greater => match left_ty_inner.scalar_kind() { |
| 913 |
Some(crate::ScalarKind::Sint) => spirv::Op::SGreaterThan, |
| 914 |
Some(crate::ScalarKind::Uint) => spirv::Op::UGreaterThan, |
| 915 |
Some(crate::ScalarKind::Float) => spirv::Op::FOrdGreaterThan, |
| 916 |
_ => unimplemented!(), |
| 917 |
}, |
| 918 |
crate::BinaryOperator::GreaterEqual => match left_ty_inner.scalar_kind() { |
| 919 |
Some(crate::ScalarKind::Sint) => spirv::Op::SGreaterThanEqual, |
| 920 |
Some(crate::ScalarKind::Uint) => spirv::Op::UGreaterThanEqual, |
| 921 |
Some(crate::ScalarKind::Float) => spirv::Op::FOrdGreaterThanEqual, |
| 922 |
_ => unimplemented!(), |
| 923 |
}, |
| 924 |
crate::BinaryOperator::And => match left_ty_inner.scalar_kind() { |
| 925 |
Some(crate::ScalarKind::Bool) => spirv::Op::LogicalAnd, |
| 926 |
_ => spirv::Op::BitwiseAnd, |
| 927 |
}, |
| 928 |
crate::BinaryOperator::ExclusiveOr => spirv::Op::BitwiseXor, |
| 929 |
crate::BinaryOperator::InclusiveOr => match left_ty_inner.scalar_kind() { |
| 930 |
Some(crate::ScalarKind::Bool) => spirv::Op::LogicalOr, |
| 931 |
_ => spirv::Op::BitwiseOr, |
| 932 |
}, |
| 933 |
crate::BinaryOperator::LogicalAnd => spirv::Op::LogicalAnd, |
| 934 |
crate::BinaryOperator::LogicalOr => spirv::Op::LogicalOr, |
| 935 |
crate::BinaryOperator::ShiftLeft => spirv::Op::ShiftLeftLogical, |
| 936 |
crate::BinaryOperator::ShiftRight => match left_ty_inner.scalar_kind() { |
| 937 |
Some(crate::ScalarKind::Sint) => spirv::Op::ShiftRightArithmetic, |
| 938 |
Some(crate::ScalarKind::Uint) => spirv::Op::ShiftRightLogical, |
| 939 |
_ => unimplemented!(), |
| 940 |
}, |
| 941 |
}; |
| 942 |
|
| 943 |
block.body.push(Instruction::binary( |
| 944 |
spirv_op, |
| 945 |
result_type_id, |
| 946 |
id, |
| 947 |
if reverse_operands { right_id } else { left_id }, |
| 948 |
if reverse_operands { left_id } else { right_id }, |
| 949 |
)); |
| 950 |
} |
| 951 |
id |
| 952 |
} |
| 953 |
crate::Expression::Math { |
| 954 |
fun, |
| 955 |
arg, |
| 956 |
arg1, |
| 957 |
arg2, |
| 958 |
arg3, |
| 959 |
} => { |
| 960 |
use crate::MathFunction as Mf; |
| 961 |
enum MathOp { |
| 962 |
Ext(spirv::GLOp), |
| 963 |
Custom(Instruction), |
| 964 |
} |
| 965 |
|
| 966 |
let arg0_id = self.cached[arg]; |
| 967 |
let arg_ty = self.fun_info[arg].ty.inner_with(&self.ir_module.types); |
| 968 |
let arg_scalar_kind = arg_ty.scalar_kind(); |
| 969 |
let arg1_id = match arg1 { |
| 970 |
Some(handle) => self.cached[handle], |
| 971 |
None => 0, |
| 972 |
}; |
| 973 |
let arg2_id = match arg2 { |
| 974 |
Some(handle) => self.cached[handle], |
| 975 |
None => 0, |
| 976 |
}; |
| 977 |
let arg3_id = match arg3 { |
| 978 |
Some(handle) => self.cached[handle], |
| 979 |
None => 0, |
| 980 |
}; |
| 981 |
|
| 982 |
let id = self.gen_id(); |
| 983 |
let math_op = match fun { |
| 984 |
// comparison |
| 985 |
Mf::Abs => { |
| 986 |
match arg_scalar_kind { |
| 987 |
Some(crate::ScalarKind::Float) => MathOp::Ext(spirv::GLOp::FAbs), |
| 988 |
Some(crate::ScalarKind::Sint) => MathOp::Ext(spirv::GLOp::SAbs), |
| 989 |
Some(crate::ScalarKind::Uint) => { |
| 990 |
MathOp::Custom(Instruction::unary( |
| 991 |
spirv::Op::CopyObject, // do nothing |
| 992 |
result_type_id, |
| 993 |
id, |
| 994 |
arg0_id, |
| 995 |
)) |
| 996 |
} |
| 997 |
other => unimplemented!("Unexpected abs({:?})", other), |
| 998 |
} |
| 999 |
} |
| 1000 |
Mf::Min => MathOp::Ext(match arg_scalar_kind { |
| 1001 |
Some(crate::ScalarKind::Float) => spirv::GLOp::FMin, |
| 1002 |
Some(crate::ScalarKind::Sint) => spirv::GLOp::SMin, |
| 1003 |
Some(crate::ScalarKind::Uint) => spirv::GLOp::UMin, |
| 1004 |
other => unimplemented!("Unexpected min({:?})", other), |
| 1005 |
}), |
| 1006 |
Mf::Max => MathOp::Ext(match arg_scalar_kind { |
| 1007 |
Some(crate::ScalarKind::Float) => spirv::GLOp::FMax, |
| 1008 |
Some(crate::ScalarKind::Sint) => spirv::GLOp::SMax, |
| 1009 |
Some(crate::ScalarKind::Uint) => spirv::GLOp::UMax, |
| 1010 |
other => unimplemented!("Unexpected max({:?})", other), |
| 1011 |
}), |
| 1012 |
Mf::Clamp => match arg_scalar_kind { |
| 1013 |
// Clamp is undefined if min > max. In practice this means it can use a median-of-three |
| 1014 |
// instruction to determine the value. This is fine according to the WGSL spec for float |
| 1015 |
// clamp, but integer clamp _must_ use min-max. As such we write out min/max. |
| 1016 |
Some(crate::ScalarKind::Float) => MathOp::Ext(spirv::GLOp::FClamp), |
| 1017 |
Some(_) => { |
| 1018 |
let (min_op, max_op) = match arg_scalar_kind { |
| 1019 |
Some(crate::ScalarKind::Sint) => { |
| 1020 |
(spirv::GLOp::SMin, spirv::GLOp::SMax) |
| 1021 |
} |
| 1022 |
Some(crate::ScalarKind::Uint) => { |
| 1023 |
(spirv::GLOp::UMin, spirv::GLOp::UMax) |
| 1024 |
} |
| 1025 |
_ => unreachable!(), |
| 1026 |
}; |
| 1027 |
|
| 1028 |
let max_id = self.gen_id(); |
| 1029 |
block.body.push(Instruction::ext_inst( |
| 1030 |
self.writer.gl450_ext_inst_id, |
| 1031 |
max_op, |
| 1032 |
result_type_id, |
| 1033 |
max_id, |
| 1034 |
&[arg0_id, arg1_id], |
| 1035 |
)); |
| 1036 |
|
| 1037 |
MathOp::Custom(Instruction::ext_inst( |
| 1038 |
self.writer.gl450_ext_inst_id, |
| 1039 |
min_op, |
| 1040 |
result_type_id, |
| 1041 |
id, |
| 1042 |
&[max_id, arg2_id], |
| 1043 |
)) |
| 1044 |
} |
| 1045 |
other => unimplemented!("Unexpected max({:?})", other), |
| 1046 |
}, |
| 1047 |
Mf::Saturate => { |
| 1048 |
let (maybe_size, scalar) = match *arg_ty { |
| 1049 |
crate::TypeInner::Vector { size, scalar } => (Some(size), scalar), |
| 1050 |
crate::TypeInner::Scalar(scalar) => (None, scalar), |
| 1051 |
ref other => unimplemented!("Unexpected saturate({:?})", other), |
| 1052 |
}; |
| 1053 |
let scalar = crate::Scalar::float(scalar.width); |
| 1054 |
let mut arg1_id = self.writer.get_constant_scalar_with(0, scalar)?; |
| 1055 |
let mut arg2_id = self.writer.get_constant_scalar_with(1, scalar)?; |
| 1056 |
|
| 1057 |
if let Some(size) = maybe_size { |
| 1058 |
let ty = |
| 1059 |
LocalType::Numeric(NumericType::Vector { size, scalar }).into(); |
| 1060 |
|
| 1061 |
self.temp_list.clear(); |
| 1062 |
self.temp_list.resize(size as _, arg1_id); |
| 1063 |
|
| 1064 |
arg1_id = self.writer.get_constant_composite(ty, &self.temp_list); |
| 1065 |
|
| 1066 |
self.temp_list.fill(arg2_id); |
| 1067 |
|
| 1068 |
arg2_id = self.writer.get_constant_composite(ty, &self.temp_list); |
| 1069 |
} |
| 1070 |
|
| 1071 |
MathOp::Custom(Instruction::ext_inst( |
| 1072 |
self.writer.gl450_ext_inst_id, |
| 1073 |
spirv::GLOp::FClamp, |
| 1074 |
result_type_id, |
| 1075 |
id, |
| 1076 |
&[arg0_id, arg1_id, arg2_id], |
| 1077 |
)) |
| 1078 |
} |
| 1079 |
// trigonometry |
| 1080 |
Mf::Sin => MathOp::Ext(spirv::GLOp::Sin), |
| 1081 |
Mf::Sinh => MathOp::Ext(spirv::GLOp::Sinh), |
| 1082 |
Mf::Asin => MathOp::Ext(spirv::GLOp::Asin), |
| 1083 |
Mf::Cos => MathOp::Ext(spirv::GLOp::Cos), |
| 1084 |
Mf::Cosh => MathOp::Ext(spirv::GLOp::Cosh), |
| 1085 |
Mf::Acos => MathOp::Ext(spirv::GLOp::Acos), |
| 1086 |
Mf::Tan => MathOp::Ext(spirv::GLOp::Tan), |
| 1087 |
Mf::Tanh => MathOp::Ext(spirv::GLOp::Tanh), |
| 1088 |
Mf::Atan => MathOp::Ext(spirv::GLOp::Atan), |
| 1089 |
Mf::Atan2 => MathOp::Ext(spirv::GLOp::Atan2), |
| 1090 |
Mf::Asinh => MathOp::Ext(spirv::GLOp::Asinh), |
| 1091 |
Mf::Acosh => MathOp::Ext(spirv::GLOp::Acosh), |
| 1092 |
Mf::Atanh => MathOp::Ext(spirv::GLOp::Atanh), |
| 1093 |
Mf::Radians => MathOp::Ext(spirv::GLOp::Radians), |
| 1094 |
Mf::Degrees => MathOp::Ext(spirv::GLOp::Degrees), |
| 1095 |
// decomposition |
| 1096 |
Mf::Ceil => MathOp::Ext(spirv::GLOp::Ceil), |
| 1097 |
Mf::Round => MathOp::Ext(spirv::GLOp::RoundEven), |
| 1098 |
Mf::Floor => MathOp::Ext(spirv::GLOp::Floor), |
| 1099 |
Mf::Fract => MathOp::Ext(spirv::GLOp::Fract), |
| 1100 |
Mf::Trunc => MathOp::Ext(spirv::GLOp::Trunc), |
| 1101 |
Mf::Modf => MathOp::Ext(spirv::GLOp::ModfStruct), |
| 1102 |
Mf::Frexp => MathOp::Ext(spirv::GLOp::FrexpStruct), |
| 1103 |
Mf::Ldexp => MathOp::Ext(spirv::GLOp::Ldexp), |
| 1104 |
// geometry |
| 1105 |
Mf::Dot => match *self.fun_info[arg].ty.inner_with(&self.ir_module.types) { |
| 1106 |
crate::TypeInner::Vector { |
| 1107 |
scalar: |
| 1108 |
crate::Scalar { |
| 1109 |
kind: crate::ScalarKind::Float, |
| 1110 |
.. |
| 1111 |
}, |
| 1112 |
.. |
| 1113 |
} => MathOp::Custom(Instruction::binary( |
| 1114 |
spirv::Op::Dot, |
| 1115 |
result_type_id, |
| 1116 |
id, |
| 1117 |
arg0_id, |
| 1118 |
arg1_id, |
| 1119 |
)), |
| 1120 |
// TODO: consider using integer dot product if VK_KHR_shader_integer_dot_product is available |
| 1121 |
crate::TypeInner::Vector { size, .. } => { |
| 1122 |
self.write_dot_product( |
| 1123 |
id, |
| 1124 |
result_type_id, |
| 1125 |
arg0_id, |
| 1126 |
arg1_id, |
| 1127 |
size as u32, |
| 1128 |
block, |
| 1129 |
|result_id, composite_id, index| { |
| 1130 |
Instruction::composite_extract( |
| 1131 |
result_type_id, |
| 1132 |
result_id, |
| 1133 |
composite_id, |
| 1134 |
&[index], |
| 1135 |
) |
| 1136 |
}, |
| 1137 |
); |
| 1138 |
self.cached[expr_handle] = id; |
| 1139 |
return Ok(()); |
| 1140 |
} |
| 1141 |
_ => unreachable!( |
| 1142 |
"Correct TypeInner for dot product should be already validated" |
| 1143 |
), |
| 1144 |
}, |
| 1145 |
fun @ (Mf::Dot4I8Packed | Mf::Dot4U8Packed) => { |
| 1146 |
if self |
| 1147 |
.writer |
| 1148 |
.require_all(&[ |
| 1149 |
spirv::Capability::DotProduct, |
| 1150 |
spirv::Capability::DotProductInput4x8BitPacked, |
| 1151 |
]) |
| 1152 |
.is_ok() |
| 1153 |
{ |
| 1154 |
// Write optimized code using `PackedVectorFormat4x8Bit`. |
| 1155 |
if self.writer.lang_version() < (1, 6) { |
| 1156 |
// SPIR-V 1.6 supports the required capabilities natively, so the extension |
| 1157 |
// is only required for earlier versions. See right column of |
| 1158 |
// <https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#OpSDot>. |
| 1159 |
self.writer.use_extension("SPV_KHR_integer_dot_product"); |
| 1160 |
} |
| 1161 |
|
| 1162 |
let op = match fun { |
| 1163 |
Mf::Dot4I8Packed => spirv::Op::SDot, |
| 1164 |
Mf::Dot4U8Packed => spirv::Op::UDot, |
| 1165 |
_ => unreachable!(), |
| 1166 |
}; |
| 1167 |
|
| 1168 |
block.body.push(Instruction::ternary( |
| 1169 |
op, |
| 1170 |
result_type_id, |
| 1171 |
id, |
| 1172 |
arg0_id, |
| 1173 |
arg1_id, |
| 1174 |
spirv::PackedVectorFormat::PackedVectorFormat4x8Bit as Word, |
| 1175 |
)); |
| 1176 |
} else { |
| 1177 |
// Fall back to a polyfill since `PackedVectorFormat4x8Bit` is not available. |
| 1178 |
let (extract_op, arg0_id, arg1_id) = match fun { |
| 1179 |
Mf::Dot4U8Packed => (spirv::Op::BitFieldUExtract, arg0_id, arg1_id), |
| 1180 |
Mf::Dot4I8Packed => { |
| 1181 |
// Convert both packed arguments to signed integers so that we can apply the |
| 1182 |
// `BitFieldSExtract` operation on them in `write_dot_product` below. |
| 1183 |
let new_arg0_id = self.gen_id(); |
| 1184 |
block.body.push(Instruction::unary( |
| 1185 |
spirv::Op::Bitcast, |
| 1186 |
result_type_id, |
| 1187 |
new_arg0_id, |
| 1188 |
arg0_id, |
| 1189 |
)); |
| 1190 |
|
| 1191 |
let new_arg1_id = self.gen_id(); |
| 1192 |
block.body.push(Instruction::unary( |
| 1193 |
spirv::Op::Bitcast, |
| 1194 |
result_type_id, |
| 1195 |
new_arg1_id, |
| 1196 |
arg1_id, |
| 1197 |
)); |
| 1198 |
|
| 1199 |
(spirv::Op::BitFieldSExtract, new_arg0_id, new_arg1_id) |
| 1200 |
} |
| 1201 |
_ => unreachable!(), |
| 1202 |
}; |
| 1203 |
|
| 1204 |
let eight = self.writer.get_constant_scalar(crate::Literal::U32(8)); |
| 1205 |
|
| 1206 |
const VEC_LENGTH: u8 = 4; |
| 1207 |
let bit_shifts: [_; VEC_LENGTH as usize] = |
| 1208 |
core::array::from_fn(|index| { |
| 1209 |
self.writer |
| 1210 |
.get_constant_scalar(crate::Literal::U32(index as u32 * 8)) |
| 1211 |
}); |
| 1212 |
|
| 1213 |
self.write_dot_product( |
| 1214 |
id, |
| 1215 |
result_type_id, |
| 1216 |
arg0_id, |
| 1217 |
arg1_id, |
| 1218 |
VEC_LENGTH as Word, |
| 1219 |
block, |
| 1220 |
|result_id, composite_id, index| { |
| 1221 |
Instruction::ternary( |
| 1222 |
extract_op, |
| 1223 |
result_type_id, |
| 1224 |
result_id, |
| 1225 |
composite_id, |
| 1226 |
bit_shifts[index as usize], |
| 1227 |
eight, |
| 1228 |
) |
| 1229 |
}, |
| 1230 |
); |
| 1231 |
} |
| 1232 |
|
| 1233 |
self.cached[expr_handle] = id; |
| 1234 |
return Ok(()); |
| 1235 |
} |
| 1236 |
Mf::Outer => MathOp::Custom(Instruction::binary( |
| 1237 |
spirv::Op::OuterProduct, |
| 1238 |
result_type_id, |
| 1239 |
id, |
| 1240 |
arg0_id, |
| 1241 |
arg1_id, |
| 1242 |
)), |
| 1243 |
Mf::Cross => MathOp::Ext(spirv::GLOp::Cross), |
| 1244 |
Mf::Distance => MathOp::Ext(spirv::GLOp::Distance), |
| 1245 |
Mf::Length => MathOp::Ext(spirv::GLOp::Length), |
| 1246 |
Mf::Normalize => MathOp::Ext(spirv::GLOp::Normalize), |
| 1247 |
Mf::FaceForward => MathOp::Ext(spirv::GLOp::FaceForward), |
| 1248 |
Mf::Reflect => MathOp::Ext(spirv::GLOp::Reflect), |
| 1249 |
Mf::Refract => MathOp::Ext(spirv::GLOp::Refract), |
| 1250 |
// exponent |
| 1251 |
Mf::Exp => MathOp::Ext(spirv::GLOp::Exp), |
| 1252 |
Mf::Exp2 => MathOp::Ext(spirv::GLOp::Exp2), |
| 1253 |
Mf::Log => MathOp::Ext(spirv::GLOp::Log), |
| 1254 |
Mf::Log2 => MathOp::Ext(spirv::GLOp::Log2), |
| 1255 |
Mf::Pow => MathOp::Ext(spirv::GLOp::Pow), |
| 1256 |
// computational |
| 1257 |
Mf::Sign => MathOp::Ext(match arg_scalar_kind { |
| 1258 |
Some(crate::ScalarKind::Float) => spirv::GLOp::FSign, |
| 1259 |
Some(crate::ScalarKind::Sint) => spirv::GLOp::SSign, |
| 1260 |
other => unimplemented!("Unexpected sign({:?})", other), |
| 1261 |
}), |
| 1262 |
Mf::Fma => MathOp::Ext(spirv::GLOp::Fma), |
| 1263 |
Mf::Mix => { |
| 1264 |
let selector = arg2.unwrap(); |
| 1265 |
let selector_ty = |
| 1266 |
self.fun_info[selector].ty.inner_with(&self.ir_module.types); |
| 1267 |
match (arg_ty, selector_ty) { |
| 1268 |
// if the selector is a scalar, we need to splat it |
| 1269 |
( |
| 1270 |
&crate::TypeInner::Vector { size, .. }, |
| 1271 |
&crate::TypeInner::Scalar(scalar), |
| 1272 |
) => { |
| 1273 |
let selector_type_id = |
| 1274 |
self.get_numeric_type_id(NumericType::Vector { size, scalar }); |
| 1275 |
self.temp_list.clear(); |
| 1276 |
self.temp_list.resize(size as usize, arg2_id); |
| 1277 |
|
| 1278 |
let selector_id = self.gen_id(); |
| 1279 |
block.body.push(Instruction::composite_construct( |
| 1280 |
selector_type_id, |
| 1281 |
selector_id, |
| 1282 |
&self.temp_list, |
| 1283 |
)); |
| 1284 |
|
| 1285 |
MathOp::Custom(Instruction::ext_inst( |
| 1286 |
self.writer.gl450_ext_inst_id, |
| 1287 |
spirv::GLOp::FMix, |
| 1288 |
result_type_id, |
| 1289 |
id, |
| 1290 |
&[arg0_id, arg1_id, selector_id], |
| 1291 |
)) |
| 1292 |
} |
| 1293 |
_ => MathOp::Ext(spirv::GLOp::FMix), |
| 1294 |
} |
| 1295 |
} |
| 1296 |
Mf::Step => MathOp::Ext(spirv::GLOp::Step), |
| 1297 |
Mf::SmoothStep => MathOp::Ext(spirv::GLOp::SmoothStep), |
| 1298 |
Mf::Sqrt => MathOp::Ext(spirv::GLOp::Sqrt), |
| 1299 |
Mf::InverseSqrt => MathOp::Ext(spirv::GLOp::InverseSqrt), |
| 1300 |
Mf::Inverse => MathOp::Ext(spirv::GLOp::MatrixInverse), |
| 1301 |
Mf::Transpose => MathOp::Custom(Instruction::unary( |
| 1302 |
spirv::Op::Transpose, |
| 1303 |
result_type_id, |
| 1304 |
id, |
| 1305 |
arg0_id, |
| 1306 |
)), |
| 1307 |
Mf::Determinant => MathOp::Ext(spirv::GLOp::Determinant), |
| 1308 |
Mf::QuantizeToF16 => MathOp::Custom(Instruction::unary( |
| 1309 |
spirv::Op::QuantizeToF16, |
| 1310 |
result_type_id, |
| 1311 |
id, |
| 1312 |
arg0_id, |
| 1313 |
)), |
| 1314 |
Mf::ReverseBits => MathOp::Custom(Instruction::unary( |
| 1315 |
spirv::Op::BitReverse, |
| 1316 |
result_type_id, |
| 1317 |
id, |
| 1318 |
arg0_id, |
| 1319 |
)), |
| 1320 |
Mf::CountTrailingZeros => { |
| 1321 |
let uint_id = match *arg_ty { |
| 1322 |
crate::TypeInner::Vector { size, scalar } => { |
| 1323 |
let ty = |
| 1324 |
LocalType::Numeric(NumericType::Vector { size, scalar }).into(); |
| 1325 |
|
| 1326 |
self.temp_list.clear(); |
| 1327 |
self.temp_list.resize( |
| 1328 |
size as _, |
| 1329 |
self.writer |
| 1330 |
.get_constant_scalar_with(scalar.width * 8, scalar)?, |
| 1331 |
); |
| 1332 |
|
| 1333 |
self.writer.get_constant_composite(ty, &self.temp_list) |
| 1334 |
} |
| 1335 |
crate::TypeInner::Scalar(scalar) => self |
| 1336 |
.writer |
| 1337 |
.get_constant_scalar_with(scalar.width * 8, scalar)?, |
| 1338 |
_ => unreachable!(), |
| 1339 |
}; |
| 1340 |
|
| 1341 |
let lsb_id = self.gen_id(); |
| 1342 |
block.body.push(Instruction::ext_inst( |
| 1343 |
self.writer.gl450_ext_inst_id, |
| 1344 |
spirv::GLOp::FindILsb, |
| 1345 |
result_type_id, |
| 1346 |
lsb_id, |
| 1347 |
&[arg0_id], |
| 1348 |
)); |
| 1349 |
|
| 1350 |
MathOp::Custom(Instruction::ext_inst( |
| 1351 |
self.writer.gl450_ext_inst_id, |
| 1352 |
spirv::GLOp::UMin, |
| 1353 |
result_type_id, |
| 1354 |
id, |
| 1355 |
&[uint_id, lsb_id], |
| 1356 |
)) |
| 1357 |
} |
| 1358 |
Mf::CountLeadingZeros => { |
| 1359 |
let (int_type_id, int_id, width) = match *arg_ty { |
| 1360 |
crate::TypeInner::Vector { size, scalar } => { |
| 1361 |
let ty = |
| 1362 |
LocalType::Numeric(NumericType::Vector { size, scalar }).into(); |
| 1363 |
|
| 1364 |
self.temp_list.clear(); |
| 1365 |
self.temp_list.resize( |
| 1366 |
size as _, |
| 1367 |
self.writer |
| 1368 |
.get_constant_scalar_with(scalar.width * 8 - 1, scalar)?, |
| 1369 |
); |
| 1370 |
|
| 1371 |
( |
| 1372 |
self.get_type_id(ty), |
| 1373 |
self.writer.get_constant_composite(ty, &self.temp_list), |
| 1374 |
scalar.width, |
| 1375 |
) |
| 1376 |
} |
| 1377 |
crate::TypeInner::Scalar(scalar) => ( |
| 1378 |
self.get_numeric_type_id(NumericType::Scalar(scalar)), |
| 1379 |
self.writer |
| 1380 |
.get_constant_scalar_with(scalar.width * 8 - 1, scalar)?, |
| 1381 |
scalar.width, |
| 1382 |
), |
| 1383 |
_ => unreachable!(), |
| 1384 |
}; |
| 1385 |
|
| 1386 |
if width != 4 { |
| 1387 |
unreachable!("This is validated out until a polyfill is implemented. https://github.com/gfx-rs/wgpu/issues/5276"); |
| 1388 |
}; |
| 1389 |
|
| 1390 |
let msb_id = self.gen_id(); |
| 1391 |
block.body.push(Instruction::ext_inst( |
| 1392 |
self.writer.gl450_ext_inst_id, |
| 1393 |
if width != 4 { |
| 1394 |
spirv::GLOp::FindILsb |
| 1395 |
} else { |
| 1396 |
spirv::GLOp::FindUMsb |
| 1397 |
}, |
| 1398 |
int_type_id, |
| 1399 |
msb_id, |
| 1400 |
&[arg0_id], |
| 1401 |
)); |
| 1402 |
|
| 1403 |
MathOp::Custom(Instruction::binary( |
| 1404 |
spirv::Op::ISub, |
| 1405 |
result_type_id, |
| 1406 |
id, |
| 1407 |
int_id, |
| 1408 |
msb_id, |
| 1409 |
)) |
| 1410 |
} |
| 1411 |
Mf::CountOneBits => MathOp::Custom(Instruction::unary( |
| 1412 |
spirv::Op::BitCount, |
| 1413 |
result_type_id, |
| 1414 |
id, |
| 1415 |
arg0_id, |
| 1416 |
)), |
| 1417 |
Mf::ExtractBits => { |
| 1418 |
let op = match arg_scalar_kind { |
| 1419 |
Some(crate::ScalarKind::Uint) => spirv::Op::BitFieldUExtract, |
| 1420 |
Some(crate::ScalarKind::Sint) => spirv::Op::BitFieldSExtract, |
| 1421 |
other => unimplemented!("Unexpected sign({:?})", other), |
| 1422 |
}; |
| 1423 |
|
| 1424 |
// The behavior of ExtractBits is undefined when offset + count > bit_width. We need |
| 1425 |
// to first sanitize the offset and count first. If we don't do this, AMD and Intel |
| 1426 |
// will return out-of-spec values if the extracted range is not within the bit width. |
| 1427 |
// |
| 1428 |
// This encodes the exact formula specified by the wgsl spec: |
| 1429 |
// https://gpuweb.github.io/gpuweb/wgsl/#extractBits-unsigned-builtin |
| 1430 |
// |
| 1431 |
// w = sizeof(x) * 8 |
| 1432 |
// o = min(offset, w) |
| 1433 |
// tmp = w - o |
| 1434 |
// c = min(count, tmp) |
| 1435 |
// |
| 1436 |
// bitfieldExtract(x, o, c) |
| 1437 |
|
| 1438 |
let bit_width = arg_ty.scalar_width().unwrap() * 8; |
| 1439 |
let width_constant = self |
| 1440 |
.writer |
| 1441 |
.get_constant_scalar(crate::Literal::U32(bit_width as u32)); |
| 1442 |
|
| 1443 |
let u32_type = |
| 1444 |
self.get_numeric_type_id(NumericType::Scalar(crate::Scalar::U32)); |
| 1445 |
|
| 1446 |
// o = min(offset, w) |
| 1447 |
let offset_id = self.gen_id(); |
| 1448 |
block.body.push(Instruction::ext_inst( |
| 1449 |
self.writer.gl450_ext_inst_id, |
| 1450 |
spirv::GLOp::UMin, |
| 1451 |
u32_type, |
| 1452 |
offset_id, |
| 1453 |
&[arg1_id, width_constant], |
| 1454 |
)); |
| 1455 |
|
| 1456 |
// tmp = w - o |
| 1457 |
let max_count_id = self.gen_id(); |
| 1458 |
block.body.push(Instruction::binary( |
| 1459 |
spirv::Op::ISub, |
| 1460 |
u32_type, |
| 1461 |
max_count_id, |
| 1462 |
width_constant, |
| 1463 |
offset_id, |
| 1464 |
)); |
| 1465 |
|
| 1466 |
// c = min(count, tmp) |
| 1467 |
let count_id = self.gen_id(); |
| 1468 |
block.body.push(Instruction::ext_inst( |
| 1469 |
self.writer.gl450_ext_inst_id, |
| 1470 |
spirv::GLOp::UMin, |
| 1471 |
u32_type, |
| 1472 |
count_id, |
| 1473 |
&[arg2_id, max_count_id], |
| 1474 |
)); |
| 1475 |
|
| 1476 |
MathOp::Custom(Instruction::ternary( |
| 1477 |
op, |
| 1478 |
result_type_id, |
| 1479 |
id, |
| 1480 |
arg0_id, |
| 1481 |
offset_id, |
| 1482 |
count_id, |
| 1483 |
)) |
| 1484 |
} |
| 1485 |
Mf::InsertBits => { |
| 1486 |
// The behavior of InsertBits has the same undefined behavior as ExtractBits. |
| 1487 |
|
| 1488 |
let bit_width = arg_ty.scalar_width().unwrap() * 8; |
| 1489 |
let width_constant = self |
| 1490 |
.writer |
| 1491 |
.get_constant_scalar(crate::Literal::U32(bit_width as u32)); |
| 1492 |
|
| 1493 |
let u32_type = |
| 1494 |
self.get_numeric_type_id(NumericType::Scalar(crate::Scalar::U32)); |
| 1495 |
|
| 1496 |
// o = min(offset, w) |
| 1497 |
let offset_id = self.gen_id(); |
| 1498 |
block.body.push(Instruction::ext_inst( |
| 1499 |
self.writer.gl450_ext_inst_id, |
| 1500 |
spirv::GLOp::UMin, |
| 1501 |
u32_type, |
| 1502 |
offset_id, |
| 1503 |
&[arg2_id, width_constant], |
| 1504 |
)); |
| 1505 |
|
| 1506 |
// tmp = w - o |
| 1507 |
let max_count_id = self.gen_id(); |
| 1508 |
block.body.push(Instruction::binary( |
| 1509 |
spirv::Op::ISub, |
| 1510 |
u32_type, |
| 1511 |
max_count_id, |
| 1512 |
width_constant, |
| 1513 |
offset_id, |
| 1514 |
)); |
| 1515 |
|
| 1516 |
// c = min(count, tmp) |
| 1517 |
let count_id = self.gen_id(); |
| 1518 |
block.body.push(Instruction::ext_inst( |
| 1519 |
self.writer.gl450_ext_inst_id, |
| 1520 |
spirv::GLOp::UMin, |
| 1521 |
u32_type, |
| 1522 |
count_id, |
| 1523 |
&[arg3_id, max_count_id], |
| 1524 |
)); |
| 1525 |
|
| 1526 |
MathOp::Custom(Instruction::quaternary( |
| 1527 |
spirv::Op::BitFieldInsert, |
| 1528 |
result_type_id, |
| 1529 |
id, |
| 1530 |
arg0_id, |
| 1531 |
arg1_id, |
| 1532 |
offset_id, |
| 1533 |
count_id, |
| 1534 |
)) |
| 1535 |
} |
| 1536 |
Mf::FirstTrailingBit => MathOp::Ext(spirv::GLOp::FindILsb), |
| 1537 |
Mf::FirstLeadingBit => { |
| 1538 |
if arg_ty.scalar_width() == Some(4) { |
| 1539 |
let thing = match arg_scalar_kind { |
| 1540 |
Some(crate::ScalarKind::Uint) => spirv::GLOp::FindUMsb, |
| 1541 |
Some(crate::ScalarKind::Sint) => spirv::GLOp::FindSMsb, |
| 1542 |
other => unimplemented!("Unexpected firstLeadingBit({:?})", other), |
| 1543 |
}; |
| 1544 |
MathOp::Ext(thing) |
| 1545 |
} else { |
| 1546 |
unreachable!("This is validated out until a polyfill is implemented. https://github.com/gfx-rs/wgpu/issues/5276"); |
| 1547 |
} |
| 1548 |
} |
| 1549 |
Mf::Pack4x8unorm => MathOp::Ext(spirv::GLOp::PackUnorm4x8), |
| 1550 |
Mf::Pack4x8snorm => MathOp::Ext(spirv::GLOp::PackSnorm4x8), |
| 1551 |
Mf::Pack2x16float => MathOp::Ext(spirv::GLOp::PackHalf2x16), |
| 1552 |
Mf::Pack2x16unorm => MathOp::Ext(spirv::GLOp::PackUnorm2x16), |
| 1553 |
Mf::Pack2x16snorm => MathOp::Ext(spirv::GLOp::PackSnorm2x16), |
| 1554 |
fun @ (Mf::Pack4xI8 | Mf::Pack4xU8 | Mf::Pack4xI8Clamp | Mf::Pack4xU8Clamp) => { |
| 1555 |
let (int_type, is_signed) = match fun { |
| 1556 |
Mf::Pack4xI8 | Mf::Pack4xI8Clamp => (crate::ScalarKind::Sint, true), |
| 1557 |
Mf::Pack4xU8 | Mf::Pack4xU8Clamp => (crate::ScalarKind::Uint, false), |
| 1558 |
_ => unreachable!(), |
| 1559 |
}; |
| 1560 |
let should_clamp = matches!(fun, Mf::Pack4xI8Clamp | Mf::Pack4xU8Clamp); |
| 1561 |
let uint_type_id = |
| 1562 |
self.get_numeric_type_id(NumericType::Scalar(crate::Scalar::U32)); |
| 1563 |
|
| 1564 |
let int_type_id = |
| 1565 |
self.get_numeric_type_id(NumericType::Scalar(crate::Scalar { |
| 1566 |
kind: int_type, |
| 1567 |
width: 4, |
| 1568 |
})); |
| 1569 |
|
| 1570 |
let mut last_instruction = Instruction::new(spirv::Op::Nop); |
| 1571 |
|
| 1572 |
let zero = self.writer.get_constant_scalar(crate::Literal::U32(0)); |
| 1573 |
let mut preresult = zero; |
| 1574 |
block |
| 1575 |
.body |
| 1576 |
.reserve(usize::from(VEC_LENGTH) * (2 + usize::from(is_signed))); |
| 1577 |
|
| 1578 |
let eight = self.writer.get_constant_scalar(crate::Literal::U32(8)); |
| 1579 |
const VEC_LENGTH: u8 = 4; |
| 1580 |
for i in 0..u32::from(VEC_LENGTH) { |
| 1581 |
let offset = |
| 1582 |
self.writer.get_constant_scalar(crate::Literal::U32(i * 8)); |
| 1583 |
let mut extracted = self.gen_id(); |
| 1584 |
block.body.push(Instruction::binary( |
| 1585 |
spirv::Op::CompositeExtract, |
| 1586 |
int_type_id, |
| 1587 |
extracted, |
| 1588 |
arg0_id, |
| 1589 |
i, |
| 1590 |
)); |
| 1591 |
if is_signed { |
| 1592 |
let casted = self.gen_id(); |
| 1593 |
block.body.push(Instruction::unary( |
| 1594 |
spirv::Op::Bitcast, |
| 1595 |
uint_type_id, |
| 1596 |
casted, |
| 1597 |
extracted, |
| 1598 |
)); |
| 1599 |
extracted = casted; |
| 1600 |
} |
| 1601 |
if should_clamp { |
| 1602 |
let (min, max, clamp_op) = if is_signed { |
| 1603 |
( |
| 1604 |
crate::Literal::I32(-128), |
| 1605 |
crate::Literal::I32(127), |
| 1606 |
spirv::GLOp::SClamp, |
| 1607 |
) |
| 1608 |
} else { |
| 1609 |
( |
| 1610 |
crate::Literal::U32(0), |
| 1611 |
crate::Literal::U32(255), |
| 1612 |
spirv::GLOp::UClamp, |
| 1613 |
) |
| 1614 |
}; |
| 1615 |
let [min, max] = |
| 1616 |
[min, max].map(|lit| self.writer.get_constant_scalar(lit)); |
| 1617 |
|
| 1618 |
let clamp_id = self.gen_id(); |
| 1619 |
block.body.push(Instruction::ext_inst( |
| 1620 |
self.writer.gl450_ext_inst_id, |
| 1621 |
clamp_op, |
| 1622 |
result_type_id, |
| 1623 |
clamp_id, |
| 1624 |
&[extracted, min, max], |
| 1625 |
)); |
| 1626 |
|
| 1627 |
extracted = clamp_id; |
| 1628 |
} |
| 1629 |
let is_last = i == u32::from(VEC_LENGTH - 1); |
| 1630 |
if is_last { |
| 1631 |
last_instruction = Instruction::quaternary( |
| 1632 |
spirv::Op::BitFieldInsert, |
| 1633 |
result_type_id, |
| 1634 |
id, |
| 1635 |
preresult, |
| 1636 |
extracted, |
| 1637 |
offset, |
| 1638 |
eight, |
| 1639 |
) |
| 1640 |
} else { |
| 1641 |
let new_preresult = self.gen_id(); |
| 1642 |
block.body.push(Instruction::quaternary( |
| 1643 |
spirv::Op::BitFieldInsert, |
| 1644 |
result_type_id, |
| 1645 |
new_preresult, |
| 1646 |
preresult, |
| 1647 |
extracted, |
| 1648 |
offset, |
| 1649 |
eight, |
| 1650 |
)); |
| 1651 |
preresult = new_preresult; |
| 1652 |
} |
| 1653 |
} |
| 1654 |
|
| 1655 |
MathOp::Custom(last_instruction) |
| 1656 |
} |
| 1657 |
Mf::Unpack4x8unorm => MathOp::Ext(spirv::GLOp::UnpackUnorm4x8), |
| 1658 |
Mf::Unpack4x8snorm => MathOp::Ext(spirv::GLOp::UnpackSnorm4x8), |
| 1659 |
Mf::Unpack2x16float => MathOp::Ext(spirv::GLOp::UnpackHalf2x16), |
| 1660 |
Mf::Unpack2x16unorm => MathOp::Ext(spirv::GLOp::UnpackUnorm2x16), |
| 1661 |
Mf::Unpack2x16snorm => MathOp::Ext(spirv::GLOp::UnpackSnorm2x16), |
| 1662 |
fun @ (Mf::Unpack4xI8 | Mf::Unpack4xU8) => { |
| 1663 |
let (int_type, extract_op, is_signed) = match fun { |
| 1664 |
Mf::Unpack4xI8 => { |
| 1665 |
(crate::ScalarKind::Sint, spirv::Op::BitFieldSExtract, true) |
| 1666 |
} |
| 1667 |
Mf::Unpack4xU8 => { |
| 1668 |
(crate::ScalarKind::Uint, spirv::Op::BitFieldUExtract, false) |
| 1669 |
} |
| 1670 |
_ => unreachable!(), |
| 1671 |
}; |
| 1672 |
|
| 1673 |
let sint_type_id = |
| 1674 |
self.get_numeric_type_id(NumericType::Scalar(crate::Scalar::I32)); |
| 1675 |
|
| 1676 |
let eight = self.writer.get_constant_scalar(crate::Literal::U32(8)); |
| 1677 |
let int_type_id = |
| 1678 |
self.get_numeric_type_id(NumericType::Scalar(crate::Scalar { |
| 1679 |
kind: int_type, |
| 1680 |
width: 4, |
| 1681 |
})); |
| 1682 |
block |
| 1683 |
.body |
| 1684 |
.reserve(usize::from(VEC_LENGTH) * 2 + usize::from(is_signed)); |
| 1685 |
let arg_id = if is_signed { |
| 1686 |
let new_arg_id = self.gen_id(); |
| 1687 |
block.body.push(Instruction::unary( |
| 1688 |
spirv::Op::Bitcast, |
| 1689 |
sint_type_id, |
| 1690 |
new_arg_id, |
| 1691 |
arg0_id, |
| 1692 |
)); |
| 1693 |
new_arg_id |
| 1694 |
} else { |
| 1695 |
arg0_id |
| 1696 |
}; |
| 1697 |
|
| 1698 |
const VEC_LENGTH: u8 = 4; |
| 1699 |
let parts: [_; VEC_LENGTH as usize] = |
| 1700 |
core::array::from_fn(|_| self.gen_id()); |
| 1701 |
for (i, part_id) in parts.into_iter().enumerate() { |
| 1702 |
let index = self |
| 1703 |
.writer |
| 1704 |
.get_constant_scalar(crate::Literal::U32(i as u32 * 8)); |
| 1705 |
block.body.push(Instruction::ternary( |
| 1706 |
extract_op, |
| 1707 |
int_type_id, |
| 1708 |
part_id, |
| 1709 |
arg_id, |
| 1710 |
index, |
| 1711 |
eight, |
| 1712 |
)); |
| 1713 |
} |
| 1714 |
|
| 1715 |
MathOp::Custom(Instruction::composite_construct(result_type_id, id, &parts)) |
| 1716 |
} |
| 1717 |
}; |
| 1718 |
|
| 1719 |
block.body.push(match math_op { |
| 1720 |
MathOp::Ext(op) => Instruction::ext_inst( |
| 1721 |
self.writer.gl450_ext_inst_id, |
| 1722 |
op, |
| 1723 |
result_type_id, |
| 1724 |
id, |
| 1725 |
&[arg0_id, arg1_id, arg2_id, arg3_id][..fun.argument_count()], |
| 1726 |
), |
| 1727 |
MathOp::Custom(inst) => inst, |
| 1728 |
}); |
| 1729 |
id |
| 1730 |
} |
| 1731 |
crate::Expression::LocalVariable(variable) => self.function.variables[&variable].id, |
| 1732 |
crate::Expression::Load { pointer } => { |
| 1733 |
self.write_checked_load(pointer, block, AccessTypeAdjustment::None, result_type_id)? |
| 1734 |
} |
| 1735 |
crate::Expression::FunctionArgument(index) => self.function.parameter_id(index), |
| 1736 |
crate::Expression::CallResult(_) |
| 1737 |
| crate::Expression::AtomicResult { .. } |
| 1738 |
| crate::Expression::WorkGroupUniformLoadResult { .. } |
| 1739 |
| crate::Expression::RayQueryProceedResult |
| 1740 |
| crate::Expression::SubgroupBallotResult |
| 1741 |
| crate::Expression::SubgroupOperationResult { .. } => self.cached[expr_handle], |
| 1742 |
crate::Expression::As { |
| 1743 |
expr, |
| 1744 |
kind, |
| 1745 |
convert, |
| 1746 |
} => self.write_as_expression(expr, convert, kind, block, result_type_id)?, |
| 1747 |
crate::Expression::ImageLoad { |
| 1748 |
image, |
| 1749 |
coordinate, |
| 1750 |
array_index, |
| 1751 |
sample, |
| 1752 |
level, |
| 1753 |
} => self.write_image_load( |
| 1754 |
result_type_id, |
| 1755 |
image, |
| 1756 |
coordinate, |
| 1757 |
array_index, |
| 1758 |
level, |
| 1759 |
sample, |
| 1760 |
block, |
| 1761 |
)?, |
| 1762 |
crate::Expression::ImageSample { |
| 1763 |
image, |
| 1764 |
sampler, |
| 1765 |
gather, |
| 1766 |
coordinate, |
| 1767 |
array_index, |
| 1768 |
offset, |
| 1769 |
level, |
| 1770 |
depth_ref, |
| 1771 |
} => self.write_image_sample( |
| 1772 |
result_type_id, |
| 1773 |
image, |
| 1774 |
sampler, |
| 1775 |
gather, |
| 1776 |
coordinate, |
| 1777 |
array_index, |
| 1778 |
offset, |
| 1779 |
level, |
| 1780 |
depth_ref, |
| 1781 |
block, |
| 1782 |
)?, |
| 1783 |
crate::Expression::Select { |
| 1784 |
condition, |
| 1785 |
accept, |
| 1786 |
reject, |
| 1787 |
} => { |
| 1788 |
let id = self.gen_id(); |
| 1789 |
let mut condition_id = self.cached[condition]; |
| 1790 |
let accept_id = self.cached[accept]; |
| 1791 |
let reject_id = self.cached[reject]; |
| 1792 |
|
| 1793 |
let condition_ty = self.fun_info[condition] |
| 1794 |
.ty |
| 1795 |
.inner_with(&self.ir_module.types); |
| 1796 |
let object_ty = self.fun_info[accept].ty.inner_with(&self.ir_module.types); |
| 1797 |
|
| 1798 |
if let ( |
| 1799 |
&crate::TypeInner::Scalar( |
| 1800 |
condition_scalar @ crate::Scalar { |
| 1801 |
kind: crate::ScalarKind::Bool, |
| 1802 |
.. |
| 1803 |
}, |
| 1804 |
), |
| 1805 |
&crate::TypeInner::Vector { size, .. }, |
| 1806 |
) = (condition_ty, object_ty) |
| 1807 |
{ |
| 1808 |
self.temp_list.clear(); |
| 1809 |
self.temp_list.resize(size as usize, condition_id); |
| 1810 |
|
| 1811 |
let bool_vector_type_id = self.get_numeric_type_id(NumericType::Vector { |
| 1812 |
size, |
| 1813 |
scalar: condition_scalar, |
| 1814 |
}); |
| 1815 |
|
| 1816 |
let id = self.gen_id(); |
| 1817 |
block.body.push(Instruction::composite_construct( |
| 1818 |
bool_vector_type_id, |
| 1819 |
id, |
| 1820 |
&self.temp_list, |
| 1821 |
)); |
| 1822 |
condition_id = id |
| 1823 |
} |
| 1824 |
|
| 1825 |
let instruction = |
| 1826 |
Instruction::select(result_type_id, id, condition_id, accept_id, reject_id); |
| 1827 |
block.body.push(instruction); |
| 1828 |
id |
| 1829 |
} |
| 1830 |
crate::Expression::Derivative { axis, ctrl, expr } => { |
| 1831 |
use crate::{DerivativeAxis as Axis, DerivativeControl as Ctrl}; |
| 1832 |
match ctrl { |
| 1833 |
Ctrl::Coarse | Ctrl::Fine => { |
| 1834 |
self.writer.require_any( |
| 1835 |
"DerivativeControl", |
| 1836 |
&[spirv::Capability::DerivativeControl], |
| 1837 |
)?; |
| 1838 |
} |
| 1839 |
Ctrl::None => {} |
| 1840 |
} |
| 1841 |
let id = self.gen_id(); |
| 1842 |
let expr_id = self.cached[expr]; |
| 1843 |
let op = match (axis, ctrl) { |
| 1844 |
(Axis::X, Ctrl::Coarse) => spirv::Op::DPdxCoarse, |
| 1845 |
(Axis::X, Ctrl::Fine) => spirv::Op::DPdxFine, |
| 1846 |
(Axis::X, Ctrl::None) => spirv::Op::DPdx, |
| 1847 |
(Axis::Y, Ctrl::Coarse) => spirv::Op::DPdyCoarse, |
| 1848 |
(Axis::Y, Ctrl::Fine) => spirv::Op::DPdyFine, |
| 1849 |
(Axis::Y, Ctrl::None) => spirv::Op::DPdy, |
| 1850 |
(Axis::Width, Ctrl::Coarse) => spirv::Op::FwidthCoarse, |
| 1851 |
(Axis::Width, Ctrl::Fine) => spirv::Op::FwidthFine, |
| 1852 |
(Axis::Width, Ctrl::None) => spirv::Op::Fwidth, |
| 1853 |
}; |
| 1854 |
block |
| 1855 |
.body |
| 1856 |
.push(Instruction::derivative(op, result_type_id, id, expr_id)); |
| 1857 |
id |
| 1858 |
} |
| 1859 |
crate::Expression::ImageQuery { image, query } => { |
| 1860 |
self.write_image_query(result_type_id, image, query, block)? |
| 1861 |
} |
| 1862 |
crate::Expression::Relational { fun, argument } => { |
| 1863 |
use crate::RelationalFunction as Rf; |
| 1864 |
let arg_id = self.cached[argument]; |
| 1865 |
let op = match fun { |
| 1866 |
Rf::All => spirv::Op::All, |
| 1867 |
Rf::Any => spirv::Op::Any, |
| 1868 |
Rf::IsNan => spirv::Op::IsNan, |
| 1869 |
Rf::IsInf => spirv::Op::IsInf, |
| 1870 |
}; |
| 1871 |
let id = self.gen_id(); |
| 1872 |
block |
| 1873 |
.body |
| 1874 |
.push(Instruction::relational(op, result_type_id, id, arg_id)); |
| 1875 |
id |
| 1876 |
} |
| 1877 |
crate::Expression::ArrayLength(expr) => self.write_runtime_array_length(expr, block)?, |
| 1878 |
crate::Expression::RayQueryGetIntersection { query, committed } => { |
| 1879 |
let query_id = self.cached[query]; |
| 1880 |
let func_id = self |
| 1881 |
.writer |
| 1882 |
.write_ray_query_get_intersection_function(committed, self.ir_module); |
| 1883 |
let ray_intersection = self.ir_module.special_types.ray_intersection.unwrap(); |
| 1884 |
let intersection_type_id = self.get_handle_type_id(ray_intersection); |
| 1885 |
let id = self.gen_id(); |
| 1886 |
block.body.push(Instruction::function_call( |
| 1887 |
intersection_type_id, |
| 1888 |
id, |
| 1889 |
func_id, |
| 1890 |
&[query_id], |
| 1891 |
)); |
| 1892 |
id |
| 1893 |
} |
| 1894 |
crate::Expression::RayQueryVertexPositions { query, committed } => { |
| 1895 |
self.writer.require_any( |
| 1896 |
"RayQueryVertexPositions", |
| 1897 |
&[spirv::Capability::RayQueryPositionFetchKHR], |
| 1898 |
)?; |
| 1899 |
self.write_ray_query_return_vertex_position(query, block, committed) |
| 1900 |
} |
| 1901 |
}; |
| 1902 |
|
| 1903 |
self.cached[expr_handle] = id; |
| 1904 |
Ok(()) |
| 1905 |
} |
| 1906 |
|
| 1907 |
/// Helper which focuses on generating the `As` expressions and the various conversions |
| 1908 |
/// that need to happen because of that. |
| 1909 |
fn write_as_expression( |
| 1910 |
&mut self, |
| 1911 |
expr: Handle<crate::Expression>, |
| 1912 |
convert: Option<u8>, |
| 1913 |
kind: crate::ScalarKind, |
| 1914 |
|
| 1915 |
block: &mut Block, |
| 1916 |
result_type_id: u32, |
| 1917 |
) -> Result<u32, Error> { |
| 1918 |
use crate::ScalarKind as Sk; |
| 1919 |
let expr_id = self.cached[expr]; |
| 1920 |
let ty = self.fun_info[expr].ty.inner_with(&self.ir_module.types); |
| 1921 |
|
| 1922 |
// Matrix casts needs special treatment in SPIR-V, as the cast functions |
| 1923 |
// can take vectors or scalars, but not matrices. In order to cast a matrix |
| 1924 |
// we need to cast each column of the matrix individually and construct a new |
| 1925 |
// matrix from the converted columns. |
| 1926 |
if let crate::TypeInner::Matrix { |
| 1927 |
columns, |
| 1928 |
rows, |
| 1929 |
scalar, |
| 1930 |
} = *ty |
| 1931 |
{ |
| 1932 |
let Some(convert) = convert else { |
| 1933 |
// No conversion needs to be done, passes through. |
| 1934 |
return Ok(expr_id); |
| 1935 |
}; |
| 1936 |
|
| 1937 |
if convert == scalar.width { |
| 1938 |
// No conversion needs to be done, passes through. |
| 1939 |
return Ok(expr_id); |
| 1940 |
} |
| 1941 |
|
| 1942 |
if kind != Sk::Float { |
| 1943 |
// Only float conversions are supported for matrices. |
| 1944 |
return Err(Error::Validation("Matrices must be floats")); |
| 1945 |
} |
| 1946 |
|
| 1947 |
// Type of each extracted column |
| 1948 |
let column_src_ty = |
| 1949 |
self.get_type_id(LookupType::Local(LocalType::Numeric(NumericType::Vector { |
| 1950 |
size: rows, |
| 1951 |
scalar, |
| 1952 |
}))); |
| 1953 |
|
| 1954 |
// Type of the column after conversion |
| 1955 |
let column_dst_ty = |
| 1956 |
self.get_type_id(LookupType::Local(LocalType::Numeric(NumericType::Vector { |
| 1957 |
size: rows, |
| 1958 |
scalar: crate::Scalar { |
| 1959 |
kind, |
| 1960 |
width: convert, |
| 1961 |
}, |
| 1962 |
}))); |
| 1963 |
|
| 1964 |
let mut components = ArrayVec::<Word, 4>::new(); |
| 1965 |
|
| 1966 |
for column in 0..columns as usize { |
| 1967 |
let column_id = self.gen_id(); |
| 1968 |
block.body.push(Instruction::composite_extract( |
| 1969 |
column_src_ty, |
| 1970 |
column_id, |
| 1971 |
expr_id, |
| 1972 |
&[column as u32], |
| 1973 |
)); |
| 1974 |
|
| 1975 |
let column_conv_id = self.gen_id(); |
| 1976 |
block.body.push(Instruction::unary( |
| 1977 |
spirv::Op::FConvert, |
| 1978 |
column_dst_ty, |
| 1979 |
column_conv_id, |
| 1980 |
column_id, |
| 1981 |
)); |
| 1982 |
|
| 1983 |
components.push(column_conv_id); |
| 1984 |
} |
| 1985 |
|
| 1986 |
let construct_id = self.gen_id(); |
| 1987 |
|
| 1988 |
block.body.push(Instruction::composite_construct( |
| 1989 |
result_type_id, |
| 1990 |
construct_id, |
| 1991 |
&components, |
| 1992 |
)); |
| 1993 |
|
| 1994 |
return Ok(construct_id); |
| 1995 |
} |
| 1996 |
|
| 1997 |
let (src_scalar, src_size) = match *ty { |
| 1998 |
crate::TypeInner::Scalar(scalar) => (scalar, None), |
| 1999 |
crate::TypeInner::Vector { scalar, size } => (scalar, Some(size)), |
| 2000 |
ref other => { |
| 2001 |
log::error!("As source {:?}", other); |
| 2002 |
return Err(Error::Validation("Unexpected Expression::As source")); |
| 2003 |
} |
| 2004 |
}; |
| 2005 |
|
| 2006 |
enum Cast { |
| 2007 |
Identity(Word), |
| 2008 |
Unary(spirv::Op, Word), |
| 2009 |
Binary(spirv::Op, Word, Word), |
| 2010 |
Ternary(spirv::Op, Word, Word, Word), |
| 2011 |
} |
| 2012 |
let cast = match (src_scalar.kind, kind, convert) { |
| 2013 |
// Filter out identity casts. Some Adreno drivers are |
| 2014 |
// confused by no-op OpBitCast instructions. |
| 2015 |
(src_kind, kind, convert) |
| 2016 |
if src_kind == kind |
| 2017 |
&& convert.filter(|&width| width != src_scalar.width).is_none() => |
| 2018 |
{ |
| 2019 |
Cast::Identity(expr_id) |
| 2020 |
} |
| 2021 |
(Sk::Bool, Sk::Bool, _) => Cast::Unary(spirv::Op::CopyObject, expr_id), |
| 2022 |
(_, _, None) => Cast::Unary(spirv::Op::Bitcast, expr_id), |
| 2023 |
// casting to a bool - generate `OpXxxNotEqual` |
| 2024 |
(_, Sk::Bool, Some(_)) => { |
| 2025 |
let op = match src_scalar.kind { |
| 2026 |
Sk::Sint | Sk::Uint => spirv::Op::INotEqual, |
| 2027 |
Sk::Float => spirv::Op::FUnordNotEqual, |
| 2028 |
Sk::Bool | Sk::AbstractInt | Sk::AbstractFloat => unreachable!(), |
| 2029 |
}; |
| 2030 |
let zero_scalar_id = self.writer.get_constant_scalar_with(0, src_scalar)?; |
| 2031 |
let zero_id = match src_size { |
| 2032 |
Some(size) => { |
| 2033 |
let ty = LocalType::Numeric(NumericType::Vector { |
| 2034 |
size, |
| 2035 |
scalar: src_scalar, |
| 2036 |
}) |
| 2037 |
.into(); |
| 2038 |
|
| 2039 |
self.temp_list.clear(); |
| 2040 |
self.temp_list.resize(size as _, zero_scalar_id); |
| 2041 |
|
| 2042 |
self.writer.get_constant_composite(ty, &self.temp_list) |
| 2043 |
} |
| 2044 |
None => zero_scalar_id, |
| 2045 |
}; |
| 2046 |
|
| 2047 |
Cast::Binary(op, expr_id, zero_id) |
| 2048 |
} |
| 2049 |
// casting from a bool - generate `OpSelect` |
| 2050 |
(Sk::Bool, _, Some(dst_width)) => { |
| 2051 |
let dst_scalar = crate::Scalar { |
| 2052 |
kind, |
| 2053 |
width: dst_width, |
| 2054 |
}; |
| 2055 |
let zero_scalar_id = self.writer.get_constant_scalar_with(0, dst_scalar)?; |
| 2056 |
let one_scalar_id = self.writer.get_constant_scalar_with(1, dst_scalar)?; |
| 2057 |
let (accept_id, reject_id) = match src_size { |
| 2058 |
Some(size) => { |
| 2059 |
let ty = LocalType::Numeric(NumericType::Vector { |
| 2060 |
size, |
| 2061 |
scalar: dst_scalar, |
| 2062 |
}) |
| 2063 |
.into(); |
| 2064 |
|
| 2065 |
self.temp_list.clear(); |
| 2066 |
self.temp_list.resize(size as _, zero_scalar_id); |
| 2067 |
|
| 2068 |
let vec0_id = self.writer.get_constant_composite(ty, &self.temp_list); |
| 2069 |
|
| 2070 |
self.temp_list.fill(one_scalar_id); |
| 2071 |
|
| 2072 |
let vec1_id = self.writer.get_constant_composite(ty, &self.temp_list); |
| 2073 |
|
| 2074 |
(vec1_id, vec0_id) |
| 2075 |
} |
| 2076 |
None => (one_scalar_id, zero_scalar_id), |
| 2077 |
}; |
| 2078 |
|
| 2079 |
Cast::Ternary(spirv::Op::Select, expr_id, accept_id, reject_id) |
| 2080 |
} |
| 2081 |
// Avoid undefined behaviour when casting from a float to integer |
| 2082 |
// when the value is out of range for the target type. Additionally |
| 2083 |
// ensure we clamp to the correct value as per the WGSL spec. |
| 2084 |
// |
| 2085 |
// https://www.w3.org/TR/WGSL/#floating-point-conversion: |
| 2086 |
// * If X is exactly representable in the target type T, then the |
| 2087 |
// result is that value. |
| 2088 |
// * Otherwise, the result is the value in T closest to |
| 2089 |
// truncate(X) and also exactly representable in the original |
| 2090 |
// floating point type. |
| 2091 |
(Sk::Float, Sk::Sint | Sk::Uint, Some(width)) => { |
| 2092 |
let dst_scalar = crate::Scalar { kind, width }; |
| 2093 |
let (min, max) = |
| 2094 |
crate::proc::min_max_float_representable_by(src_scalar, dst_scalar); |
| 2095 |
let expr_type_id = self.get_expression_type_id(&self.fun_info[expr].ty); |
| 2096 |
|
| 2097 |
let maybe_splat_const = |writer: &mut Writer, const_id| match src_size { |
| 2098 |
None => const_id, |
| 2099 |
Some(size) => { |
| 2100 |
let constituent_ids = [const_id; crate::VectorSize::MAX]; |
| 2101 |
writer.get_constant_composite( |
| 2102 |
LookupType::Local(LocalType::Numeric(NumericType::Vector { |
| 2103 |
size, |
| 2104 |
scalar: src_scalar, |
| 2105 |
})), |
| 2106 |
&constituent_ids[..size as usize], |
| 2107 |
) |
| 2108 |
} |
| 2109 |
}; |
| 2110 |
let min_const_id = self.writer.get_constant_scalar(min); |
| 2111 |
let min_const_id = maybe_splat_const(self.writer, min_const_id); |
| 2112 |
let max_const_id = self.writer.get_constant_scalar(max); |
| 2113 |
let max_const_id = maybe_splat_const(self.writer, max_const_id); |
| 2114 |
|
| 2115 |
let clamp_id = self.gen_id(); |
| 2116 |
block.body.push(Instruction::ext_inst( |
| 2117 |
self.writer.gl450_ext_inst_id, |
| 2118 |
spirv::GLOp::FClamp, |
| 2119 |
expr_type_id, |
| 2120 |
clamp_id, |
| 2121 |
&[expr_id, min_const_id, max_const_id], |
| 2122 |
)); |
| 2123 |
|
| 2124 |
let op = match dst_scalar.kind { |
| 2125 |
crate::ScalarKind::Sint => spirv::Op::ConvertFToS, |
| 2126 |
crate::ScalarKind::Uint => spirv::Op::ConvertFToU, |
| 2127 |
_ => unreachable!(), |
| 2128 |
}; |
| 2129 |
Cast::Unary(op, clamp_id) |
| 2130 |
} |
| 2131 |
(Sk::Float, Sk::Float, Some(dst_width)) if src_scalar.width != dst_width => { |
| 2132 |
Cast::Unary(spirv::Op::FConvert, expr_id) |
| 2133 |
} |
| 2134 |
(Sk::Sint, Sk::Float, Some(_)) => Cast::Unary(spirv::Op::ConvertSToF, expr_id), |
| 2135 |
(Sk::Sint, Sk::Sint, Some(dst_width)) if src_scalar.width != dst_width => { |
| 2136 |
Cast::Unary(spirv::Op::SConvert, expr_id) |
| 2137 |
} |
| 2138 |
(Sk::Uint, Sk::Float, Some(_)) => Cast::Unary(spirv::Op::ConvertUToF, expr_id), |
| 2139 |
(Sk::Uint, Sk::Uint, Some(dst_width)) if src_scalar.width != dst_width => { |
| 2140 |
Cast::Unary(spirv::Op::UConvert, expr_id) |
| 2141 |
} |
| 2142 |
(Sk::Uint, Sk::Sint, Some(dst_width)) if src_scalar.width != dst_width => { |
| 2143 |
Cast::Unary(spirv::Op::SConvert, expr_id) |
| 2144 |
} |
| 2145 |
(Sk::Sint, Sk::Uint, Some(dst_width)) if src_scalar.width != dst_width => { |
| 2146 |
Cast::Unary(spirv::Op::UConvert, expr_id) |
| 2147 |
} |
| 2148 |
// We assume it's either an identity cast, or int-uint. |
| 2149 |
_ => Cast::Unary(spirv::Op::Bitcast, expr_id), |
| 2150 |
}; |
| 2151 |
Ok(match cast { |
| 2152 |
Cast::Identity(expr) => expr, |
| 2153 |
Cast::Unary(op, op1) => { |
| 2154 |
let id = self.gen_id(); |
| 2155 |
block |
| 2156 |
.body |
| 2157 |
.push(Instruction::unary(op, result_type_id, id, op1)); |
| 2158 |
id |
| 2159 |
} |
| 2160 |
Cast::Binary(op, op1, op2) => { |
| 2161 |
let id = self.gen_id(); |
| 2162 |
block |
| 2163 |
.body |
| 2164 |
.push(Instruction::binary(op, result_type_id, id, op1, op2)); |
| 2165 |
id |
| 2166 |
} |
| 2167 |
Cast::Ternary(op, op1, op2, op3) => { |
| 2168 |
let id = self.gen_id(); |
| 2169 |
block |
| 2170 |
.body |
| 2171 |
.push(Instruction::ternary(op, result_type_id, id, op1, op2, op3)); |
| 2172 |
id |
| 2173 |
} |
| 2174 |
}) |
| 2175 |
} |
| 2176 |
|
| 2177 |
/// Build an `OpAccessChain` instruction. |
| 2178 |
/// |
| 2179 |
/// Emit any needed bounds-checking expressions to `block`. |
| 2180 |
/// |
| 2181 |
/// Give the `OpAccessChain` a result type based on `expr_handle`, adjusted |
| 2182 |
/// according to `type_adjustment`; see the documentation for |
| 2183 |
/// [`AccessTypeAdjustment`] for details. |
| 2184 |
/// |
| 2185 |
/// On success, the return value is an [`ExpressionPointer`] value; see the |
| 2186 |
/// documentation for that type. |
| 2187 |
fn write_access_chain( |
| 2188 |
&mut self, |
| 2189 |
mut expr_handle: Handle<crate::Expression>, |
| 2190 |
block: &mut Block, |
| 2191 |
type_adjustment: AccessTypeAdjustment, |
| 2192 |
) -> Result<ExpressionPointer, Error> { |
| 2193 |
let result_type_id = { |
| 2194 |
let resolution = &self.fun_info[expr_handle].ty; |
| 2195 |
match type_adjustment { |
| 2196 |
AccessTypeAdjustment::None => self.writer.get_expression_type_id(resolution), |
| 2197 |
AccessTypeAdjustment::IntroducePointer(class) => { |
| 2198 |
self.writer.get_resolution_pointer_id(resolution, class) |
| 2199 |
} |
| 2200 |
} |
| 2201 |
}; |
| 2202 |
|
| 2203 |
// The id of the boolean `and` of all dynamic bounds checks up to this point. |
| 2204 |
// |
| 2205 |
// See `extend_bounds_check_condition_chain` for a full explanation. |
| 2206 |
let mut accumulated_checks = None; |
| 2207 |
|
| 2208 |
// Is true if we are accessing into a binding array with a non-uniform index. |
| 2209 |
let mut is_non_uniform_binding_array = false; |
| 2210 |
|
| 2211 |
self.temp_list.clear(); |
| 2212 |
let root_id = loop { |
| 2213 |
// If `expr_handle` was spilled, then the temporary variable has exactly |
| 2214 |
// the value we want to start from. |
| 2215 |
if let Some(spilled) = self.function.spilled_composites.get(&expr_handle) { |
| 2216 |
// The root id of the `OpAccessChain` instruction is the temporary |
| 2217 |
// variable we spilled the composite to. |
| 2218 |
break spilled.id; |
| 2219 |
} |
| 2220 |
|
| 2221 |
expr_handle = match self.ir_function.expressions[expr_handle] { |
| 2222 |
crate::Expression::Access { base, index } => { |
| 2223 |
is_non_uniform_binding_array |= |
| 2224 |
self.is_nonuniform_binding_array_access(base, index); |
| 2225 |
|
| 2226 |
let index = GuardedIndex::Expression(index); |
| 2227 |
let index_id = |
| 2228 |
self.write_access_chain_index(base, index, &mut accumulated_checks, block)?; |
| 2229 |
self.temp_list.push(index_id); |
| 2230 |
|
| 2231 |
base |
| 2232 |
} |
| 2233 |
crate::Expression::AccessIndex { base, index } => { |
| 2234 |
// Decide whether we're indexing a struct (bounds checks |
| 2235 |
// forbidden) or anything else (bounds checks required). |
| 2236 |
let mut base_ty = self.fun_info[base].ty.inner_with(&self.ir_module.types); |
| 2237 |
if let crate::TypeInner::Pointer { base, .. } = *base_ty { |
| 2238 |
base_ty = &self.ir_module.types[base].inner; |
| 2239 |
} |
| 2240 |
let index_id = if let crate::TypeInner::Struct { .. } = *base_ty { |
| 2241 |
self.get_index_constant(index) |
| 2242 |
} else { |
| 2243 |
// `index` is constant, so this can't possibly require |
| 2244 |
// setting `is_nonuniform_binding_array_access`. |
| 2245 |
|
| 2246 |
// Even though the index value is statically known, `base` |
| 2247 |
// may be a runtime-sized array, so we still need to go |
| 2248 |
// through the bounds check process. |
| 2249 |
self.write_access_chain_index( |
| 2250 |
base, |
| 2251 |
GuardedIndex::Known(index), |
| 2252 |
&mut accumulated_checks, |
| 2253 |
block, |
| 2254 |
)? |
| 2255 |
}; |
| 2256 |
|
| 2257 |
self.temp_list.push(index_id); |
| 2258 |
base |
| 2259 |
} |
| 2260 |
crate::Expression::GlobalVariable(handle) => { |
| 2261 |
let gv = &self.writer.global_variables[handle]; |
| 2262 |
break gv.access_id; |
| 2263 |
} |
| 2264 |
crate::Expression::LocalVariable(variable) => { |
| 2265 |
let local_var = &self.function.variables[&variable]; |
| 2266 |
break local_var.id; |
| 2267 |
} |
| 2268 |
crate::Expression::FunctionArgument(index) => { |
| 2269 |
break self.function.parameter_id(index); |
| 2270 |
} |
| 2271 |
ref other => unimplemented!("Unexpected pointer expression {:?}", other), |
| 2272 |
} |
| 2273 |
}; |
| 2274 |
|
| 2275 |
let (pointer_id, expr_pointer) = if self.temp_list.is_empty() { |
| 2276 |
( |
| 2277 |
root_id, |
| 2278 |
ExpressionPointer::Ready { |
| 2279 |
pointer_id: root_id, |
| 2280 |
}, |
| 2281 |
) |
| 2282 |
} else { |
| 2283 |
self.temp_list.reverse(); |
| 2284 |
let pointer_id = self.gen_id(); |
| 2285 |
let access = |
| 2286 |
Instruction::access_chain(result_type_id, pointer_id, root_id, &self.temp_list); |
| 2287 |
|
| 2288 |
// If we generated some bounds checks, we need to leave it to our |
| 2289 |
// caller to generate the branch, the access, the load or store, and |
| 2290 |
// the zero value (for loads). Otherwise, we can emit the access |
| 2291 |
// ourselves, and just hand them the id of the pointer. |
| 2292 |
let expr_pointer = match accumulated_checks { |
| 2293 |
Some(condition) => ExpressionPointer::Conditional { condition, access }, |
| 2294 |
None => { |
| 2295 |
block.body.push(access); |
| 2296 |
ExpressionPointer::Ready { pointer_id } |
| 2297 |
} |
| 2298 |
}; |
| 2299 |
(pointer_id, expr_pointer) |
| 2300 |
}; |
| 2301 |
// Subsequent load, store and atomic operations require the pointer to be decorated as NonUniform |
| 2302 |
// if the binding array was accessed with a non-uniform index |
| 2303 |
// see VUID-RuntimeSpirv-NonUniform-06274 |
| 2304 |
if is_non_uniform_binding_array { |
| 2305 |
self.writer |
| 2306 |
.decorate_non_uniform_binding_array_access(pointer_id)?; |
| 2307 |
} |
| 2308 |
|
| 2309 |
Ok(expr_pointer) |
| 2310 |
} |
| 2311 |
|
| 2312 |
fn is_nonuniform_binding_array_access( |
| 2313 |
&mut self, |
| 2314 |
base: Handle<crate::Expression>, |
| 2315 |
index: Handle<crate::Expression>, |
| 2316 |
) -> bool { |
| 2317 |
let crate::Expression::GlobalVariable(var_handle) = self.ir_function.expressions[base] |
| 2318 |
else { |
| 2319 |
return false; |
| 2320 |
}; |
| 2321 |
|
| 2322 |
// The access chain needs to be decorated as NonUniform |
| 2323 |
// see VUID-RuntimeSpirv-NonUniform-06274 |
| 2324 |
let gvar = &self.ir_module.global_variables[var_handle]; |
| 2325 |
let crate::TypeInner::BindingArray { .. } = self.ir_module.types[gvar.ty].inner else { |
| 2326 |
return false; |
| 2327 |
}; |
| 2328 |
|
| 2329 |
self.fun_info[index].uniformity.non_uniform_result.is_some() |
| 2330 |
} |
| 2331 |
|
| 2332 |
/// Compute a single index operand to an `OpAccessChain` instruction. |
| 2333 |
/// |
| 2334 |
/// Given that we are indexing `base` with `index`, apply the appropriate |
| 2335 |
/// bounds check policies, emitting code to `block` to clamp `index` or |
| 2336 |
/// determine whether it's in bounds. Return the SPIR-V instruction id of |
| 2337 |
/// the index value we should actually use. |
| 2338 |
/// |
| 2339 |
/// Extend `accumulated_checks` to include the results of any needed bounds |
| 2340 |
/// checks. See [`BlockContext::extend_bounds_check_condition_chain`]. |
| 2341 |
fn write_access_chain_index( |
| 2342 |
&mut self, |
| 2343 |
base: Handle<crate::Expression>, |
| 2344 |
index: GuardedIndex, |
| 2345 |
accumulated_checks: &mut Option<Word>, |
| 2346 |
block: &mut Block, |
| 2347 |
) -> Result<Word, Error> { |
| 2348 |
match self.write_bounds_check(base, index, block)? { |
| 2349 |
BoundsCheckResult::KnownInBounds(known_index) => { |
| 2350 |
// Even if the index is known, `OpAccessChain` |
| 2351 |
// requires expression operands, not literals. |
| 2352 |
let scalar = crate::Literal::U32(known_index); |
| 2353 |
Ok(self.writer.get_constant_scalar(scalar)) |
| 2354 |
} |
| 2355 |
BoundsCheckResult::Computed(computed_index_id) => Ok(computed_index_id), |
| 2356 |
BoundsCheckResult::Conditional { |
| 2357 |
condition_id: condition, |
| 2358 |
index_id: index, |
| 2359 |
} => { |
| 2360 |
self.extend_bounds_check_condition_chain(accumulated_checks, condition, block); |
| 2361 |
|
| 2362 |
// Use the index from the `Access` expression unchanged. |
| 2363 |
Ok(index) |
| 2364 |
} |
| 2365 |
} |
| 2366 |
} |
| 2367 |
|
| 2368 |
/// Add a condition to a chain of bounds checks. |
| 2369 |
/// |
| 2370 |
/// As we build an `OpAccessChain` instruction govered by |
| 2371 |
/// [`BoundsCheckPolicy::ReadZeroSkipWrite`], we accumulate a chain of |
| 2372 |
/// dynamic bounds checks, one for each index in the chain, which must all |
| 2373 |
/// be true for that `OpAccessChain`'s execution to be well-defined. This |
| 2374 |
/// function adds the boolean instruction id `comparison_id` to `chain`. |
| 2375 |
/// |
| 2376 |
/// If `chain` is `None`, that means there are no bounds checks in the chain |
| 2377 |
/// yet. If chain is `Some(id)`, then `id` is the conjunction of all the |
| 2378 |
/// bounds checks in the chain. |
| 2379 |
/// |
| 2380 |
/// When we have multiple bounds checks, we combine them with |
| 2381 |
/// `OpLogicalAnd`, not a short-circuit branch. This means we might do |
| 2382 |
/// comparisons we don't need to, but we expect these checks to almost |
| 2383 |
/// always succeed, and keeping branches to a minimum is essential. |
| 2384 |
/// |
| 2385 |
/// [`BoundsCheckPolicy::ReadZeroSkipWrite`]: crate::proc::BoundsCheckPolicy |
| 2386 |
fn extend_bounds_check_condition_chain( |
| 2387 |
&mut self, |
| 2388 |
chain: &mut Option<Word>, |
| 2389 |
comparison_id: Word, |
| 2390 |
block: &mut Block, |
| 2391 |
) { |
| 2392 |
match *chain { |
| 2393 |
Some(ref mut prior_checks) => { |
| 2394 |
let combined = self.gen_id(); |
| 2395 |
block.body.push(Instruction::binary( |
| 2396 |
spirv::Op::LogicalAnd, |
| 2397 |
self.writer.get_bool_type_id(), |
| 2398 |
combined, |
| 2399 |
*prior_checks, |
| 2400 |
comparison_id, |
| 2401 |
)); |
| 2402 |
*prior_checks = combined; |
| 2403 |
} |
| 2404 |
None => { |
| 2405 |
// Start a fresh chain of checks. |
| 2406 |
*chain = Some(comparison_id); |
| 2407 |
} |
| 2408 |
} |
| 2409 |
} |
| 2410 |
|
| 2411 |
fn write_checked_load( |
| 2412 |
&mut self, |
| 2413 |
pointer: Handle<crate::Expression>, |
| 2414 |
block: &mut Block, |
| 2415 |
access_type_adjustment: AccessTypeAdjustment, |
| 2416 |
result_type_id: Word, |
| 2417 |
) -> Result<Word, Error> { |
| 2418 |
match self.write_access_chain(pointer, block, access_type_adjustment)? { |
| 2419 |
ExpressionPointer::Ready { pointer_id } => { |
| 2420 |
let id = self.gen_id(); |
| 2421 |
let atomic_space = |
| 2422 |
match *self.fun_info[pointer].ty.inner_with(&self.ir_module.types) { |
| 2423 |
crate::TypeInner::Pointer { base, space } => { |
| 2424 |
match self.ir_module.types[base].inner { |
| 2425 |
crate::TypeInner::Atomic { .. } => Some(space), |
| 2426 |
_ => None, |
| 2427 |
} |
| 2428 |
} |
| 2429 |
_ => None, |
| 2430 |
}; |
| 2431 |
let instruction = if let Some(space) = atomic_space { |
| 2432 |
let (semantics, scope) = space.to_spirv_semantics_and_scope(); |
| 2433 |
let scope_constant_id = self.get_scope_constant(scope as u32); |
| 2434 |
let semantics_id = self.get_index_constant(semantics.bits()); |
| 2435 |
Instruction::atomic_load( |
| 2436 |
result_type_id, |
| 2437 |
id, |
| 2438 |
pointer_id, |
| 2439 |
scope_constant_id, |
| 2440 |
semantics_id, |
| 2441 |
) |
| 2442 |
} else { |
| 2443 |
Instruction::load(result_type_id, id, pointer_id, None) |
| 2444 |
}; |
| 2445 |
block.body.push(instruction); |
| 2446 |
Ok(id) |
| 2447 |
} |
| 2448 |
ExpressionPointer::Conditional { condition, access } => { |
| 2449 |
//TODO: support atomics? |
| 2450 |
let value = self.write_conditional_indexed_load( |
| 2451 |
result_type_id, |
| 2452 |
condition, |
| 2453 |
block, |
| 2454 |
move |id_gen, block| { |
| 2455 |
// The in-bounds path. Perform the access and the load. |
| 2456 |
let pointer_id = access.result_id.unwrap(); |
| 2457 |
let value_id = id_gen.next(); |
| 2458 |
block.body.push(access); |
| 2459 |
block.body.push(Instruction::load( |
| 2460 |
result_type_id, |
| 2461 |
value_id, |
| 2462 |
pointer_id, |
| 2463 |
None, |
| 2464 |
)); |
| 2465 |
value_id |
| 2466 |
}, |
| 2467 |
); |
| 2468 |
Ok(value) |
| 2469 |
} |
| 2470 |
} |
| 2471 |
} |
| 2472 |
|
| 2473 |
fn spill_to_internal_variable(&mut self, base: Handle<crate::Expression>, block: &mut Block) { |
| 2474 |
use indexmap::map::Entry; |
| 2475 |
|
| 2476 |
// Make sure we have an internal variable to spill `base` to. |
| 2477 |
let spill_variable_id = match self.function.spilled_composites.entry(base) { |
| 2478 |
Entry::Occupied(preexisting) => preexisting.get().id, |
| 2479 |
Entry::Vacant(vacant) => { |
| 2480 |
// Generate a new internal variable of the appropriate |
| 2481 |
// type for `base`. |
| 2482 |
let pointer_type_id = self.writer.get_resolution_pointer_id( |
| 2483 |
&self.fun_info[base].ty, |
| 2484 |
spirv::StorageClass::Function, |
| 2485 |
); |
| 2486 |
let id = self.writer.id_gen.next(); |
| 2487 |
vacant.insert(super::LocalVariable { |
| 2488 |
id, |
| 2489 |
instruction: Instruction::variable( |
| 2490 |
pointer_type_id, |
| 2491 |
id, |
| 2492 |
spirv::StorageClass::Function, |
| 2493 |
None, |
| 2494 |
), |
| 2495 |
}); |
| 2496 |
id |
| 2497 |
} |
| 2498 |
}; |
| 2499 |
|
| 2500 |
// Perform the store even if we already had a spill variable for `base`. |
| 2501 |
// Consider this code: |
| 2502 |
// |
| 2503 |
// var x = ...; |
| 2504 |
// var y = ...; |
| 2505 |
// var z = ...; |
| 2506 |
// for (i = 0; i<2; i++) { |
| 2507 |
// let a = array(i, i, i); |
| 2508 |
// if (i == 0) { |
| 2509 |
// x += a[y]; |
| 2510 |
// } else [ |
| 2511 |
// x += a[z]; |
| 2512 |
// } |
| 2513 |
// } |
| 2514 |
// |
| 2515 |
// The value of `a` needs to be spilled so we can subscript it with `y` and `z`. |
| 2516 |
// |
| 2517 |
// When we generate SPIR-V for `a[y]`, we will create the spill |
| 2518 |
// variable, and store `a`'s value in it. |
| 2519 |
// |
| 2520 |
// When we generate SPIR-V for `a[z]`, we will notice that the spill |
| 2521 |
// variable for `a` has already been declared, but it is still essential |
| 2522 |
// that we store `a` into it, so that `a[z]` sees this iteration's value |
| 2523 |
// of `a`. |
| 2524 |
let base_id = self.cached[base]; |
| 2525 |
block |
| 2526 |
.body |
| 2527 |
.push(Instruction::store(spill_variable_id, base_id, None)); |
| 2528 |
} |
| 2529 |
|
| 2530 |
/// Generate an access to a spilled temporary, if necessary. |
| 2531 |
/// |
| 2532 |
/// Given `access`, an [`Access`] or [`AccessIndex`] expression that refers |
| 2533 |
/// to a component of a composite value that has been spilled to a temporary |
| 2534 |
/// variable, determine whether other expressions are going to use |
| 2535 |
/// `access`'s value: |
| 2536 |
/// |
| 2537 |
/// - If so, perform the access and cache that as the value of `access`. |
| 2538 |
/// |
| 2539 |
/// - Otherwise, generate no code and cache no value for `access`. |
| 2540 |
/// |
| 2541 |
/// Return `Ok(0)` if no value was fetched, or `Ok(id)` if we loaded it into |
| 2542 |
/// the instruction given by `id`. |
| 2543 |
/// |
| 2544 |
/// [`Access`]: crate::Expression::Access |
| 2545 |
/// [`AccessIndex`]: crate::Expression::AccessIndex |
| 2546 |
fn maybe_access_spilled_composite( |
| 2547 |
&mut self, |
| 2548 |
access: Handle<crate::Expression>, |
| 2549 |
block: &mut Block, |
| 2550 |
result_type_id: Word, |
| 2551 |
) -> Result<Word, Error> { |
| 2552 |
let access_uses = self.function.access_uses.get(&access).map_or(0, |r| *r); |
| 2553 |
if access_uses == self.fun_info[access].ref_count { |
| 2554 |
// This expression is only used by other `Access` and |
| 2555 |
// `AccessIndex` expressions, so we don't need to cache a |
| 2556 |
// value for it yet. |
| 2557 |
Ok(0) |
| 2558 |
} else { |
| 2559 |
// There are other expressions that are going to expect this |
| 2560 |
// expression's value to be cached, not just other `Access` or |
| 2561 |
// `AccessIndex` expressions. We must actually perform the |
| 2562 |
// access on the spill variable now. |
| 2563 |
self.write_checked_load( |
| 2564 |
access, |
| 2565 |
block, |
| 2566 |
AccessTypeAdjustment::IntroducePointer(spirv::StorageClass::Function), |
| 2567 |
result_type_id, |
| 2568 |
) |
| 2569 |
} |
| 2570 |
} |
| 2571 |
|
| 2572 |
/// Build the instructions for matrix - matrix column operations |
| 2573 |
#[allow(clippy::too_many_arguments)] |
| 2574 |
fn write_matrix_matrix_column_op( |
| 2575 |
&mut self, |
| 2576 |
block: &mut Block, |
| 2577 |
result_id: Word, |
| 2578 |
result_type_id: Word, |
| 2579 |
left_id: Word, |
| 2580 |
right_id: Word, |
| 2581 |
columns: crate::VectorSize, |
| 2582 |
rows: crate::VectorSize, |
| 2583 |
width: u8, |
| 2584 |
op: spirv::Op, |
| 2585 |
) { |
| 2586 |
self.temp_list.clear(); |
| 2587 |
|
| 2588 |
let vector_type_id = self.get_numeric_type_id(NumericType::Vector { |
| 2589 |
size: rows, |
| 2590 |
scalar: crate::Scalar::float(width), |
| 2591 |
}); |
| 2592 |
|
| 2593 |
for index in 0..columns as u32 { |
| 2594 |
let column_id_left = self.gen_id(); |
| 2595 |
let column_id_right = self.gen_id(); |
| 2596 |
let column_id_res = self.gen_id(); |
| 2597 |
|
| 2598 |
block.body.push(Instruction::composite_extract( |
| 2599 |
vector_type_id, |
| 2600 |
column_id_left, |
| 2601 |
left_id, |
| 2602 |
&[index], |
| 2603 |
)); |
| 2604 |
block.body.push(Instruction::composite_extract( |
| 2605 |
vector_type_id, |
| 2606 |
column_id_right, |
| 2607 |
right_id, |
| 2608 |
&[index], |
| 2609 |
)); |
| 2610 |
block.body.push(Instruction::binary( |
| 2611 |
op, |
| 2612 |
vector_type_id, |
| 2613 |
column_id_res, |
| 2614 |
column_id_left, |
| 2615 |
column_id_right, |
| 2616 |
)); |
| 2617 |
|
| 2618 |
self.temp_list.push(column_id_res); |
| 2619 |
} |
| 2620 |
|
| 2621 |
block.body.push(Instruction::composite_construct( |
| 2622 |
result_type_id, |
| 2623 |
result_id, |
| 2624 |
&self.temp_list, |
| 2625 |
)); |
| 2626 |
} |
| 2627 |
|
| 2628 |
/// Build the instructions for vector - scalar multiplication |
| 2629 |
fn write_vector_scalar_mult( |
| 2630 |
&mut self, |
| 2631 |
block: &mut Block, |
| 2632 |
result_id: Word, |
| 2633 |
result_type_id: Word, |
| 2634 |
vector_id: Word, |
| 2635 |
scalar_id: Word, |
| 2636 |
vector: &crate::TypeInner, |
| 2637 |
) { |
| 2638 |
let (size, kind) = match *vector { |
| 2639 |
crate::TypeInner::Vector { |
| 2640 |
size, |
| 2641 |
scalar: crate::Scalar { kind, .. }, |
| 2642 |
} => (size, kind), |
| 2643 |
_ => unreachable!(), |
| 2644 |
}; |
| 2645 |
|
| 2646 |
let (op, operand_id) = match kind { |
| 2647 |
crate::ScalarKind::Float => (spirv::Op::VectorTimesScalar, scalar_id), |
| 2648 |
_ => { |
| 2649 |
let operand_id = self.gen_id(); |
| 2650 |
self.temp_list.clear(); |
| 2651 |
self.temp_list.resize(size as usize, scalar_id); |
| 2652 |
block.body.push(Instruction::composite_construct( |
| 2653 |
result_type_id, |
| 2654 |
operand_id, |
| 2655 |
&self.temp_list, |
| 2656 |
)); |
| 2657 |
(spirv::Op::IMul, operand_id) |
| 2658 |
} |
| 2659 |
}; |
| 2660 |
|
| 2661 |
block.body.push(Instruction::binary( |
| 2662 |
op, |
| 2663 |
result_type_id, |
| 2664 |
result_id, |
| 2665 |
vector_id, |
| 2666 |
operand_id, |
| 2667 |
)); |
| 2668 |
} |
| 2669 |
|
| 2670 |
/// Build the instructions for the arithmetic expression of a dot product |
| 2671 |
/// |
| 2672 |
/// The argument `extractor` is a function that maps `(result_id, |
| 2673 |
/// composite_id, index)` to an instruction that extracts the `index`th |
| 2674 |
/// entry of the value with ID `composite_id` and assigns it to the slot |
| 2675 |
/// with id `result_id` (which must have type `result_type_id`). |
| 2676 |
#[expect(clippy::too_many_arguments)] |
| 2677 |
fn write_dot_product( |
| 2678 |
&mut self, |
| 2679 |
result_id: Word, |
| 2680 |
result_type_id: Word, |
| 2681 |
arg0_id: Word, |
| 2682 |
arg1_id: Word, |
| 2683 |
size: u32, |
| 2684 |
block: &mut Block, |
| 2685 |
extractor: impl Fn(Word, Word, Word) -> Instruction, |
| 2686 |
) { |
| 2687 |
let mut partial_sum = self.writer.get_constant_null(result_type_id); |
| 2688 |
let last_component = size - 1; |
| 2689 |
for index in 0..=last_component { |
| 2690 |
// compute the product of the current components |
| 2691 |
let a_id = self.gen_id(); |
| 2692 |
block.body.push(extractor(a_id, arg0_id, index)); |
| 2693 |
let b_id = self.gen_id(); |
| 2694 |
block.body.push(extractor(b_id, arg1_id, index)); |
| 2695 |
let prod_id = self.gen_id(); |
| 2696 |
block.body.push(Instruction::binary( |
| 2697 |
spirv::Op::IMul, |
| 2698 |
result_type_id, |
| 2699 |
prod_id, |
| 2700 |
a_id, |
| 2701 |
b_id, |
| 2702 |
)); |
| 2703 |
|
| 2704 |
// choose the id for the next sum, depending on current index |
| 2705 |
let id = if index == last_component { |
| 2706 |
result_id |
| 2707 |
} else { |
| 2708 |
self.gen_id() |
| 2709 |
}; |
| 2710 |
|
| 2711 |
// sum the computed product with the partial sum |
| 2712 |
block.body.push(Instruction::binary( |
| 2713 |
spirv::Op::IAdd, |
| 2714 |
result_type_id, |
| 2715 |
id, |
| 2716 |
partial_sum, |
| 2717 |
prod_id, |
| 2718 |
)); |
| 2719 |
// set the id of the result as the previous partial sum |
| 2720 |
partial_sum = id; |
| 2721 |
} |
| 2722 |
} |
| 2723 |
|
| 2724 |
/// Generate one or more SPIR-V blocks for `naga_block`. |
| 2725 |
/// |
| 2726 |
/// Use `label_id` as the label for the SPIR-V entry point block. |
| 2727 |
/// |
| 2728 |
/// If control reaches the end of the SPIR-V block, terminate it according |
| 2729 |
/// to `exit`. This function's return value indicates whether it acted on |
| 2730 |
/// this parameter or not; see [`BlockExitDisposition`]. |
| 2731 |
/// |
| 2732 |
/// If the block contains [`Break`] or [`Continue`] statements, |
| 2733 |
/// `loop_context` supplies the labels of the SPIR-V blocks to jump to. If |
| 2734 |
/// either of these labels are `None`, then it should have been a Naga |
| 2735 |
/// validation error for the corresponding statement to occur in this |
| 2736 |
/// context. |
| 2737 |
/// |
| 2738 |
/// [`Break`]: Statement::Break |
| 2739 |
/// [`Continue`]: Statement::Continue |
| 2740 |
fn write_block( |
| 2741 |
&mut self, |
| 2742 |
label_id: Word, |
| 2743 |
naga_block: &crate::Block, |
| 2744 |
exit: BlockExit, |
| 2745 |
loop_context: LoopContext, |
| 2746 |
debug_info: Option<&DebugInfoInner>, |
| 2747 |
) -> Result<BlockExitDisposition, Error> { |
| 2748 |
let mut block = Block::new(label_id); |
| 2749 |
for (statement, span) in naga_block.span_iter() { |
| 2750 |
if let (Some(debug_info), false) = ( |
| 2751 |
debug_info, |
| 2752 |
matches!( |
| 2753 |
statement, |
| 2754 |
&(Statement::Block(..) |
| 2755 |
| Statement::Break |
| 2756 |
| Statement::Continue |
| 2757 |
| Statement::Kill |
| 2758 |
| Statement::Return { .. } |
| 2759 |
| Statement::Loop { .. }) |
| 2760 |
), |
| 2761 |
) { |
| 2762 |
let loc: crate::SourceLocation = span.location(debug_info.source_code); |
| 2763 |
block.body.push(Instruction::line( |
| 2764 |
debug_info.source_file_id, |
| 2765 |
loc.line_number, |
| 2766 |
loc.line_position, |
| 2767 |
)); |
| 2768 |
}; |
| 2769 |
match *statement { |
| 2770 |
Statement::Emit(ref range) => { |
| 2771 |
for handle in range.clone() { |
| 2772 |
// omit const expressions as we've already cached those |
| 2773 |
if !self.expression_constness.is_const(handle) { |
| 2774 |
self.cache_expression_value(handle, &mut block)?; |
| 2775 |
} |
| 2776 |
} |
| 2777 |
} |
| 2778 |
Statement::Block(ref block_statements) => { |
| 2779 |
let scope_id = self.gen_id(); |
| 2780 |
self.function.consume(block, Instruction::branch(scope_id)); |
| 2781 |
|
| 2782 |
let merge_id = self.gen_id(); |
| 2783 |
let merge_used = self.write_block( |
| 2784 |
scope_id, |
| 2785 |
block_statements, |
| 2786 |
BlockExit::Branch { target: merge_id }, |
| 2787 |
loop_context, |
| 2788 |
debug_info, |
| 2789 |
)?; |
| 2790 |
|
| 2791 |
match merge_used { |
| 2792 |
BlockExitDisposition::Used => { |
| 2793 |
block = Block::new(merge_id); |
| 2794 |
} |
| 2795 |
BlockExitDisposition::Discarded => { |
| 2796 |
return Ok(BlockExitDisposition::Discarded); |
| 2797 |
} |
| 2798 |
} |
| 2799 |
} |
| 2800 |
Statement::If { |
| 2801 |
condition, |
| 2802 |
ref accept, |
| 2803 |
ref reject, |
| 2804 |
} => { |
| 2805 |
let condition_id = self.cached[condition]; |
| 2806 |
|
| 2807 |
let merge_id = self.gen_id(); |
| 2808 |
block.body.push(Instruction::selection_merge( |
| 2809 |
merge_id, |
| 2810 |
spirv::SelectionControl::NONE, |
| 2811 |
)); |
| 2812 |
|
| 2813 |
let accept_id = if accept.is_empty() { |
| 2814 |
None |
| 2815 |
} else { |
| 2816 |
Some(self.gen_id()) |
| 2817 |
}; |
| 2818 |
let reject_id = if reject.is_empty() { |
| 2819 |
None |
| 2820 |
} else { |
| 2821 |
Some(self.gen_id()) |
| 2822 |
}; |
| 2823 |
|
| 2824 |
self.function.consume( |
| 2825 |
block, |
| 2826 |
Instruction::branch_conditional( |
| 2827 |
condition_id, |
| 2828 |
accept_id.unwrap_or(merge_id), |
| 2829 |
reject_id.unwrap_or(merge_id), |
| 2830 |
), |
| 2831 |
); |
| 2832 |
|
| 2833 |
if let Some(block_id) = accept_id { |
| 2834 |
// We can ignore the `BlockExitDisposition` returned here because, |
| 2835 |
// even if `merge_id` is not actually reachable, it is always |
| 2836 |
// referred to by the `OpSelectionMerge` instruction we emitted |
| 2837 |
// earlier. |
| 2838 |
let _ = self.write_block( |
| 2839 |
block_id, |
| 2840 |
accept, |
| 2841 |
BlockExit::Branch { target: merge_id }, |
| 2842 |
loop_context, |
| 2843 |
debug_info, |
| 2844 |
)?; |
| 2845 |
} |
| 2846 |
if let Some(block_id) = reject_id { |
| 2847 |
// We can ignore the `BlockExitDisposition` returned here because, |
| 2848 |
// even if `merge_id` is not actually reachable, it is always |
| 2849 |
// referred to by the `OpSelectionMerge` instruction we emitted |
| 2850 |
// earlier. |
| 2851 |
let _ = self.write_block( |
| 2852 |
block_id, |
| 2853 |
reject, |
| 2854 |
BlockExit::Branch { target: merge_id }, |
| 2855 |
loop_context, |
| 2856 |
debug_info, |
| 2857 |
)?; |
| 2858 |
} |
| 2859 |
|
| 2860 |
block = Block::new(merge_id); |
| 2861 |
} |
| 2862 |
Statement::Switch { |
| 2863 |
selector, |
| 2864 |
ref cases, |
| 2865 |
} => { |
| 2866 |
let selector_id = self.cached[selector]; |
| 2867 |
|
| 2868 |
let merge_id = self.gen_id(); |
| 2869 |
block.body.push(Instruction::selection_merge( |
| 2870 |
merge_id, |
| 2871 |
spirv::SelectionControl::NONE, |
| 2872 |
)); |
| 2873 |
|
| 2874 |
let mut default_id = None; |
| 2875 |
// id of previous empty fall-through case |
| 2876 |
let mut last_id = None; |
| 2877 |
|
| 2878 |
let mut raw_cases = Vec::with_capacity(cases.len()); |
| 2879 |
let mut case_ids = Vec::with_capacity(cases.len()); |
| 2880 |
for case in cases.iter() { |
| 2881 |
// take id of previous empty fall-through case or generate a new one |
| 2882 |
let label_id = last_id.take().unwrap_or_else(|| self.gen_id()); |
| 2883 |
|
| 2884 |
if case.fall_through && case.body.is_empty() { |
| 2885 |
last_id = Some(label_id); |
| 2886 |
} |
| 2887 |
|
| 2888 |
case_ids.push(label_id); |
| 2889 |
|
| 2890 |
match case.value { |
| 2891 |
crate::SwitchValue::I32(value) => { |
| 2892 |
raw_cases.push(super::instructions::Case { |
| 2893 |
value: value as Word, |
| 2894 |
label_id, |
| 2895 |
}); |
| 2896 |
} |
| 2897 |
crate::SwitchValue::U32(value) => { |
| 2898 |
raw_cases.push(super::instructions::Case { value, label_id }); |
| 2899 |
} |
| 2900 |
crate::SwitchValue::Default => { |
| 2901 |
default_id = Some(label_id); |
| 2902 |
} |
| 2903 |
} |
| 2904 |
} |
| 2905 |
|
| 2906 |
let default_id = default_id.unwrap(); |
| 2907 |
|
| 2908 |
self.function.consume( |
| 2909 |
block, |
| 2910 |
Instruction::switch(selector_id, default_id, &raw_cases), |
| 2911 |
); |
| 2912 |
|
| 2913 |
let inner_context = LoopContext { |
| 2914 |
break_id: Some(merge_id), |
| 2915 |
..loop_context |
| 2916 |
}; |
| 2917 |
|
| 2918 |
for (i, (case, label_id)) in cases |
| 2919 |
.iter() |
| 2920 |
.zip(case_ids.iter()) |
| 2921 |
.filter(|&(case, _)| !(case.fall_through && case.body.is_empty())) |
| 2922 |
.enumerate() |
| 2923 |
{ |
| 2924 |
let case_finish_id = if case.fall_through { |
| 2925 |
case_ids[i + 1] |
| 2926 |
} else { |
| 2927 |
merge_id |
| 2928 |
}; |
| 2929 |
// We can ignore the `BlockExitDisposition` returned here because |
| 2930 |
// `case_finish_id` is always referred to by either: |
| 2931 |
// |
| 2932 |
// - the `OpSwitch`, if it's the next case's label for a |
| 2933 |
// fall-through, or |
| 2934 |
// |
| 2935 |
// - the `OpSelectionMerge`, if it's the switch's overall merge |
| 2936 |
// block because there's no fall-through. |
| 2937 |
let _ = self.write_block( |
| 2938 |
*label_id, |
| 2939 |
&case.body, |
| 2940 |
BlockExit::Branch { |
| 2941 |
target: case_finish_id, |
| 2942 |
}, |
| 2943 |
inner_context, |
| 2944 |
debug_info, |
| 2945 |
)?; |
| 2946 |
} |
| 2947 |
|
| 2948 |
block = Block::new(merge_id); |
| 2949 |
} |
| 2950 |
Statement::Loop { |
| 2951 |
ref body, |
| 2952 |
ref continuing, |
| 2953 |
break_if, |
| 2954 |
} => { |
| 2955 |
let preamble_id = self.gen_id(); |
| 2956 |
self.function |
| 2957 |
.consume(block, Instruction::branch(preamble_id)); |
| 2958 |
|
| 2959 |
let merge_id = self.gen_id(); |
| 2960 |
let body_id = self.gen_id(); |
| 2961 |
let continuing_id = self.gen_id(); |
| 2962 |
|
| 2963 |
// SPIR-V requires the continuing to the `OpLoopMerge`, |
| 2964 |
// so we have to start a new block with it. |
| 2965 |
block = Block::new(preamble_id); |
| 2966 |
// HACK the loop statement is begin with branch instruction, |
| 2967 |
// so we need to put `OpLine` debug info before merge instruction |
| 2968 |
if let Some(debug_info) = debug_info { |
| 2969 |
let loc: crate::SourceLocation = span.location(debug_info.source_code); |
| 2970 |
block.body.push(Instruction::line( |
| 2971 |
debug_info.source_file_id, |
| 2972 |
loc.line_number, |
| 2973 |
loc.line_position, |
| 2974 |
)) |
| 2975 |
} |
| 2976 |
block.body.push(Instruction::loop_merge( |
| 2977 |
merge_id, |
| 2978 |
continuing_id, |
| 2979 |
spirv::SelectionControl::NONE, |
| 2980 |
)); |
| 2981 |
|
| 2982 |
if self.force_loop_bounding { |
| 2983 |
block = self.write_force_bounded_loop_instructions(block, merge_id); |
| 2984 |
} |
| 2985 |
self.function.consume(block, Instruction::branch(body_id)); |
| 2986 |
|
| 2987 |
// We can ignore the `BlockExitDisposition` returned here because, |
| 2988 |
// even if `continuing_id` is not actually reachable, it is always |
| 2989 |
// referred to by the `OpLoopMerge` instruction we emitted earlier. |
| 2990 |
let _ = self.write_block( |
| 2991 |
body_id, |
| 2992 |
body, |
| 2993 |
BlockExit::Branch { |
| 2994 |
target: continuing_id, |
| 2995 |
}, |
| 2996 |
LoopContext { |
| 2997 |
continuing_id: Some(continuing_id), |
| 2998 |
break_id: Some(merge_id), |
| 2999 |
}, |
| 3000 |
debug_info, |
| 3001 |
)?; |
| 3002 |
|
| 3003 |
let exit = match break_if { |
| 3004 |
Some(condition) => BlockExit::BreakIf { |
| 3005 |
condition, |
| 3006 |
preamble_id, |
| 3007 |
}, |
| 3008 |
None => BlockExit::Branch { |
| 3009 |
target: preamble_id, |
| 3010 |
}, |
| 3011 |
}; |
| 3012 |
|
| 3013 |
// We can ignore the `BlockExitDisposition` returned here because, |
| 3014 |
// even if `merge_id` is not actually reachable, it is always referred |
| 3015 |
// to by the `OpLoopMerge` instruction we emitted earlier. |
| 3016 |
let _ = self.write_block( |
| 3017 |
continuing_id, |
| 3018 |
continuing, |
| 3019 |
exit, |
| 3020 |
LoopContext { |
| 3021 |
continuing_id: None, |
| 3022 |
break_id: Some(merge_id), |
| 3023 |
}, |
| 3024 |
debug_info, |
| 3025 |
)?; |
| 3026 |
|
| 3027 |
block = Block::new(merge_id); |
| 3028 |
} |
| 3029 |
Statement::Break => { |
| 3030 |
self.function |
| 3031 |
.consume(block, Instruction::branch(loop_context.break_id.unwrap())); |
| 3032 |
return Ok(BlockExitDisposition::Discarded); |
| 3033 |
} |
| 3034 |
Statement::Continue => { |
| 3035 |
self.function.consume( |
| 3036 |
block, |
| 3037 |
Instruction::branch(loop_context.continuing_id.unwrap()), |
| 3038 |
); |
| 3039 |
return Ok(BlockExitDisposition::Discarded); |
| 3040 |
} |
| 3041 |
Statement::Return { value: Some(value) } => { |
| 3042 |
let value_id = self.cached[value]; |
| 3043 |
let instruction = match self.function.entry_point_context { |
| 3044 |
// If this is an entry point, and we need to return anything, |
| 3045 |
// let's instead store the output variables and return `void`. |
| 3046 |
Some(ref context) => { |
| 3047 |
self.writer.write_entry_point_return( |
| 3048 |
value_id, |
| 3049 |
self.ir_function.result.as_ref().unwrap(), |
| 3050 |
&context.results, |
| 3051 |
&mut block.body, |
| 3052 |
)?; |
| 3053 |
Instruction::return_void() |
| 3054 |
} |
| 3055 |
None => Instruction::return_value(value_id), |
| 3056 |
}; |
| 3057 |
self.function.consume(block, instruction); |
| 3058 |
return Ok(BlockExitDisposition::Discarded); |
| 3059 |
} |
| 3060 |
Statement::Return { value: None } => { |
| 3061 |
self.function.consume(block, Instruction::return_void()); |
| 3062 |
return Ok(BlockExitDisposition::Discarded); |
| 3063 |
} |
| 3064 |
Statement::Kill => { |
| 3065 |
self.function.consume(block, Instruction::kill()); |
| 3066 |
return Ok(BlockExitDisposition::Discarded); |
| 3067 |
} |
| 3068 |
Statement::Barrier(flags) => { |
| 3069 |
self.writer.write_barrier(flags, &mut block); |
| 3070 |
} |
| 3071 |
Statement::Store { pointer, value } => { |
| 3072 |
let value_id = self.cached[value]; |
| 3073 |
match self.write_access_chain( |
| 3074 |
pointer, |
| 3075 |
&mut block, |
| 3076 |
AccessTypeAdjustment::None, |
| 3077 |
)? { |
| 3078 |
ExpressionPointer::Ready { pointer_id } => { |
| 3079 |
let atomic_space = match *self.fun_info[pointer] |
| 3080 |
.ty |
| 3081 |
.inner_with(&self.ir_module.types) |
| 3082 |
{ |
| 3083 |
crate::TypeInner::Pointer { base, space } => { |
| 3084 |
match self.ir_module.types[base].inner { |
| 3085 |
crate::TypeInner::Atomic { .. } => Some(space), |
| 3086 |
_ => None, |
| 3087 |
} |
| 3088 |
} |
| 3089 |
_ => None, |
| 3090 |
}; |
| 3091 |
let instruction = if let Some(space) = atomic_space { |
| 3092 |
let (semantics, scope) = space.to_spirv_semantics_and_scope(); |
| 3093 |
let scope_constant_id = self.get_scope_constant(scope as u32); |
| 3094 |
let semantics_id = self.get_index_constant(semantics.bits()); |
| 3095 |
Instruction::atomic_store( |
| 3096 |
pointer_id, |
| 3097 |
scope_constant_id, |
| 3098 |
semantics_id, |
| 3099 |
value_id, |
| 3100 |
) |
| 3101 |
} else { |
| 3102 |
Instruction::store(pointer_id, value_id, None) |
| 3103 |
}; |
| 3104 |
block.body.push(instruction); |
| 3105 |
} |
| 3106 |
ExpressionPointer::Conditional { condition, access } => { |
| 3107 |
let mut selection = Selection::start(&mut block, ()); |
| 3108 |
selection.if_true(self, condition, ()); |
| 3109 |
|
| 3110 |
// The in-bounds path. Perform the access and the store. |
| 3111 |
let pointer_id = access.result_id.unwrap(); |
| 3112 |
selection.block().body.push(access); |
| 3113 |
selection |
| 3114 |
.block() |
| 3115 |
.body |
| 3116 |
.push(Instruction::store(pointer_id, value_id, None)); |
| 3117 |
|
| 3118 |
// Finish the in-bounds block and start the merge block. This |
| 3119 |
// is the block we'll leave current on return. |
| 3120 |
selection.finish(self, ()); |
| 3121 |
} |
| 3122 |
}; |
| 3123 |
} |
| 3124 |
Statement::ImageStore { |
| 3125 |
image, |
| 3126 |
coordinate, |
| 3127 |
array_index, |
| 3128 |
value, |
| 3129 |
} => self.write_image_store(image, coordinate, array_index, value, &mut block)?, |
| 3130 |
Statement::Call { |
| 3131 |
function: local_function, |
| 3132 |
ref arguments, |
| 3133 |
result, |
| 3134 |
} => { |
| 3135 |
let id = self.gen_id(); |
| 3136 |
self.temp_list.clear(); |
| 3137 |
for &argument in arguments { |
| 3138 |
self.temp_list.push(self.cached[argument]); |
| 3139 |
} |
| 3140 |
|
| 3141 |
let type_id = match result { |
| 3142 |
Some(expr) => { |
| 3143 |
self.cached[expr] = id; |
| 3144 |
self.get_expression_type_id(&self.fun_info[expr].ty) |
| 3145 |
} |
| 3146 |
None => self.writer.void_type, |
| 3147 |
}; |
| 3148 |
|
| 3149 |
block.body.push(Instruction::function_call( |
| 3150 |
type_id, |
| 3151 |
id, |
| 3152 |
self.writer.lookup_function[&local_function], |
| 3153 |
&self.temp_list, |
| 3154 |
)); |
| 3155 |
} |
| 3156 |
Statement::Atomic { |
| 3157 |
pointer, |
| 3158 |
ref fun, |
| 3159 |
value, |
| 3160 |
result, |
| 3161 |
} => { |
| 3162 |
let id = self.gen_id(); |
| 3163 |
// Compare-and-exchange operations produce a struct result, |
| 3164 |
// so use `result`'s type if it is available. For no-result |
| 3165 |
// operations, fall back to `value`'s type. |
| 3166 |
let result_type_id = |
| 3167 |
self.get_expression_type_id(&self.fun_info[result.unwrap_or(value)].ty); |
| 3168 |
|
| 3169 |
if let Some(result) = result { |
| 3170 |
self.cached[result] = id; |
| 3171 |
} |
| 3172 |
|
| 3173 |
let pointer_id = match self.write_access_chain( |
| 3174 |
pointer, |
| 3175 |
&mut block, |
| 3176 |
AccessTypeAdjustment::None, |
| 3177 |
)? { |
| 3178 |
ExpressionPointer::Ready { pointer_id } => pointer_id, |
| 3179 |
ExpressionPointer::Conditional { .. } => { |
| 3180 |
return Err(Error::FeatureNotImplemented( |
| 3181 |
"Atomics out-of-bounds handling", |
| 3182 |
)); |
| 3183 |
} |
| 3184 |
}; |
| 3185 |
|
| 3186 |
let space = self.fun_info[pointer] |
| 3187 |
.ty |
| 3188 |
.inner_with(&self.ir_module.types) |
| 3189 |
.pointer_space() |
| 3190 |
.unwrap(); |
| 3191 |
let (semantics, scope) = space.to_spirv_semantics_and_scope(); |
| 3192 |
let scope_constant_id = self.get_scope_constant(scope as u32); |
| 3193 |
let semantics_id = self.get_index_constant(semantics.bits()); |
| 3194 |
let value_id = self.cached[value]; |
| 3195 |
let value_inner = self.fun_info[value].ty.inner_with(&self.ir_module.types); |
| 3196 |
|
| 3197 |
let crate::TypeInner::Scalar(scalar) = *value_inner else { |
| 3198 |
return Err(Error::FeatureNotImplemented( |
| 3199 |
"Atomics with non-scalar values", |
| 3200 |
)); |
| 3201 |
}; |
| 3202 |
|
| 3203 |
let instruction = match *fun { |
| 3204 |
crate::AtomicFunction::Add => { |
| 3205 |
let spirv_op = match scalar.kind { |
| 3206 |
crate::ScalarKind::Sint | crate::ScalarKind::Uint => { |
| 3207 |
spirv::Op::AtomicIAdd |
| 3208 |
} |
| 3209 |
crate::ScalarKind::Float => spirv::Op::AtomicFAddEXT, |
| 3210 |
_ => unimplemented!(), |
| 3211 |
}; |
| 3212 |
Instruction::atomic_binary( |
| 3213 |
spirv_op, |
| 3214 |
result_type_id, |
| 3215 |
id, |
| 3216 |
pointer_id, |
| 3217 |
scope_constant_id, |
| 3218 |
semantics_id, |
| 3219 |
value_id, |
| 3220 |
) |
| 3221 |
} |
| 3222 |
crate::AtomicFunction::Subtract => { |
| 3223 |
let (spirv_op, value_id) = match scalar.kind { |
| 3224 |
crate::ScalarKind::Sint | crate::ScalarKind::Uint => { |
| 3225 |
(spirv::Op::AtomicISub, value_id) |
| 3226 |
} |
| 3227 |
crate::ScalarKind::Float => { |
| 3228 |
// HACK: SPIR-V doesn't have a atomic subtraction, |
| 3229 |
// so we add the negated value instead. |
| 3230 |
let neg_result_id = self.gen_id(); |
| 3231 |
block.body.push(Instruction::unary( |
| 3232 |
spirv::Op::FNegate, |
| 3233 |
result_type_id, |
| 3234 |
neg_result_id, |
| 3235 |
value_id, |
| 3236 |
)); |
| 3237 |
(spirv::Op::AtomicFAddEXT, neg_result_id) |
| 3238 |
} |
| 3239 |
_ => unimplemented!(), |
| 3240 |
}; |
| 3241 |
Instruction::atomic_binary( |
| 3242 |
spirv_op, |
| 3243 |
result_type_id, |
| 3244 |
id, |
| 3245 |
pointer_id, |
| 3246 |
scope_constant_id, |
| 3247 |
semantics_id, |
| 3248 |
value_id, |
| 3249 |
) |
| 3250 |
} |
| 3251 |
crate::AtomicFunction::And => { |
| 3252 |
let spirv_op = match scalar.kind { |
| 3253 |
crate::ScalarKind::Sint | crate::ScalarKind::Uint => { |
| 3254 |
spirv::Op::AtomicAnd |
| 3255 |
} |
| 3256 |
_ => unimplemented!(), |
| 3257 |
}; |
| 3258 |
Instruction::atomic_binary( |
| 3259 |
spirv_op, |
| 3260 |
result_type_id, |
| 3261 |
id, |
| 3262 |
pointer_id, |
| 3263 |
scope_constant_id, |
| 3264 |
semantics_id, |
| 3265 |
value_id, |
| 3266 |
) |
| 3267 |
} |
| 3268 |
crate::AtomicFunction::InclusiveOr => { |
| 3269 |
let spirv_op = match scalar.kind { |
| 3270 |
crate::ScalarKind::Sint | crate::ScalarKind::Uint => { |
| 3271 |
spirv::Op::AtomicOr |
| 3272 |
} |
| 3273 |
_ => unimplemented!(), |
| 3274 |
}; |
| 3275 |
Instruction::atomic_binary( |
| 3276 |
spirv_op, |
| 3277 |
result_type_id, |
| 3278 |
id, |
| 3279 |
pointer_id, |
| 3280 |
scope_constant_id, |
| 3281 |
semantics_id, |
| 3282 |
value_id, |
| 3283 |
) |
| 3284 |
} |
| 3285 |
crate::AtomicFunction::ExclusiveOr => { |
| 3286 |
let spirv_op = match scalar.kind { |
| 3287 |
crate::ScalarKind::Sint | crate::ScalarKind::Uint => { |
| 3288 |
spirv::Op::AtomicXor |
| 3289 |
} |
| 3290 |
_ => unimplemented!(), |
| 3291 |
}; |
| 3292 |
Instruction::atomic_binary( |
| 3293 |
spirv_op, |
| 3294 |
result_type_id, |
| 3295 |
id, |
| 3296 |
pointer_id, |
| 3297 |
scope_constant_id, |
| 3298 |
semantics_id, |
| 3299 |
value_id, |
| 3300 |
) |
| 3301 |
} |
| 3302 |
crate::AtomicFunction::Min => { |
| 3303 |
let spirv_op = match scalar.kind { |
| 3304 |
crate::ScalarKind::Sint => spirv::Op::AtomicSMin, |
| 3305 |
crate::ScalarKind::Uint => spirv::Op::AtomicUMin, |
| 3306 |
_ => unimplemented!(), |
| 3307 |
}; |
| 3308 |
Instruction::atomic_binary( |
| 3309 |
spirv_op, |
| 3310 |
result_type_id, |
| 3311 |
id, |
| 3312 |
pointer_id, |
| 3313 |
scope_constant_id, |
| 3314 |
semantics_id, |
| 3315 |
value_id, |
| 3316 |
) |
| 3317 |
} |
| 3318 |
crate::AtomicFunction::Max => { |
| 3319 |
let spirv_op = match scalar.kind { |
| 3320 |
crate::ScalarKind::Sint => spirv::Op::AtomicSMax, |
| 3321 |
crate::ScalarKind::Uint => spirv::Op::AtomicUMax, |
| 3322 |
_ => unimplemented!(), |
| 3323 |
}; |
| 3324 |
Instruction::atomic_binary( |
| 3325 |
spirv_op, |
| 3326 |
result_type_id, |
| 3327 |
id, |
| 3328 |
pointer_id, |
| 3329 |
scope_constant_id, |
| 3330 |
semantics_id, |
| 3331 |
value_id, |
| 3332 |
) |
| 3333 |
} |
| 3334 |
crate::AtomicFunction::Exchange { compare: None } => { |
| 3335 |
Instruction::atomic_binary( |
| 3336 |
spirv::Op::AtomicExchange, |
| 3337 |
result_type_id, |
| 3338 |
id, |
| 3339 |
pointer_id, |
| 3340 |
scope_constant_id, |
| 3341 |
semantics_id, |
| 3342 |
value_id, |
| 3343 |
) |
| 3344 |
} |
| 3345 |
crate::AtomicFunction::Exchange { compare: Some(cmp) } => { |
| 3346 |
let scalar_type_id = |
| 3347 |
self.get_numeric_type_id(NumericType::Scalar(scalar)); |
| 3348 |
let bool_type_id = |
| 3349 |
self.get_numeric_type_id(NumericType::Scalar(crate::Scalar::BOOL)); |
| 3350 |
|
| 3351 |
let cas_result_id = self.gen_id(); |
| 3352 |
let equality_result_id = self.gen_id(); |
| 3353 |
let equality_operator = match scalar.kind { |
| 3354 |
crate::ScalarKind::Sint | crate::ScalarKind::Uint => { |
| 3355 |
spirv::Op::IEqual |
| 3356 |
} |
| 3357 |
_ => unimplemented!(), |
| 3358 |
}; |
| 3359 |
let mut cas_instr = Instruction::new(spirv::Op::AtomicCompareExchange); |
| 3360 |
cas_instr.set_type(scalar_type_id); |
| 3361 |
cas_instr.set_result(cas_result_id); |
| 3362 |
cas_instr.add_operand(pointer_id); |
| 3363 |
cas_instr.add_operand(scope_constant_id); |
| 3364 |
cas_instr.add_operand(semantics_id); // semantics if equal |
| 3365 |
cas_instr.add_operand(semantics_id); // semantics if not equal |
| 3366 |
cas_instr.add_operand(value_id); |
| 3367 |
cas_instr.add_operand(self.cached[cmp]); |
| 3368 |
block.body.push(cas_instr); |
| 3369 |
block.body.push(Instruction::binary( |
| 3370 |
equality_operator, |
| 3371 |
bool_type_id, |
| 3372 |
equality_result_id, |
| 3373 |
cas_result_id, |
| 3374 |
self.cached[cmp], |
| 3375 |
)); |
| 3376 |
Instruction::composite_construct( |
| 3377 |
result_type_id, |
| 3378 |
id, |
| 3379 |
&[cas_result_id, equality_result_id], |
| 3380 |
) |
| 3381 |
} |
| 3382 |
}; |
| 3383 |
|
| 3384 |
block.body.push(instruction); |
| 3385 |
} |
| 3386 |
Statement::ImageAtomic { |
| 3387 |
image, |
| 3388 |
coordinate, |
| 3389 |
array_index, |
| 3390 |
fun, |
| 3391 |
value, |
| 3392 |
} => { |
| 3393 |
self.write_image_atomic( |
| 3394 |
image, |
| 3395 |
coordinate, |
| 3396 |
array_index, |
| 3397 |
fun, |
| 3398 |
value, |
| 3399 |
&mut block, |
| 3400 |
)?; |
| 3401 |
} |
| 3402 |
Statement::WorkGroupUniformLoad { pointer, result } => { |
| 3403 |
self.writer |
| 3404 |
.write_barrier(crate::Barrier::WORK_GROUP, &mut block); |
| 3405 |
let result_type_id = self.get_expression_type_id(&self.fun_info[result].ty); |
| 3406 |
// Embed the body of |
| 3407 |
match self.write_access_chain( |
| 3408 |
pointer, |
| 3409 |
&mut block, |
| 3410 |
AccessTypeAdjustment::None, |
| 3411 |
)? { |
| 3412 |
ExpressionPointer::Ready { pointer_id } => { |
| 3413 |
let id = self.gen_id(); |
| 3414 |
block.body.push(Instruction::load( |
| 3415 |
result_type_id, |
| 3416 |
id, |
| 3417 |
pointer_id, |
| 3418 |
None, |
| 3419 |
)); |
| 3420 |
self.cached[result] = id; |
| 3421 |
} |
| 3422 |
ExpressionPointer::Conditional { condition, access } => { |
| 3423 |
self.cached[result] = self.write_conditional_indexed_load( |
| 3424 |
result_type_id, |
| 3425 |
condition, |
| 3426 |
&mut block, |
| 3427 |
move |id_gen, block| { |
| 3428 |
// The in-bounds path. Perform the access and the load. |
| 3429 |
let pointer_id = access.result_id.unwrap(); |
| 3430 |
let value_id = id_gen.next(); |
| 3431 |
block.body.push(access); |
| 3432 |
block.body.push(Instruction::load( |
| 3433 |
result_type_id, |
| 3434 |
value_id, |
| 3435 |
pointer_id, |
| 3436 |
None, |
| 3437 |
)); |
| 3438 |
value_id |
| 3439 |
}, |
| 3440 |
) |
| 3441 |
} |
| 3442 |
} |
| 3443 |
self.writer |
| 3444 |
.write_barrier(crate::Barrier::WORK_GROUP, &mut block); |
| 3445 |
} |
| 3446 |
Statement::RayQuery { query, ref fun } => { |
| 3447 |
self.write_ray_query_function(query, fun, &mut block); |
| 3448 |
} |
| 3449 |
Statement::SubgroupBallot { |
| 3450 |
result, |
| 3451 |
ref predicate, |
| 3452 |
} => { |
| 3453 |
self.write_subgroup_ballot(predicate, result, &mut block)?; |
| 3454 |
} |
| 3455 |
Statement::SubgroupCollectiveOperation { |
| 3456 |
ref op, |
| 3457 |
ref collective_op, |
| 3458 |
argument, |
| 3459 |
result, |
| 3460 |
} => { |
| 3461 |
self.write_subgroup_operation(op, collective_op, argument, result, &mut block)?; |
| 3462 |
} |
| 3463 |
Statement::SubgroupGather { |
| 3464 |
ref mode, |
| 3465 |
argument, |
| 3466 |
result, |
| 3467 |
} => { |
| 3468 |
self.write_subgroup_gather(mode, argument, result, &mut block)?; |
| 3469 |
} |
| 3470 |
} |
| 3471 |
} |
| 3472 |
|
| 3473 |
let termination = match exit { |
| 3474 |
// We're generating code for the top-level Block of the function, so we |
| 3475 |
// need to end it with some kind of return instruction. |
| 3476 |
BlockExit::Return => match self.ir_function.result { |
| 3477 |
Some(ref result) if self.function.entry_point_context.is_none() => { |
| 3478 |
let type_id = self.get_handle_type_id(result.ty); |
| 3479 |
let null_id = self.writer.get_constant_null(type_id); |
| 3480 |
Instruction::return_value(null_id) |
| 3481 |
} |
| 3482 |
_ => Instruction::return_void(), |
| 3483 |
}, |
| 3484 |
BlockExit::Branch { target } => Instruction::branch(target), |
| 3485 |
BlockExit::BreakIf { |
| 3486 |
condition, |
| 3487 |
preamble_id, |
| 3488 |
} => { |
| 3489 |
let condition_id = self.cached[condition]; |
| 3490 |
|
| 3491 |
Instruction::branch_conditional( |
| 3492 |
condition_id, |
| 3493 |
loop_context.break_id.unwrap(), |
| 3494 |
preamble_id, |
| 3495 |
) |
| 3496 |
} |
| 3497 |
}; |
| 3498 |
|
| 3499 |
self.function.consume(block, termination); |
| 3500 |
Ok(BlockExitDisposition::Used) |
| 3501 |
} |
| 3502 |
|
| 3503 |
pub(super) fn write_function_body( |
| 3504 |
&mut self, |
| 3505 |
entry_id: Word, |
| 3506 |
debug_info: Option<&DebugInfoInner>, |
| 3507 |
) -> Result<(), Error> { |
| 3508 |
// We can ignore the `BlockExitDisposition` returned here because |
| 3509 |
// `BlockExit::Return` doesn't refer to a block. |
| 3510 |
let _ = self.write_block( |
| 3511 |
entry_id, |
| 3512 |
&self.ir_function.body, |
| 3513 |
BlockExit::Return, |
| 3514 |
LoopContext::default(), |
| 3515 |
debug_info, |
| 3516 |
)?; |
| 3517 |
|
| 3518 |
Ok(()) |
| 3519 |
} |
| 3520 |
} |