| 1 |
/*! |
| 2 |
Frontend for [SPIR-V][spv] (Standard Portable Intermediate Representation). |
| 3 |
|
| 4 |
## ID lookups |
| 5 |
|
| 6 |
Our IR links to everything with `Handle`, while SPIR-V uses IDs. |
| 7 |
In order to keep track of the associations, the parser has many lookup tables. |
| 8 |
There map `spv::Word` into a specific IR handle, plus potentially a bit of |
| 9 |
extra info, such as the related SPIR-V type ID. |
| 10 |
TODO: would be nice to find ways that avoid looking up as much |
| 11 |
|
| 12 |
## Inputs/Outputs |
| 13 |
|
| 14 |
We create a private variable for each input/output. The relevant inputs are |
| 15 |
populated at the start of an entry point. The outputs are saved at the end. |
| 16 |
|
| 17 |
The function associated with an entry point is wrapped in another function, |
| 18 |
such that we can handle any `Return` statements without problems. |
| 19 |
|
| 20 |
## Row-major matrices |
| 21 |
|
| 22 |
We don't handle them natively, since the IR only expects column majority. |
| 23 |
Instead, we detect when such matrix is accessed in the `OpAccessChain`, |
| 24 |
and we generate a parallel expression that loads the value, but transposed. |
| 25 |
This value then gets used instead of `OpLoad` result later on. |
| 26 |
|
| 27 |
[spv]: https://www.khronos.org/registry/SPIR-V/ |
| 28 |
*/ |
| 29 |
|
| 30 |
mod convert; |
| 31 |
mod error; |
| 32 |
mod function; |
| 33 |
mod image; |
| 34 |
mod null; |
| 35 |
|
| 36 |
pub use error::Error; |
| 37 |
|
| 38 |
use alloc::{borrow::ToOwned, format, string::String, vec, vec::Vec}; |
| 39 |
use core::{convert::TryInto, mem, num::NonZeroU32}; |
| 40 |
use std::path::PathBuf; |
| 41 |
|
| 42 |
use half::f16; |
| 43 |
use petgraph::graphmap::GraphMap; |
| 44 |
|
| 45 |
use super::atomic_upgrade::Upgrades; |
| 46 |
use crate::{ |
| 47 |
arena::{Arena, Handle, UniqueArena}, |
| 48 |
proc::{Alignment, Layouter}, |
| 49 |
FastHashMap, FastHashSet, FastIndexMap, |
| 50 |
}; |
| 51 |
use convert::*; |
| 52 |
use function::*; |
| 53 |
|
| 54 |
pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ |
| 55 |
spirv::Capability::Shader, |
| 56 |
spirv::Capability::VulkanMemoryModel, |
| 57 |
spirv::Capability::ClipDistance, |
| 58 |
spirv::Capability::CullDistance, |
| 59 |
spirv::Capability::SampleRateShading, |
| 60 |
spirv::Capability::DerivativeControl, |
| 61 |
spirv::Capability::Matrix, |
| 62 |
spirv::Capability::ImageQuery, |
| 63 |
spirv::Capability::Sampled1D, |
| 64 |
spirv::Capability::Image1D, |
| 65 |
spirv::Capability::SampledCubeArray, |
| 66 |
spirv::Capability::ImageCubeArray, |
| 67 |
spirv::Capability::StorageImageExtendedFormats, |
| 68 |
spirv::Capability::Int8, |
| 69 |
spirv::Capability::Int16, |
| 70 |
spirv::Capability::Int64, |
| 71 |
spirv::Capability::Int64Atomics, |
| 72 |
spirv::Capability::Float16, |
| 73 |
spirv::Capability::AtomicFloat32AddEXT, |
| 74 |
spirv::Capability::Float64, |
| 75 |
spirv::Capability::Geometry, |
| 76 |
spirv::Capability::MultiView, |
| 77 |
spirv::Capability::StorageBuffer16BitAccess, |
| 78 |
spirv::Capability::UniformAndStorageBuffer16BitAccess, |
| 79 |
spirv::Capability::GroupNonUniform, |
| 80 |
spirv::Capability::GroupNonUniformVote, |
| 81 |
spirv::Capability::GroupNonUniformArithmetic, |
| 82 |
spirv::Capability::GroupNonUniformBallot, |
| 83 |
spirv::Capability::GroupNonUniformShuffle, |
| 84 |
spirv::Capability::GroupNonUniformShuffleRelative, |
| 85 |
// tricky ones |
| 86 |
spirv::Capability::UniformBufferArrayDynamicIndexing, |
| 87 |
spirv::Capability::StorageBufferArrayDynamicIndexing, |
| 88 |
]; |
| 89 |
pub const SUPPORTED_EXTENSIONS: &[&str] = &[ |
| 90 |
"SPV_KHR_storage_buffer_storage_class", |
| 91 |
"SPV_KHR_vulkan_memory_model", |
| 92 |
"SPV_KHR_multiview", |
| 93 |
"SPV_EXT_shader_atomic_float_add", |
| 94 |
"SPV_KHR_16bit_storage", |
| 95 |
]; |
| 96 |
pub const SUPPORTED_EXT_SETS: &[&str] = &["GLSL.std.450"]; |
| 97 |
|
| 98 |
#[derive(Copy, Clone)] |
| 99 |
pub struct Instruction { |
| 100 |
op: spirv::Op, |
| 101 |
wc: u16, |
| 102 |
} |
| 103 |
|
| 104 |
impl Instruction { |
| 105 |
const fn expect(self, count: u16) -> Result<(), Error> { |
| 106 |
if self.wc == count { |
| 107 |
Ok(()) |
| 108 |
} else { |
| 109 |
Err(Error::InvalidOperandCount(self.op, self.wc)) |
| 110 |
} |
| 111 |
} |
| 112 |
|
| 113 |
fn expect_at_least(self, count: u16) -> Result<u16, Error> { |
| 114 |
self.wc |
| 115 |
.checked_sub(count) |
| 116 |
.ok_or(Error::InvalidOperandCount(self.op, self.wc)) |
| 117 |
} |
| 118 |
} |
| 119 |
|
| 120 |
impl crate::TypeInner { |
| 121 |
fn can_comparison_sample(&self, module: &crate::Module) -> bool { |
| 122 |
match *self { |
| 123 |
crate::TypeInner::Image { |
| 124 |
class: |
| 125 |
crate::ImageClass::Sampled { |
| 126 |
kind: crate::ScalarKind::Float, |
| 127 |
multi: false, |
| 128 |
}, |
| 129 |
.. |
| 130 |
} => true, |
| 131 |
crate::TypeInner::Sampler { .. } => true, |
| 132 |
crate::TypeInner::BindingArray { base, .. } => { |
| 133 |
module.types[base].inner.can_comparison_sample(module) |
| 134 |
} |
| 135 |
_ => false, |
| 136 |
} |
| 137 |
} |
| 138 |
} |
| 139 |
|
| 140 |
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)] |
| 141 |
pub enum ModuleState { |
| 142 |
Empty, |
| 143 |
Capability, |
| 144 |
Extension, |
| 145 |
ExtInstImport, |
| 146 |
MemoryModel, |
| 147 |
EntryPoint, |
| 148 |
ExecutionMode, |
| 149 |
Source, |
| 150 |
Name, |
| 151 |
ModuleProcessed, |
| 152 |
Annotation, |
| 153 |
Type, |
| 154 |
Function, |
| 155 |
} |
| 156 |
|
| 157 |
trait LookupHelper { |
| 158 |
type Target; |
| 159 |
fn lookup(&self, key: spirv::Word) -> Result<&Self::Target, Error>; |
| 160 |
} |
| 161 |
|
| 162 |
impl<T> LookupHelper for FastHashMap<spirv::Word, T> { |
| 163 |
type Target = T; |
| 164 |
fn lookup(&self, key: spirv::Word) -> Result<&T, Error> { |
| 165 |
self.get(&key).ok_or(Error::InvalidId(key)) |
| 166 |
} |
| 167 |
} |
| 168 |
|
| 169 |
impl crate::ImageDimension { |
| 170 |
const fn required_coordinate_size(&self) -> Option<crate::VectorSize> { |
| 171 |
match *self { |
| 172 |
crate::ImageDimension::D1 => None, |
| 173 |
crate::ImageDimension::D2 => Some(crate::VectorSize::Bi), |
| 174 |
crate::ImageDimension::D3 => Some(crate::VectorSize::Tri), |
| 175 |
crate::ImageDimension::Cube => Some(crate::VectorSize::Tri), |
| 176 |
} |
| 177 |
} |
| 178 |
} |
| 179 |
|
| 180 |
type MemberIndex = u32; |
| 181 |
|
| 182 |
bitflags::bitflags! { |
| 183 |
#[derive(Clone, Copy, Debug, Default)] |
| 184 |
struct DecorationFlags: u32 { |
| 185 |
const NON_READABLE = 0x1; |
| 186 |
const NON_WRITABLE = 0x2; |
| 187 |
} |
| 188 |
} |
| 189 |
|
| 190 |
impl DecorationFlags { |
| 191 |
fn to_storage_access(self) -> crate::StorageAccess { |
| 192 |
let mut access = crate::StorageAccess::LOAD | crate::StorageAccess::STORE; |
| 193 |
if self.contains(DecorationFlags::NON_READABLE) { |
| 194 |
access &= !crate::StorageAccess::LOAD; |
| 195 |
} |
| 196 |
if self.contains(DecorationFlags::NON_WRITABLE) { |
| 197 |
access &= !crate::StorageAccess::STORE; |
| 198 |
} |
| 199 |
access |
| 200 |
} |
| 201 |
} |
| 202 |
|
| 203 |
#[derive(Debug, PartialEq)] |
| 204 |
enum Majority { |
| 205 |
Column, |
| 206 |
Row, |
| 207 |
} |
| 208 |
|
| 209 |
#[derive(Debug, Default)] |
| 210 |
struct Decoration { |
| 211 |
name: Option<String>, |
| 212 |
built_in: Option<spirv::Word>, |
| 213 |
location: Option<spirv::Word>, |
| 214 |
desc_set: Option<spirv::Word>, |
| 215 |
desc_index: Option<spirv::Word>, |
| 216 |
specialization_constant_id: Option<spirv::Word>, |
| 217 |
storage_buffer: bool, |
| 218 |
offset: Option<spirv::Word>, |
| 219 |
array_stride: Option<NonZeroU32>, |
| 220 |
matrix_stride: Option<NonZeroU32>, |
| 221 |
matrix_major: Option<Majority>, |
| 222 |
invariant: bool, |
| 223 |
interpolation: Option<crate::Interpolation>, |
| 224 |
sampling: Option<crate::Sampling>, |
| 225 |
flags: DecorationFlags, |
| 226 |
} |
| 227 |
|
| 228 |
impl Decoration { |
| 229 |
fn debug_name(&self) -> &str { |
| 230 |
match self.name { |
| 231 |
Some(ref name) => name.as_str(), |
| 232 |
None => "?", |
| 233 |
} |
| 234 |
} |
| 235 |
|
| 236 |
const fn resource_binding(&self) -> Option<crate::ResourceBinding> { |
| 237 |
match *self { |
| 238 |
Decoration { |
| 239 |
desc_set: Some(group), |
| 240 |
desc_index: Some(binding), |
| 241 |
.. |
| 242 |
} => Some(crate::ResourceBinding { group, binding }), |
| 243 |
_ => None, |
| 244 |
} |
| 245 |
} |
| 246 |
|
| 247 |
fn io_binding(&self) -> Result<crate::Binding, Error> { |
| 248 |
match *self { |
| 249 |
Decoration { |
| 250 |
built_in: Some(built_in), |
| 251 |
location: None, |
| 252 |
invariant, |
| 253 |
.. |
| 254 |
} => Ok(crate::Binding::BuiltIn(map_builtin(built_in, invariant)?)), |
| 255 |
Decoration { |
| 256 |
built_in: None, |
| 257 |
location: Some(location), |
| 258 |
interpolation, |
| 259 |
sampling, |
| 260 |
.. |
| 261 |
} => Ok(crate::Binding::Location { |
| 262 |
location, |
| 263 |
interpolation, |
| 264 |
sampling, |
| 265 |
blend_src: None, |
| 266 |
}), |
| 267 |
_ => Err(Error::MissingDecoration(spirv::Decoration::Location)), |
| 268 |
} |
| 269 |
} |
| 270 |
} |
| 271 |
|
| 272 |
#[derive(Debug)] |
| 273 |
struct LookupFunctionType { |
| 274 |
parameter_type_ids: Vec<spirv::Word>, |
| 275 |
return_type_id: spirv::Word, |
| 276 |
} |
| 277 |
|
| 278 |
struct LookupFunction { |
| 279 |
handle: Handle<crate::Function>, |
| 280 |
parameters_sampling: Vec<image::SamplingFlags>, |
| 281 |
} |
| 282 |
|
| 283 |
#[derive(Debug)] |
| 284 |
struct EntryPoint { |
| 285 |
stage: crate::ShaderStage, |
| 286 |
name: String, |
| 287 |
early_depth_test: Option<crate::EarlyDepthTest>, |
| 288 |
workgroup_size: [u32; 3], |
| 289 |
variable_ids: Vec<spirv::Word>, |
| 290 |
} |
| 291 |
|
| 292 |
#[derive(Clone, Debug)] |
| 293 |
struct LookupType { |
| 294 |
handle: Handle<crate::Type>, |
| 295 |
base_id: Option<spirv::Word>, |
| 296 |
} |
| 297 |
|
| 298 |
#[derive(Debug)] |
| 299 |
enum Constant { |
| 300 |
Constant(Handle<crate::Constant>), |
| 301 |
Override(Handle<crate::Override>), |
| 302 |
} |
| 303 |
|
| 304 |
impl Constant { |
| 305 |
const fn to_expr(&self) -> crate::Expression { |
| 306 |
match *self { |
| 307 |
Self::Constant(c) => crate::Expression::Constant(c), |
| 308 |
Self::Override(o) => crate::Expression::Override(o), |
| 309 |
} |
| 310 |
} |
| 311 |
} |
| 312 |
|
| 313 |
#[derive(Debug)] |
| 314 |
struct LookupConstant { |
| 315 |
inner: Constant, |
| 316 |
type_id: spirv::Word, |
| 317 |
} |
| 318 |
|
| 319 |
#[derive(Debug)] |
| 320 |
enum Variable { |
| 321 |
Global, |
| 322 |
Input(crate::FunctionArgument), |
| 323 |
Output(crate::FunctionResult), |
| 324 |
} |
| 325 |
|
| 326 |
#[derive(Debug)] |
| 327 |
struct LookupVariable { |
| 328 |
inner: Variable, |
| 329 |
handle: Handle<crate::GlobalVariable>, |
| 330 |
type_id: spirv::Word, |
| 331 |
} |
| 332 |
|
| 333 |
/// Information about SPIR-V result ids, stored in `Frontend::lookup_expression`. |
| 334 |
#[derive(Clone, Debug)] |
| 335 |
struct LookupExpression { |
| 336 |
/// The `Expression` constructed for this result. |
| 337 |
/// |
| 338 |
/// Note that, while a SPIR-V result id can be used in any block dominated |
| 339 |
/// by its definition, a Naga `Expression` is only in scope for the rest of |
| 340 |
/// its subtree. `Frontend::get_expr_handle` takes care of spilling the result |
| 341 |
/// to a `LocalVariable` which can then be used anywhere. |
| 342 |
handle: Handle<crate::Expression>, |
| 343 |
|
| 344 |
/// The SPIR-V type of this result. |
| 345 |
type_id: spirv::Word, |
| 346 |
|
| 347 |
/// The label id of the block that defines this expression. |
| 348 |
/// |
| 349 |
/// This is zero for globals, constants, and function parameters, since they |
| 350 |
/// originate outside any function's block. |
| 351 |
block_id: spirv::Word, |
| 352 |
} |
| 353 |
|
| 354 |
#[derive(Debug)] |
| 355 |
struct LookupMember { |
| 356 |
type_id: spirv::Word, |
| 357 |
// This is true for either matrices, or arrays of matrices (yikes). |
| 358 |
row_major: bool, |
| 359 |
} |
| 360 |
|
| 361 |
#[derive(Clone, Debug)] |
| 362 |
enum LookupLoadOverride { |
| 363 |
/// For arrays of matrices, we track them but not loading yet. |
| 364 |
Pending, |
| 365 |
/// For matrices, vectors, and scalars, we pre-load the data. |
| 366 |
Loaded(Handle<crate::Expression>), |
| 367 |
} |
| 368 |
|
| 369 |
#[derive(PartialEq)] |
| 370 |
enum ExtendedClass { |
| 371 |
Global(crate::AddressSpace), |
| 372 |
Input, |
| 373 |
Output, |
| 374 |
} |
| 375 |
|
| 376 |
#[derive(Clone, Debug)] |
| 377 |
pub struct Options { |
| 378 |
/// The IR coordinate space matches all the APIs except SPIR-V, |
| 379 |
/// so by default we flip the Y coordinate of the `BuiltIn::Position`. |
| 380 |
/// This flag can be used to avoid this. |
| 381 |
pub adjust_coordinate_space: bool, |
| 382 |
/// Only allow shaders with the known set of capabilities. |
| 383 |
pub strict_capabilities: bool, |
| 384 |
pub block_ctx_dump_prefix: Option<PathBuf>, |
| 385 |
} |
| 386 |
|
| 387 |
impl Default for Options { |
| 388 |
fn default() -> Self { |
| 389 |
Options { |
| 390 |
adjust_coordinate_space: true, |
| 391 |
strict_capabilities: true, |
| 392 |
block_ctx_dump_prefix: None, |
| 393 |
} |
| 394 |
} |
| 395 |
} |
| 396 |
|
| 397 |
/// An index into the `BlockContext::bodies` table. |
| 398 |
type BodyIndex = usize; |
| 399 |
|
| 400 |
/// An intermediate representation of a Naga [`Statement`]. |
| 401 |
/// |
| 402 |
/// `Body` and `BodyFragment` values form a tree: the `BodyIndex` fields of the |
| 403 |
/// variants are indices of the child `Body` values in [`BlockContext::bodies`]. |
| 404 |
/// The `lower` function assembles the final `Statement` tree from this `Body` |
| 405 |
/// tree. See [`BlockContext`] for details. |
| 406 |
/// |
| 407 |
/// [`Statement`]: crate::Statement |
| 408 |
#[derive(Debug)] |
| 409 |
enum BodyFragment { |
| 410 |
BlockId(spirv::Word), |
| 411 |
If { |
| 412 |
condition: Handle<crate::Expression>, |
| 413 |
accept: BodyIndex, |
| 414 |
reject: BodyIndex, |
| 415 |
}, |
| 416 |
Loop { |
| 417 |
/// The body of the loop. Its [`Body::parent`] is the block containing |
| 418 |
/// this `Loop` fragment. |
| 419 |
body: BodyIndex, |
| 420 |
|
| 421 |
/// The loop's continuing block. This is a grandchild: its |
| 422 |
/// [`Body::parent`] is the loop body block, whose index is above. |
| 423 |
continuing: BodyIndex, |
| 424 |
|
| 425 |
/// If the SPIR-V loop's back-edge branch is conditional, this is the |
| 426 |
/// expression that must be `false` for the back-edge to be taken, with |
| 427 |
/// `true` being for the "loop merge" (which breaks out of the loop). |
| 428 |
break_if: Option<Handle<crate::Expression>>, |
| 429 |
}, |
| 430 |
Switch { |
| 431 |
selector: Handle<crate::Expression>, |
| 432 |
cases: Vec<(i32, BodyIndex)>, |
| 433 |
default: BodyIndex, |
| 434 |
}, |
| 435 |
Break, |
| 436 |
Continue, |
| 437 |
} |
| 438 |
|
| 439 |
/// An intermediate representation of a Naga [`Block`]. |
| 440 |
/// |
| 441 |
/// This will be assembled into a `Block` once we've added spills for phi nodes |
| 442 |
/// and out-of-scope expressions. See [`BlockContext`] for details. |
| 443 |
/// |
| 444 |
/// [`Block`]: crate::Block |
| 445 |
#[derive(Debug)] |
| 446 |
struct Body { |
| 447 |
/// The index of the direct parent of this body |
| 448 |
parent: usize, |
| 449 |
data: Vec<BodyFragment>, |
| 450 |
} |
| 451 |
|
| 452 |
impl Body { |
| 453 |
/// Creates a new empty `Body` with the specified `parent` |
| 454 |
pub const fn with_parent(parent: usize) -> Self { |
| 455 |
Body { |
| 456 |
parent, |
| 457 |
data: Vec::new(), |
| 458 |
} |
| 459 |
} |
| 460 |
} |
| 461 |
|
| 462 |
#[derive(Debug)] |
| 463 |
struct PhiExpression { |
| 464 |
/// The local variable used for the phi node |
| 465 |
local: Handle<crate::LocalVariable>, |
| 466 |
/// List of (expression, block) |
| 467 |
expressions: Vec<(spirv::Word, spirv::Word)>, |
| 468 |
} |
| 469 |
|
| 470 |
#[derive(Copy, Clone, Debug, PartialEq, Eq)] |
| 471 |
enum MergeBlockInformation { |
| 472 |
LoopMerge, |
| 473 |
LoopContinue, |
| 474 |
SelectionMerge, |
| 475 |
SwitchMerge, |
| 476 |
} |
| 477 |
|
| 478 |
/// Fragments of Naga IR, to be assembled into `Statements` once data flow is |
| 479 |
/// resolved. |
| 480 |
/// |
| 481 |
/// We can't build a Naga `Statement` tree directly from SPIR-V blocks for three |
| 482 |
/// main reasons: |
| 483 |
/// |
| 484 |
/// - We parse a function's SPIR-V blocks in the order they appear in the file. |
| 485 |
/// Within a function, SPIR-V requires that a block must precede any blocks it |
| 486 |
/// structurally dominates, but doesn't say much else about the order in which |
| 487 |
/// they must appear. So while we know we'll see control flow header blocks |
| 488 |
/// before their child constructs and merge blocks, those children and the |
| 489 |
/// merge blocks may appear in any order - perhaps even intermingled with |
| 490 |
/// children of other constructs. |
| 491 |
/// |
| 492 |
/// - A SPIR-V expression can be used in any SPIR-V block dominated by its |
| 493 |
/// definition, whereas Naga expressions are scoped to the rest of their |
| 494 |
/// subtree. This means that discovering an expression use later in the |
| 495 |
/// function retroactively requires us to have spilled that expression into a |
| 496 |
/// local variable back before we left its scope. (The docs for |
| 497 |
/// [`Frontend::get_expr_handle`] explain this in more detail.) |
| 498 |
/// |
| 499 |
/// - We translate SPIR-V OpPhi expressions as Naga local variables in which we |
| 500 |
/// store the appropriate value before jumping to the OpPhi's block. |
| 501 |
/// |
| 502 |
/// All these cases require us to go back and amend previously generated Naga IR |
| 503 |
/// based on things we discover later. But modifying old blocks in arbitrary |
| 504 |
/// spots in a `Statement` tree is awkward. |
| 505 |
/// |
| 506 |
/// Instead, as we iterate through the function's body, we accumulate |
| 507 |
/// control-flow-free fragments of Naga IR in the [`blocks`] table, while |
| 508 |
/// building a skeleton of the Naga `Statement` tree in [`bodies`]. We note any |
| 509 |
/// spills and temporaries we must introduce in [`phis`]. |
| 510 |
/// |
| 511 |
/// Finally, once we've processed the entire function, we add temporaries and |
| 512 |
/// spills to the fragmentary `Blocks` as directed by `phis`, and assemble them |
| 513 |
/// into the final Naga `Statement` tree as directed by `bodies`. |
| 514 |
/// |
| 515 |
/// [`blocks`]: BlockContext::blocks |
| 516 |
/// [`bodies`]: BlockContext::bodies |
| 517 |
/// [`phis`]: BlockContext::phis |
| 518 |
/// [`lower`]: function::lower |
| 519 |
#[derive(Debug)] |
| 520 |
struct BlockContext<'function> { |
| 521 |
/// Phi nodes encountered when parsing the function, used to generate spills |
| 522 |
/// to local variables. |
| 523 |
phis: Vec<PhiExpression>, |
| 524 |
|
| 525 |
/// Fragments of control-flow-free Naga IR. |
| 526 |
/// |
| 527 |
/// These will be stitched together into a proper [`Statement`] tree according |
| 528 |
/// to `bodies`, once parsing is complete. |
| 529 |
/// |
| 530 |
/// [`Statement`]: crate::Statement |
| 531 |
blocks: FastHashMap<spirv::Word, crate::Block>, |
| 532 |
|
| 533 |
/// Map from each SPIR-V block's label id to the index of the [`Body`] in |
| 534 |
/// [`bodies`] the block should append its contents to. |
| 535 |
/// |
| 536 |
/// Since each statement in a Naga [`Block`] dominates the next, we are sure |
| 537 |
/// to encounter their SPIR-V blocks in order. Thus, by having this table |
| 538 |
/// map a SPIR-V structured control flow construct's merge block to the same |
| 539 |
/// body index as its header block, when we encounter the merge block, we |
| 540 |
/// will simply pick up building the [`Body`] where the header left off. |
| 541 |
/// |
| 542 |
/// A function's first block is special: it is the only block we encounter |
| 543 |
/// without having seen its label mentioned in advance. (It's simply the |
| 544 |
/// first `OpLabel` after the `OpFunction`.) We thus assume that any block |
| 545 |
/// missing an entry here must be the first block, which always has body |
| 546 |
/// index zero. |
| 547 |
/// |
| 548 |
/// [`bodies`]: BlockContext::bodies |
| 549 |
/// [`Block`]: crate::Block |
| 550 |
body_for_label: FastHashMap<spirv::Word, BodyIndex>, |
| 551 |
|
| 552 |
/// SPIR-V metadata about merge/continue blocks. |
| 553 |
mergers: FastHashMap<spirv::Word, MergeBlockInformation>, |
| 554 |
|
| 555 |
/// A table of `Body` values, each representing a block in the final IR. |
| 556 |
/// |
| 557 |
/// The first element is always the function's top-level block. |
| 558 |
bodies: Vec<Body>, |
| 559 |
|
| 560 |
/// The module we're building. |
| 561 |
module: &'function mut crate::Module, |
| 562 |
|
| 563 |
/// Id of the function currently being processed |
| 564 |
function_id: spirv::Word, |
| 565 |
/// Expression arena of the function currently being processed |
| 566 |
expressions: &'function mut Arena<crate::Expression>, |
| 567 |
/// Local variables arena of the function currently being processed |
| 568 |
local_arena: &'function mut Arena<crate::LocalVariable>, |
| 569 |
/// Arguments of the function currently being processed |
| 570 |
arguments: &'function [crate::FunctionArgument], |
| 571 |
/// Metadata about the usage of function parameters as sampling objects |
| 572 |
parameter_sampling: &'function mut [image::SamplingFlags], |
| 573 |
} |
| 574 |
|
| 575 |
enum SignAnchor { |
| 576 |
Result, |
| 577 |
Operand, |
| 578 |
} |
| 579 |
|
| 580 |
pub struct Frontend<I> { |
| 581 |
data: I, |
| 582 |
data_offset: usize, |
| 583 |
state: ModuleState, |
| 584 |
layouter: Layouter, |
| 585 |
temp_bytes: Vec<u8>, |
| 586 |
ext_glsl_id: Option<spirv::Word>, |
| 587 |
future_decor: FastHashMap<spirv::Word, Decoration>, |
| 588 |
future_member_decor: FastHashMap<(spirv::Word, MemberIndex), Decoration>, |
| 589 |
lookup_member: FastHashMap<(Handle<crate::Type>, MemberIndex), LookupMember>, |
| 590 |
handle_sampling: FastHashMap<Handle<crate::GlobalVariable>, image::SamplingFlags>, |
| 591 |
|
| 592 |
/// A record of what is accessed by [`Atomic`] statements we've |
| 593 |
/// generated, so we can upgrade the types of their operands. |
| 594 |
/// |
| 595 |
/// [`Atomic`]: crate::Statement::Atomic |
| 596 |
upgrade_atomics: Upgrades, |
| 597 |
|
| 598 |
lookup_type: FastHashMap<spirv::Word, LookupType>, |
| 599 |
lookup_void_type: Option<spirv::Word>, |
| 600 |
lookup_storage_buffer_types: FastHashMap<Handle<crate::Type>, crate::StorageAccess>, |
| 601 |
lookup_constant: FastHashMap<spirv::Word, LookupConstant>, |
| 602 |
lookup_variable: FastHashMap<spirv::Word, LookupVariable>, |
| 603 |
lookup_expression: FastHashMap<spirv::Word, LookupExpression>, |
| 604 |
// Load overrides are used to work around row-major matrices |
| 605 |
lookup_load_override: FastHashMap<spirv::Word, LookupLoadOverride>, |
| 606 |
lookup_sampled_image: FastHashMap<spirv::Word, image::LookupSampledImage>, |
| 607 |
lookup_function_type: FastHashMap<spirv::Word, LookupFunctionType>, |
| 608 |
lookup_function: FastHashMap<spirv::Word, LookupFunction>, |
| 609 |
lookup_entry_point: FastHashMap<spirv::Word, EntryPoint>, |
| 610 |
// When parsing functions, each entry point function gets an entry here so that additional |
| 611 |
// processing for them can be performed after all function parsing. |
| 612 |
deferred_entry_points: Vec<(EntryPoint, spirv::Word)>, |
| 613 |
//Note: each `OpFunctionCall` gets a single entry here, indexed by the |
| 614 |
// dummy `Handle<crate::Function>` of the call site. |
| 615 |
deferred_function_calls: Vec<spirv::Word>, |
| 616 |
dummy_functions: Arena<crate::Function>, |
| 617 |
// Graph of all function calls through the module. |
| 618 |
// It's used to sort the functions (as nodes) topologically, |
| 619 |
// so that in the IR any called function is already known. |
| 620 |
function_call_graph: GraphMap< |
| 621 |
spirv::Word, |
| 622 |
(), |
| 623 |
petgraph::Directed, |
| 624 |
core::hash::BuildHasherDefault<rustc_hash::FxHasher>, |
| 625 |
>, |
| 626 |
options: Options, |
| 627 |
|
| 628 |
/// Maps for a switch from a case target to the respective body and associated literals that |
| 629 |
/// use that target block id. |
| 630 |
/// |
| 631 |
/// Used to preserve allocations between instruction parsing. |
| 632 |
switch_cases: FastIndexMap<spirv::Word, (BodyIndex, Vec<i32>)>, |
| 633 |
|
| 634 |
/// Tracks access to gl_PerVertex's builtins, it is used to cull unused builtins since initializing those can |
| 635 |
/// affect performance and the mere presence of some of these builtins might cause backends to error since they |
| 636 |
/// might be unsupported. |
| 637 |
/// |
| 638 |
/// The problematic builtins are: PointSize, ClipDistance and CullDistance. |
| 639 |
/// |
| 640 |
/// glslang declares those by default even though they are never written to |
| 641 |
/// (see <https://github.com/KhronosGroup/glslang/issues/1868>) |
| 642 |
gl_per_vertex_builtin_access: FastHashSet<crate::BuiltIn>, |
| 643 |
} |
| 644 |
|
| 645 |
impl<I: Iterator<Item = u32>> Frontend<I> { |
| 646 |
pub fn new(data: I, options: &Options) -> Self { |
| 647 |
Frontend { |
| 648 |
data, |
| 649 |
data_offset: 0, |
| 650 |
state: ModuleState::Empty, |
| 651 |
layouter: Layouter::default(), |
| 652 |
temp_bytes: Vec::new(), |
| 653 |
ext_glsl_id: None, |
| 654 |
future_decor: FastHashMap::default(), |
| 655 |
future_member_decor: FastHashMap::default(), |
| 656 |
handle_sampling: FastHashMap::default(), |
| 657 |
lookup_member: FastHashMap::default(), |
| 658 |
upgrade_atomics: Default::default(), |
| 659 |
lookup_type: FastHashMap::default(), |
| 660 |
lookup_void_type: None, |
| 661 |
lookup_storage_buffer_types: FastHashMap::default(), |
| 662 |
lookup_constant: FastHashMap::default(), |
| 663 |
lookup_variable: FastHashMap::default(), |
| 664 |
lookup_expression: FastHashMap::default(), |
| 665 |
lookup_load_override: FastHashMap::default(), |
| 666 |
lookup_sampled_image: FastHashMap::default(), |
| 667 |
lookup_function_type: FastHashMap::default(), |
| 668 |
lookup_function: FastHashMap::default(), |
| 669 |
lookup_entry_point: FastHashMap::default(), |
| 670 |
deferred_entry_points: Vec::default(), |
| 671 |
deferred_function_calls: Vec::default(), |
| 672 |
dummy_functions: Arena::new(), |
| 673 |
function_call_graph: GraphMap::new(), |
| 674 |
options: options.clone(), |
| 675 |
switch_cases: FastIndexMap::default(), |
| 676 |
gl_per_vertex_builtin_access: FastHashSet::default(), |
| 677 |
} |
| 678 |
} |
| 679 |
|
| 680 |
fn span_from(&self, from: usize) -> crate::Span { |
| 681 |
crate::Span::from(from..self.data_offset) |
| 682 |
} |
| 683 |
|
| 684 |
fn span_from_with_op(&self, from: usize) -> crate::Span { |
| 685 |
crate::Span::from((from - 4)..self.data_offset) |
| 686 |
} |
| 687 |
|
| 688 |
fn next(&mut self) -> Result<u32, Error> { |
| 689 |
if let Some(res) = self.data.next() { |
| 690 |
self.data_offset += 4; |
| 691 |
Ok(res) |
| 692 |
} else { |
| 693 |
Err(Error::IncompleteData) |
| 694 |
} |
| 695 |
} |
| 696 |
|
| 697 |
fn next_inst(&mut self) -> Result<Instruction, Error> { |
| 698 |
let word = self.next()?; |
| 699 |
let (wc, opcode) = ((word >> 16) as u16, (word & 0xffff) as u16); |
| 700 |
if wc == 0 { |
| 701 |
return Err(Error::InvalidWordCount); |
| 702 |
} |
| 703 |
let op = spirv::Op::from_u32(opcode as u32).ok_or(Error::UnknownInstruction(opcode))?; |
| 704 |
|
| 705 |
Ok(Instruction { op, wc }) |
| 706 |
} |
| 707 |
|
| 708 |
fn next_string(&mut self, mut count: u16) -> Result<(String, u16), Error> { |
| 709 |
self.temp_bytes.clear(); |
| 710 |
loop { |
| 711 |
if count == 0 { |
| 712 |
return Err(Error::BadString); |
| 713 |
} |
| 714 |
count -= 1; |
| 715 |
let chars = self.next()?.to_le_bytes(); |
| 716 |
let pos = chars.iter().position(|&c| c == 0).unwrap_or(4); |
| 717 |
self.temp_bytes.extend_from_slice(&chars[..pos]); |
| 718 |
if pos < 4 { |
| 719 |
break; |
| 720 |
} |
| 721 |
} |
| 722 |
core::str::from_utf8(&self.temp_bytes) |
| 723 |
.map(|s| (s.to_owned(), count)) |
| 724 |
.map_err(|_| Error::BadString) |
| 725 |
} |
| 726 |
|
| 727 |
fn next_decoration( |
| 728 |
&mut self, |
| 729 |
inst: Instruction, |
| 730 |
base_words: u16, |
| 731 |
dec: &mut Decoration, |
| 732 |
) -> Result<(), Error> { |
| 733 |
let raw = self.next()?; |
| 734 |
let dec_typed = spirv::Decoration::from_u32(raw).ok_or(Error::InvalidDecoration(raw))?; |
| 735 |
log::trace!("\t\t{}: {:?}", dec.debug_name(), dec_typed); |
| 736 |
match dec_typed { |
| 737 |
spirv::Decoration::BuiltIn => { |
| 738 |
inst.expect(base_words + 2)?; |
| 739 |
dec.built_in = Some(self.next()?); |
| 740 |
} |
| 741 |
spirv::Decoration::Location => { |
| 742 |
inst.expect(base_words + 2)?; |
| 743 |
dec.location = Some(self.next()?); |
| 744 |
} |
| 745 |
spirv::Decoration::DescriptorSet => { |
| 746 |
inst.expect(base_words + 2)?; |
| 747 |
dec.desc_set = Some(self.next()?); |
| 748 |
} |
| 749 |
spirv::Decoration::Binding => { |
| 750 |
inst.expect(base_words + 2)?; |
| 751 |
dec.desc_index = Some(self.next()?); |
| 752 |
} |
| 753 |
spirv::Decoration::BufferBlock => { |
| 754 |
dec.storage_buffer = true; |
| 755 |
} |
| 756 |
spirv::Decoration::Offset => { |
| 757 |
inst.expect(base_words + 2)?; |
| 758 |
dec.offset = Some(self.next()?); |
| 759 |
} |
| 760 |
spirv::Decoration::ArrayStride => { |
| 761 |
inst.expect(base_words + 2)?; |
| 762 |
dec.array_stride = NonZeroU32::new(self.next()?); |
| 763 |
} |
| 764 |
spirv::Decoration::MatrixStride => { |
| 765 |
inst.expect(base_words + 2)?; |
| 766 |
dec.matrix_stride = NonZeroU32::new(self.next()?); |
| 767 |
} |
| 768 |
spirv::Decoration::Invariant => { |
| 769 |
dec.invariant = true; |
| 770 |
} |
| 771 |
spirv::Decoration::NoPerspective => { |
| 772 |
dec.interpolation = Some(crate::Interpolation::Linear); |
| 773 |
} |
| 774 |
spirv::Decoration::Flat => { |
| 775 |
dec.interpolation = Some(crate::Interpolation::Flat); |
| 776 |
} |
| 777 |
spirv::Decoration::Centroid => { |
| 778 |
dec.sampling = Some(crate::Sampling::Centroid); |
| 779 |
} |
| 780 |
spirv::Decoration::Sample => { |
| 781 |
dec.sampling = Some(crate::Sampling::Sample); |
| 782 |
} |
| 783 |
spirv::Decoration::NonReadable => { |
| 784 |
dec.flags |= DecorationFlags::NON_READABLE; |
| 785 |
} |
| 786 |
spirv::Decoration::NonWritable => { |
| 787 |
dec.flags |= DecorationFlags::NON_WRITABLE; |
| 788 |
} |
| 789 |
spirv::Decoration::ColMajor => { |
| 790 |
dec.matrix_major = Some(Majority::Column); |
| 791 |
} |
| 792 |
spirv::Decoration::RowMajor => { |
| 793 |
dec.matrix_major = Some(Majority::Row); |
| 794 |
} |
| 795 |
spirv::Decoration::SpecId => { |
| 796 |
dec.specialization_constant_id = Some(self.next()?); |
| 797 |
} |
| 798 |
other => { |
| 799 |
log::warn!("Unknown decoration {:?}", other); |
| 800 |
for _ in base_words + 1..inst.wc { |
| 801 |
let _var = self.next()?; |
| 802 |
} |
| 803 |
} |
| 804 |
} |
| 805 |
Ok(()) |
| 806 |
} |
| 807 |
|
| 808 |
/// Return the Naga [`Expression`] to use in `body_idx` to refer to the SPIR-V result `id`. |
| 809 |
/// |
| 810 |
/// Ideally, we would just have a map from each SPIR-V instruction id to the |
| 811 |
/// [`Handle`] for the Naga [`Expression`] we generated for it. |
| 812 |
/// Unfortunately, SPIR-V and Naga IR are different enough that such a |
| 813 |
/// straightforward relationship isn't possible. |
| 814 |
/// |
| 815 |
/// In SPIR-V, an instruction's result id can be used by any instruction |
| 816 |
/// dominated by that instruction. In Naga, an [`Expression`] is only in |
| 817 |
/// scope for the remainder of its [`Block`]. In pseudocode: |
| 818 |
/// |
| 819 |
/// ```ignore |
| 820 |
/// loop { |
| 821 |
/// a = f(); |
| 822 |
/// g(a); |
| 823 |
/// break; |
| 824 |
/// } |
| 825 |
/// h(a); |
| 826 |
/// ``` |
| 827 |
/// |
| 828 |
/// Suppose the calls to `f`, `g`, and `h` are SPIR-V instructions. In |
| 829 |
/// SPIR-V, both the `g` and `h` instructions are allowed to refer to `a`, |
| 830 |
/// because the loop body, including `f`, dominates both of them. |
| 831 |
/// |
| 832 |
/// But if `a` is a Naga [`Expression`], its scope ends at the end of the |
| 833 |
/// block it's evaluated in: the loop body. Thus, while the [`Expression`] |
| 834 |
/// we generate for `g` can refer to `a`, the one we generate for `h` |
| 835 |
/// cannot. |
| 836 |
/// |
| 837 |
/// Instead, the SPIR-V front end must generate Naga IR like this: |
| 838 |
/// |
| 839 |
/// ```ignore |
| 840 |
/// var temp; // INTRODUCED |
| 841 |
/// loop { |
| 842 |
/// a = f(); |
| 843 |
/// g(a); |
| 844 |
/// temp = a; // INTRODUCED |
| 845 |
/// } |
| 846 |
/// h(temp); // ADJUSTED |
| 847 |
/// ``` |
| 848 |
/// |
| 849 |
/// In other words, where `a` is in scope, [`Expression`]s can refer to it |
| 850 |
/// directly; but once it is out of scope, we need to spill it to a |
| 851 |
/// temporary and refer to that instead. |
| 852 |
/// |
| 853 |
/// Given a SPIR-V expression `id` and the index `body_idx` of the [body] |
| 854 |
/// that wants to refer to it: |
| 855 |
/// |
| 856 |
/// - If the Naga [`Expression`] we generated for `id` is in scope in |
| 857 |
/// `body_idx`, then we simply return its `Handle<Expression>`. |
| 858 |
/// |
| 859 |
/// - Otherwise, introduce a new [`LocalVariable`], and add an entry to |
| 860 |
/// [`BlockContext::phis`] to arrange for `id`'s value to be spilled to |
| 861 |
/// it. Then emit a fresh [`Load`] of that temporary variable for use in |
| 862 |
/// `body_idx`'s block, and return its `Handle`. |
| 863 |
/// |
| 864 |
/// The SPIR-V domination rule ensures that the introduced [`LocalVariable`] |
| 865 |
/// will always have been initialized before it is used. |
| 866 |
/// |
| 867 |
/// `lookup` must be the [`LookupExpression`] for `id`. |
| 868 |
/// |
| 869 |
/// `body_idx` argument must be the index of the [`Body`] that hopes to use |
| 870 |
/// `id`'s [`Expression`]. |
| 871 |
/// |
| 872 |
/// [`Expression`]: crate::Expression |
| 873 |
/// [`Handle`]: crate::Handle |
| 874 |
/// [`Block`]: crate::Block |
| 875 |
/// [body]: BlockContext::bodies |
| 876 |
/// [`LocalVariable`]: crate::LocalVariable |
| 877 |
/// [`Load`]: crate::Expression::Load |
| 878 |
fn get_expr_handle( |
| 879 |
&self, |
| 880 |
id: spirv::Word, |
| 881 |
lookup: &LookupExpression, |
| 882 |
ctx: &mut BlockContext, |
| 883 |
emitter: &mut crate::proc::Emitter, |
| 884 |
block: &mut crate::Block, |
| 885 |
body_idx: BodyIndex, |
| 886 |
) -> Handle<crate::Expression> { |
| 887 |
// What `Body` was `id` defined in? |
| 888 |
let expr_body_idx = ctx |
| 889 |
.body_for_label |
| 890 |
.get(&lookup.block_id) |
| 891 |
.copied() |
| 892 |
.unwrap_or(0); |
| 893 |
|
| 894 |
// Don't need to do a load/store if the expression is in the main body |
| 895 |
// or if the expression is in the same body as where the query was |
| 896 |
// requested. The body_idx might actually not be the final one if a loop |
| 897 |
// or conditional occurs but in those cases we know that the new body |
| 898 |
// will be a subscope of the body that was passed so we can still reuse |
| 899 |
// the handle and not issue a load/store. |
| 900 |
if is_parent(body_idx, expr_body_idx, ctx) { |
| 901 |
lookup.handle |
| 902 |
} else { |
| 903 |
// Add a temporary variable of the same type which will be used to |
| 904 |
// store the original expression and used in the current block |
| 905 |
let ty = self.lookup_type[&lookup.type_id].handle; |
| 906 |
let local = ctx.local_arena.append( |
| 907 |
crate::LocalVariable { |
| 908 |
name: None, |
| 909 |
ty, |
| 910 |
init: None, |
| 911 |
}, |
| 912 |
crate::Span::default(), |
| 913 |
); |
| 914 |
|
| 915 |
block.extend(emitter.finish(ctx.expressions)); |
| 916 |
let pointer = ctx.expressions.append( |
| 917 |
crate::Expression::LocalVariable(local), |
| 918 |
crate::Span::default(), |
| 919 |
); |
| 920 |
emitter.start(ctx.expressions); |
| 921 |
let expr = ctx |
| 922 |
.expressions |
| 923 |
.append(crate::Expression::Load { pointer }, crate::Span::default()); |
| 924 |
|
| 925 |
// Add a slightly odd entry to the phi table, so that while `id`'s |
| 926 |
// `Expression` is still in scope, the usual phi processing will |
| 927 |
// spill its value to `local`, where we can find it later. |
| 928 |
// |
| 929 |
// This pretends that the block in which `id` is defined is the |
| 930 |
// predecessor of some other block with a phi in it that cites id as |
| 931 |
// one of its sources, and uses `local` as its variable. There is no |
| 932 |
// such phi, but nobody needs to know that. |
| 933 |
ctx.phis.push(PhiExpression { |
| 934 |
local, |
| 935 |
expressions: vec![(id, lookup.block_id)], |
| 936 |
}); |
| 937 |
|
| 938 |
expr |
| 939 |
} |
| 940 |
} |
| 941 |
|
| 942 |
fn parse_expr_unary_op( |
| 943 |
&mut self, |
| 944 |
ctx: &mut BlockContext, |
| 945 |
emitter: &mut crate::proc::Emitter, |
| 946 |
block: &mut crate::Block, |
| 947 |
block_id: spirv::Word, |
| 948 |
body_idx: usize, |
| 949 |
op: crate::UnaryOperator, |
| 950 |
) -> Result<(), Error> { |
| 951 |
let start = self.data_offset; |
| 952 |
let result_type_id = self.next()?; |
| 953 |
let result_id = self.next()?; |
| 954 |
let p_id = self.next()?; |
| 955 |
|
| 956 |
let p_lexp = self.lookup_expression.lookup(p_id)?; |
| 957 |
let handle = self.get_expr_handle(p_id, p_lexp, ctx, emitter, block, body_idx); |
| 958 |
|
| 959 |
let expr = crate::Expression::Unary { op, expr: handle }; |
| 960 |
self.lookup_expression.insert( |
| 961 |
result_id, |
| 962 |
LookupExpression { |
| 963 |
handle: ctx.expressions.append(expr, self.span_from_with_op(start)), |
| 964 |
type_id: result_type_id, |
| 965 |
block_id, |
| 966 |
}, |
| 967 |
); |
| 968 |
Ok(()) |
| 969 |
} |
| 970 |
|
| 971 |
fn parse_expr_binary_op( |
| 972 |
&mut self, |
| 973 |
ctx: &mut BlockContext, |
| 974 |
emitter: &mut crate::proc::Emitter, |
| 975 |
block: &mut crate::Block, |
| 976 |
block_id: spirv::Word, |
| 977 |
body_idx: usize, |
| 978 |
op: crate::BinaryOperator, |
| 979 |
) -> Result<(), Error> { |
| 980 |
let start = self.data_offset; |
| 981 |
let result_type_id = self.next()?; |
| 982 |
let result_id = self.next()?; |
| 983 |
let p1_id = self.next()?; |
| 984 |
let p2_id = self.next()?; |
| 985 |
|
| 986 |
let p1_lexp = self.lookup_expression.lookup(p1_id)?; |
| 987 |
let left = self.get_expr_handle(p1_id, p1_lexp, ctx, emitter, block, body_idx); |
| 988 |
let p2_lexp = self.lookup_expression.lookup(p2_id)?; |
| 989 |
let right = self.get_expr_handle(p2_id, p2_lexp, ctx, emitter, block, body_idx); |
| 990 |
|
| 991 |
let expr = crate::Expression::Binary { op, left, right }; |
| 992 |
self.lookup_expression.insert( |
| 993 |
result_id, |
| 994 |
LookupExpression { |
| 995 |
handle: ctx.expressions.append(expr, self.span_from_with_op(start)), |
| 996 |
type_id: result_type_id, |
| 997 |
block_id, |
| 998 |
}, |
| 999 |
); |
| 1000 |
Ok(()) |
| 1001 |
} |
| 1002 |
|
| 1003 |
/// A more complicated version of the unary op, |
| 1004 |
/// where we force the operand to have the same type as the result. |
| 1005 |
fn parse_expr_unary_op_sign_adjusted( |
| 1006 |
&mut self, |
| 1007 |
ctx: &mut BlockContext, |
| 1008 |
emitter: &mut crate::proc::Emitter, |
| 1009 |
block: &mut crate::Block, |
| 1010 |
block_id: spirv::Word, |
| 1011 |
body_idx: usize, |
| 1012 |
op: crate::UnaryOperator, |
| 1013 |
) -> Result<(), Error> { |
| 1014 |
let start = self.data_offset; |
| 1015 |
let result_type_id = self.next()?; |
| 1016 |
let result_id = self.next()?; |
| 1017 |
let p1_id = self.next()?; |
| 1018 |
let span = self.span_from_with_op(start); |
| 1019 |
|
| 1020 |
let p1_lexp = self.lookup_expression.lookup(p1_id)?; |
| 1021 |
let left = self.get_expr_handle(p1_id, p1_lexp, ctx, emitter, block, body_idx); |
| 1022 |
|
| 1023 |
let result_lookup_ty = self.lookup_type.lookup(result_type_id)?; |
| 1024 |
let kind = ctx.module.types[result_lookup_ty.handle] |
| 1025 |
.inner |
| 1026 |
.scalar_kind() |
| 1027 |
.unwrap(); |
| 1028 |
|
| 1029 |
let expr = crate::Expression::Unary { |
| 1030 |
op, |
| 1031 |
expr: if p1_lexp.type_id == result_type_id { |
| 1032 |
left |
| 1033 |
} else { |
| 1034 |
ctx.expressions.append( |
| 1035 |
crate::Expression::As { |
| 1036 |
expr: left, |
| 1037 |
kind, |
| 1038 |
convert: None, |
| 1039 |
}, |
| 1040 |
span, |
| 1041 |
) |
| 1042 |
}, |
| 1043 |
}; |
| 1044 |
|
| 1045 |
self.lookup_expression.insert( |
| 1046 |
result_id, |
| 1047 |
LookupExpression { |
| 1048 |
handle: ctx.expressions.append(expr, span), |
| 1049 |
type_id: result_type_id, |
| 1050 |
block_id, |
| 1051 |
}, |
| 1052 |
); |
| 1053 |
Ok(()) |
| 1054 |
} |
| 1055 |
|
| 1056 |
/// A more complicated version of the binary op, |
| 1057 |
/// where we force the operand to have the same type as the result. |
| 1058 |
/// This is mostly needed for "i++" and "i--" coming from GLSL. |
| 1059 |
#[allow(clippy::too_many_arguments)] |
| 1060 |
fn parse_expr_binary_op_sign_adjusted( |
| 1061 |
&mut self, |
| 1062 |
ctx: &mut BlockContext, |
| 1063 |
emitter: &mut crate::proc::Emitter, |
| 1064 |
block: &mut crate::Block, |
| 1065 |
block_id: spirv::Word, |
| 1066 |
body_idx: usize, |
| 1067 |
op: crate::BinaryOperator, |
| 1068 |
// For arithmetic operations, we need the sign of operands to match the result. |
| 1069 |
// For boolean operations, however, the operands need to match the signs, but |
| 1070 |
// result is always different - a boolean. |
| 1071 |
anchor: SignAnchor, |
| 1072 |
) -> Result<(), Error> { |
| 1073 |
let start = self.data_offset; |
| 1074 |
let result_type_id = self.next()?; |
| 1075 |
let result_id = self.next()?; |
| 1076 |
let p1_id = self.next()?; |
| 1077 |
let p2_id = self.next()?; |
| 1078 |
let span = self.span_from_with_op(start); |
| 1079 |
|
| 1080 |
let p1_lexp = self.lookup_expression.lookup(p1_id)?; |
| 1081 |
let left = self.get_expr_handle(p1_id, p1_lexp, ctx, emitter, block, body_idx); |
| 1082 |
let p2_lexp = self.lookup_expression.lookup(p2_id)?; |
| 1083 |
let right = self.get_expr_handle(p2_id, p2_lexp, ctx, emitter, block, body_idx); |
| 1084 |
|
| 1085 |
let expected_type_id = match anchor { |
| 1086 |
SignAnchor::Result => result_type_id, |
| 1087 |
SignAnchor::Operand => p1_lexp.type_id, |
| 1088 |
}; |
| 1089 |
let expected_lookup_ty = self.lookup_type.lookup(expected_type_id)?; |
| 1090 |
let kind = ctx.module.types[expected_lookup_ty.handle] |
| 1091 |
.inner |
| 1092 |
.scalar_kind() |
| 1093 |
.unwrap(); |
| 1094 |
|
| 1095 |
let expr = crate::Expression::Binary { |
| 1096 |
op, |
| 1097 |
left: if p1_lexp.type_id == expected_type_id { |
| 1098 |
left |
| 1099 |
} else { |
| 1100 |
ctx.expressions.append( |
| 1101 |
crate::Expression::As { |
| 1102 |
expr: left, |
| 1103 |
kind, |
| 1104 |
convert: None, |
| 1105 |
}, |
| 1106 |
span, |
| 1107 |
) |
| 1108 |
}, |
| 1109 |
right: if p2_lexp.type_id == expected_type_id { |
| 1110 |
right |
| 1111 |
} else { |
| 1112 |
ctx.expressions.append( |
| 1113 |
crate::Expression::As { |
| 1114 |
expr: right, |
| 1115 |
kind, |
| 1116 |
convert: None, |
| 1117 |
}, |
| 1118 |
span, |
| 1119 |
) |
| 1120 |
}, |
| 1121 |
}; |
| 1122 |
|
| 1123 |
self.lookup_expression.insert( |
| 1124 |
result_id, |
| 1125 |
LookupExpression { |
| 1126 |
handle: ctx.expressions.append(expr, span), |
| 1127 |
type_id: result_type_id, |
| 1128 |
block_id, |
| 1129 |
}, |
| 1130 |
); |
| 1131 |
Ok(()) |
| 1132 |
} |
| 1133 |
|
| 1134 |
/// A version of the binary op where one or both of the arguments might need to be casted to a |
| 1135 |
/// specific integer kind (unsigned or signed), used for operations like OpINotEqual or |
| 1136 |
/// OpUGreaterThan. |
| 1137 |
#[allow(clippy::too_many_arguments)] |
| 1138 |
fn parse_expr_int_comparison( |
| 1139 |
&mut self, |
| 1140 |
ctx: &mut BlockContext, |
| 1141 |
emitter: &mut crate::proc::Emitter, |
| 1142 |
block: &mut crate::Block, |
| 1143 |
block_id: spirv::Word, |
| 1144 |
body_idx: usize, |
| 1145 |
op: crate::BinaryOperator, |
| 1146 |
kind: crate::ScalarKind, |
| 1147 |
) -> Result<(), Error> { |
| 1148 |
let start = self.data_offset; |
| 1149 |
let result_type_id = self.next()?; |
| 1150 |
let result_id = self.next()?; |
| 1151 |
let p1_id = self.next()?; |
| 1152 |
let p2_id = self.next()?; |
| 1153 |
let span = self.span_from_with_op(start); |
| 1154 |
|
| 1155 |
let p1_lexp = self.lookup_expression.lookup(p1_id)?; |
| 1156 |
let left = self.get_expr_handle(p1_id, p1_lexp, ctx, emitter, block, body_idx); |
| 1157 |
let p1_lookup_ty = self.lookup_type.lookup(p1_lexp.type_id)?; |
| 1158 |
let p1_kind = ctx.module.types[p1_lookup_ty.handle] |
| 1159 |
.inner |
| 1160 |
.scalar_kind() |
| 1161 |
.unwrap(); |
| 1162 |
let p2_lexp = self.lookup_expression.lookup(p2_id)?; |
| 1163 |
let right = self.get_expr_handle(p2_id, p2_lexp, ctx, emitter, block, body_idx); |
| 1164 |
let p2_lookup_ty = self.lookup_type.lookup(p2_lexp.type_id)?; |
| 1165 |
let p2_kind = ctx.module.types[p2_lookup_ty.handle] |
| 1166 |
.inner |
| 1167 |
.scalar_kind() |
| 1168 |
.unwrap(); |
| 1169 |
|
| 1170 |
let expr = crate::Expression::Binary { |
| 1171 |
op, |
| 1172 |
left: if p1_kind == kind { |
| 1173 |
left |
| 1174 |
} else { |
| 1175 |
ctx.expressions.append( |
| 1176 |
crate::Expression::As { |
| 1177 |
expr: left, |
| 1178 |
kind, |
| 1179 |
convert: None, |
| 1180 |
}, |
| 1181 |
span, |
| 1182 |
) |
| 1183 |
}, |
| 1184 |
right: if p2_kind == kind { |
| 1185 |
right |
| 1186 |
} else { |
| 1187 |
ctx.expressions.append( |
| 1188 |
crate::Expression::As { |
| 1189 |
expr: right, |
| 1190 |
kind, |
| 1191 |
convert: None, |
| 1192 |
}, |
| 1193 |
span, |
| 1194 |
) |
| 1195 |
}, |
| 1196 |
}; |
| 1197 |
|
| 1198 |
self.lookup_expression.insert( |
| 1199 |
result_id, |
| 1200 |
LookupExpression { |
| 1201 |
handle: ctx.expressions.append(expr, span), |
| 1202 |
type_id: result_type_id, |
| 1203 |
block_id, |
| 1204 |
}, |
| 1205 |
); |
| 1206 |
Ok(()) |
| 1207 |
} |
| 1208 |
|
| 1209 |
fn parse_expr_shift_op( |
| 1210 |
&mut self, |
| 1211 |
ctx: &mut BlockContext, |
| 1212 |
emitter: &mut crate::proc::Emitter, |
| 1213 |
block: &mut crate::Block, |
| 1214 |
block_id: spirv::Word, |
| 1215 |
body_idx: usize, |
| 1216 |
op: crate::BinaryOperator, |
| 1217 |
) -> Result<(), Error> { |
| 1218 |
let start = self.data_offset; |
| 1219 |
let result_type_id = self.next()?; |
| 1220 |
let result_id = self.next()?; |
| 1221 |
let p1_id = self.next()?; |
| 1222 |
let p2_id = self.next()?; |
| 1223 |
|
| 1224 |
let span = self.span_from_with_op(start); |
| 1225 |
|
| 1226 |
let p1_lexp = self.lookup_expression.lookup(p1_id)?; |
| 1227 |
let left = self.get_expr_handle(p1_id, p1_lexp, ctx, emitter, block, body_idx); |
| 1228 |
let p2_lexp = self.lookup_expression.lookup(p2_id)?; |
| 1229 |
let p2_handle = self.get_expr_handle(p2_id, p2_lexp, ctx, emitter, block, body_idx); |
| 1230 |
// convert the shift to Uint |
| 1231 |
let right = ctx.expressions.append( |
| 1232 |
crate::Expression::As { |
| 1233 |
expr: p2_handle, |
| 1234 |
kind: crate::ScalarKind::Uint, |
| 1235 |
convert: None, |
| 1236 |
}, |
| 1237 |
span, |
| 1238 |
); |
| 1239 |
|
| 1240 |
let expr = crate::Expression::Binary { op, left, right }; |
| 1241 |
self.lookup_expression.insert( |
| 1242 |
result_id, |
| 1243 |
LookupExpression { |
| 1244 |
handle: ctx.expressions.append(expr, span), |
| 1245 |
type_id: result_type_id, |
| 1246 |
block_id, |
| 1247 |
}, |
| 1248 |
); |
| 1249 |
Ok(()) |
| 1250 |
} |
| 1251 |
|
| 1252 |
fn parse_expr_derivative( |
| 1253 |
&mut self, |
| 1254 |
ctx: &mut BlockContext, |
| 1255 |
emitter: &mut crate::proc::Emitter, |
| 1256 |
block: &mut crate::Block, |
| 1257 |
block_id: spirv::Word, |
| 1258 |
body_idx: usize, |
| 1259 |
(axis, ctrl): (crate::DerivativeAxis, crate::DerivativeControl), |
| 1260 |
) -> Result<(), Error> { |
| 1261 |
let start = self.data_offset; |
| 1262 |
let result_type_id = self.next()?; |
| 1263 |
let result_id = self.next()?; |
| 1264 |
let arg_id = self.next()?; |
| 1265 |
|
| 1266 |
let arg_lexp = self.lookup_expression.lookup(arg_id)?; |
| 1267 |
let arg_handle = self.get_expr_handle(arg_id, arg_lexp, ctx, emitter, block, body_idx); |
| 1268 |
|
| 1269 |
let expr = crate::Expression::Derivative { |
| 1270 |
axis, |
| 1271 |
ctrl, |
| 1272 |
expr: arg_handle, |
| 1273 |
}; |
| 1274 |
self.lookup_expression.insert( |
| 1275 |
result_id, |
| 1276 |
LookupExpression { |
| 1277 |
handle: ctx.expressions.append(expr, self.span_from_with_op(start)), |
| 1278 |
type_id: result_type_id, |
| 1279 |
block_id, |
| 1280 |
}, |
| 1281 |
); |
| 1282 |
Ok(()) |
| 1283 |
} |
| 1284 |
|
| 1285 |
#[allow(clippy::too_many_arguments)] |
| 1286 |
fn insert_composite( |
| 1287 |
&self, |
| 1288 |
root_expr: Handle<crate::Expression>, |
| 1289 |
root_type_id: spirv::Word, |
| 1290 |
object_expr: Handle<crate::Expression>, |
| 1291 |
selections: &[spirv::Word], |
| 1292 |
type_arena: &UniqueArena<crate::Type>, |
| 1293 |
expressions: &mut Arena<crate::Expression>, |
| 1294 |
span: crate::Span, |
| 1295 |
) -> Result<Handle<crate::Expression>, Error> { |
| 1296 |
let selection = match selections.first() { |
| 1297 |
Some(&index) => index, |
| 1298 |
None => return Ok(object_expr), |
| 1299 |
}; |
| 1300 |
let root_span = expressions.get_span(root_expr); |
| 1301 |
let root_lookup = self.lookup_type.lookup(root_type_id)?; |
| 1302 |
|
| 1303 |
let (count, child_type_id) = match type_arena[root_lookup.handle].inner { |
| 1304 |
crate::TypeInner::Struct { ref members, .. } => { |
| 1305 |
let child_member = self |
| 1306 |
.lookup_member |
| 1307 |
.get(&(root_lookup.handle, selection)) |
| 1308 |
.ok_or(Error::InvalidAccessType(root_type_id))?; |
| 1309 |
(members.len(), child_member.type_id) |
| 1310 |
} |
| 1311 |
crate::TypeInner::Array { size, .. } => { |
| 1312 |
let size = match size { |
| 1313 |
crate::ArraySize::Constant(size) => size.get(), |
| 1314 |
crate::ArraySize::Pending(_) => { |
| 1315 |
unreachable!(); |
| 1316 |
} |
| 1317 |
// A runtime sized array is not a composite type |
| 1318 |
crate::ArraySize::Dynamic => { |
| 1319 |
return Err(Error::InvalidAccessType(root_type_id)) |
| 1320 |
} |
| 1321 |
}; |
| 1322 |
|
| 1323 |
let child_type_id = root_lookup |
| 1324 |
.base_id |
| 1325 |
.ok_or(Error::InvalidAccessType(root_type_id))?; |
| 1326 |
|
| 1327 |
(size as usize, child_type_id) |
| 1328 |
} |
| 1329 |
crate::TypeInner::Vector { size, .. } |
| 1330 |
| crate::TypeInner::Matrix { columns: size, .. } => { |
| 1331 |
let child_type_id = root_lookup |
| 1332 |
.base_id |
| 1333 |
.ok_or(Error::InvalidAccessType(root_type_id))?; |
| 1334 |
(size as usize, child_type_id) |
| 1335 |
} |
| 1336 |
_ => return Err(Error::InvalidAccessType(root_type_id)), |
| 1337 |
}; |
| 1338 |
|
| 1339 |
let mut components = Vec::with_capacity(count); |
| 1340 |
for index in 0..count as u32 { |
| 1341 |
let expr = expressions.append( |
| 1342 |
crate::Expression::AccessIndex { |
| 1343 |
base: root_expr, |
| 1344 |
index, |
| 1345 |
}, |
| 1346 |
if index == selection { span } else { root_span }, |
| 1347 |
); |
| 1348 |
components.push(expr); |
| 1349 |
} |
| 1350 |
components[selection as usize] = self.insert_composite( |
| 1351 |
components[selection as usize], |
| 1352 |
child_type_id, |
| 1353 |
object_expr, |
| 1354 |
&selections[1..], |
| 1355 |
type_arena, |
| 1356 |
expressions, |
| 1357 |
span, |
| 1358 |
)?; |
| 1359 |
|
| 1360 |
Ok(expressions.append( |
| 1361 |
crate::Expression::Compose { |
| 1362 |
ty: root_lookup.handle, |
| 1363 |
components, |
| 1364 |
}, |
| 1365 |
span, |
| 1366 |
)) |
| 1367 |
} |
| 1368 |
|
| 1369 |
/// Return the Naga [`Expression`] for `pointer_id`, and its referent [`Type`]. |
| 1370 |
/// |
| 1371 |
/// Return a [`Handle`] for a Naga [`Expression`] that holds the value of |
| 1372 |
/// the SPIR-V instruction `pointer_id`, along with the [`Type`] to which it |
| 1373 |
/// is a pointer. |
| 1374 |
/// |
| 1375 |
/// This may entail spilling `pointer_id`'s value to a temporary: |
| 1376 |
/// see [`get_expr_handle`]'s documentation. |
| 1377 |
/// |
| 1378 |
/// [`Expression`]: crate::Expression |
| 1379 |
/// [`Type`]: crate::Type |
| 1380 |
/// [`Handle`]: crate::Handle |
| 1381 |
/// [`get_expr_handle`]: Frontend::get_expr_handle |
| 1382 |
fn get_exp_and_base_ty_handles( |
| 1383 |
&self, |
| 1384 |
pointer_id: spirv::Word, |
| 1385 |
ctx: &mut BlockContext, |
| 1386 |
emitter: &mut crate::proc::Emitter, |
| 1387 |
block: &mut crate::Block, |
| 1388 |
body_idx: usize, |
| 1389 |
) -> Result<(Handle<crate::Expression>, Handle<crate::Type>), Error> { |
| 1390 |
log::trace!("\t\t\tlooking up pointer expr {:?}", pointer_id); |
| 1391 |
let p_lexp_handle; |
| 1392 |
let p_lexp_ty_id; |
| 1393 |
{ |
| 1394 |
let lexp = self.lookup_expression.lookup(pointer_id)?; |
| 1395 |
p_lexp_handle = self.get_expr_handle(pointer_id, lexp, ctx, emitter, block, body_idx); |
| 1396 |
p_lexp_ty_id = lexp.type_id; |
| 1397 |
}; |
| 1398 |
|
| 1399 |
log::trace!("\t\t\tlooking up pointer type {pointer_id:?}"); |
| 1400 |
let p_ty = self.lookup_type.lookup(p_lexp_ty_id)?; |
| 1401 |
let p_ty_base_id = p_ty.base_id.ok_or(Error::InvalidAccessType(p_lexp_ty_id))?; |
| 1402 |
|
| 1403 |
log::trace!("\t\t\tlooking up pointer base type {p_ty_base_id:?} of {p_ty:?}"); |
| 1404 |
let p_base_ty = self.lookup_type.lookup(p_ty_base_id)?; |
| 1405 |
|
| 1406 |
Ok((p_lexp_handle, p_base_ty.handle)) |
| 1407 |
} |
| 1408 |
|
| 1409 |
#[allow(clippy::too_many_arguments)] |
| 1410 |
fn parse_atomic_expr_with_value( |
| 1411 |
&mut self, |
| 1412 |
inst: Instruction, |
| 1413 |
emitter: &mut crate::proc::Emitter, |
| 1414 |
ctx: &mut BlockContext, |
| 1415 |
block: &mut crate::Block, |
| 1416 |
block_id: spirv::Word, |
| 1417 |
body_idx: usize, |
| 1418 |
atomic_function: crate::AtomicFunction, |
| 1419 |
) -> Result<(), Error> { |
| 1420 |
inst.expect(7)?; |
| 1421 |
let start = self.data_offset; |
| 1422 |
let result_type_id = self.next()?; |
| 1423 |
let result_id = self.next()?; |
| 1424 |
let pointer_id = self.next()?; |
| 1425 |
let _scope_id = self.next()?; |
| 1426 |
let _memory_semantics_id = self.next()?; |
| 1427 |
let value_id = self.next()?; |
| 1428 |
let span = self.span_from_with_op(start); |
| 1429 |
|
| 1430 |
let (p_lexp_handle, p_base_ty_handle) = |
| 1431 |
self.get_exp_and_base_ty_handles(pointer_id, ctx, emitter, block, body_idx)?; |
| 1432 |
|
| 1433 |
log::trace!("\t\t\tlooking up value expr {value_id:?}"); |
| 1434 |
let v_lexp_handle = self.lookup_expression.lookup(value_id)?.handle; |
| 1435 |
|
| 1436 |
block.extend(emitter.finish(ctx.expressions)); |
| 1437 |
// Create an expression for our result |
| 1438 |
let r_lexp_handle = { |
| 1439 |
let expr = crate::Expression::AtomicResult { |
| 1440 |
ty: p_base_ty_handle, |
| 1441 |
comparison: false, |
| 1442 |
}; |
| 1443 |
let handle = ctx.expressions.append(expr, span); |
| 1444 |
self.lookup_expression.insert( |
| 1445 |
result_id, |
| 1446 |
LookupExpression { |
| 1447 |
handle, |
| 1448 |
type_id: result_type_id, |
| 1449 |
block_id, |
| 1450 |
}, |
| 1451 |
); |
| 1452 |
handle |
| 1453 |
}; |
| 1454 |
emitter.start(ctx.expressions); |
| 1455 |
|
| 1456 |
// Create a statement for the op itself |
| 1457 |
let stmt = crate::Statement::Atomic { |
| 1458 |
pointer: p_lexp_handle, |
| 1459 |
fun: atomic_function, |
| 1460 |
value: v_lexp_handle, |
| 1461 |
result: Some(r_lexp_handle), |
| 1462 |
}; |
| 1463 |
block.push(stmt, span); |
| 1464 |
|
| 1465 |
// Store any associated global variables so we can upgrade their types later |
| 1466 |
self.record_atomic_access(ctx, p_lexp_handle)?; |
| 1467 |
|
| 1468 |
Ok(()) |
| 1469 |
} |
| 1470 |
|
| 1471 |
/// Add the next SPIR-V block's contents to `block_ctx`. |
| 1472 |
/// |
| 1473 |
/// Except for the function's entry block, `block_id` should be the label of |
| 1474 |
/// a block we've seen mentioned before, with an entry in |
| 1475 |
/// `block_ctx.body_for_label` to tell us which `Body` it contributes to. |
| 1476 |
fn next_block(&mut self, block_id: spirv::Word, ctx: &mut BlockContext) -> Result<(), Error> { |
| 1477 |
// Extend `body` with the correct form for a branch to `target`. |
| 1478 |
fn merger(body: &mut Body, target: &MergeBlockInformation) { |
| 1479 |
body.data.push(match *target { |
| 1480 |
MergeBlockInformation::LoopContinue => BodyFragment::Continue, |
| 1481 |
MergeBlockInformation::LoopMerge | MergeBlockInformation::SwitchMerge => { |
| 1482 |
BodyFragment::Break |
| 1483 |
} |
| 1484 |
|
| 1485 |
// Finishing a selection merge means just falling off the end of |
| 1486 |
// the `accept` or `reject` block of the `If` statement. |
| 1487 |
MergeBlockInformation::SelectionMerge => return, |
| 1488 |
}) |
| 1489 |
} |
| 1490 |
|
| 1491 |
let mut emitter = crate::proc::Emitter::default(); |
| 1492 |
emitter.start(ctx.expressions); |
| 1493 |
|
| 1494 |
// Find the `Body` to which this block contributes. |
| 1495 |
// |
| 1496 |
// If this is some SPIR-V structured control flow construct's merge |
| 1497 |
// block, then `body_idx` will refer to the same `Body` as the header, |
| 1498 |
// so that we simply pick up accumulating the `Body` where the header |
| 1499 |
// left off. Each of the statements in a block dominates the next, so |
| 1500 |
// we're sure to encounter their SPIR-V blocks in order, ensuring that |
| 1501 |
// the `Body` will be assembled in the proper order. |
| 1502 |
// |
| 1503 |
// Note that, unlike every other kind of SPIR-V block, we don't know the |
| 1504 |
// function's first block's label in advance. Thus, we assume that if |
| 1505 |
// this block has no entry in `ctx.body_for_label`, it must be the |
| 1506 |
// function's first block. This always has body index zero. |
| 1507 |
let mut body_idx = *ctx.body_for_label.entry(block_id).or_default(); |
| 1508 |
|
| 1509 |
// The Naga IR block this call builds. This will end up as |
| 1510 |
// `ctx.blocks[&block_id]`, and `ctx.bodies[body_idx]` will refer to it |
| 1511 |
// via a `BodyFragment::BlockId`. |
| 1512 |
let mut block = crate::Block::new(); |
| 1513 |
|
| 1514 |
// Stores the merge block as defined by a `OpSelectionMerge` otherwise is `None` |
| 1515 |
// |
| 1516 |
// This is used in `OpSwitch` to promote the `MergeBlockInformation` from |
| 1517 |
// `SelectionMerge` to `SwitchMerge` to allow `Break`s this isn't desirable for |
| 1518 |
// `LoopMerge`s because otherwise `Continue`s wouldn't be allowed |
| 1519 |
let mut selection_merge_block = None; |
| 1520 |
|
| 1521 |
macro_rules! get_expr_handle { |
| 1522 |
($id:expr, $lexp:expr) => { |
| 1523 |
self.get_expr_handle($id, $lexp, ctx, &mut emitter, &mut block, body_idx) |
| 1524 |
}; |
| 1525 |
} |
| 1526 |
macro_rules! parse_expr_op { |
| 1527 |
($op:expr, BINARY) => { |
| 1528 |
self.parse_expr_binary_op(ctx, &mut emitter, &mut block, block_id, body_idx, $op) |
| 1529 |
}; |
| 1530 |
|
| 1531 |
($op:expr, SHIFT) => { |
| 1532 |
self.parse_expr_shift_op(ctx, &mut emitter, &mut block, block_id, body_idx, $op) |
| 1533 |
}; |
| 1534 |
($op:expr, UNARY) => { |
| 1535 |
self.parse_expr_unary_op(ctx, &mut emitter, &mut block, block_id, body_idx, $op) |
| 1536 |
}; |
| 1537 |
($axis:expr, $ctrl:expr, DERIVATIVE) => { |
| 1538 |
self.parse_expr_derivative( |
| 1539 |
ctx, |
| 1540 |
&mut emitter, |
| 1541 |
&mut block, |
| 1542 |
block_id, |
| 1543 |
body_idx, |
| 1544 |
($axis, $ctrl), |
| 1545 |
) |
| 1546 |
}; |
| 1547 |
} |
| 1548 |
|
| 1549 |
let terminator = loop { |
| 1550 |
use spirv::Op; |
| 1551 |
let start = self.data_offset; |
| 1552 |
let inst = self.next_inst()?; |
| 1553 |
let span = crate::Span::from(start..(start + 4 * (inst.wc as usize))); |
| 1554 |
log::debug!("\t\t{:?} [{}]", inst.op, inst.wc); |
| 1555 |
|
| 1556 |
match inst.op { |
| 1557 |
Op::Line => { |
| 1558 |
inst.expect(4)?; |
| 1559 |
let _file_id = self.next()?; |
| 1560 |
let _row_id = self.next()?; |
| 1561 |
let _col_id = self.next()?; |
| 1562 |
} |
| 1563 |
Op::NoLine => inst.expect(1)?, |
| 1564 |
Op::Undef => { |
| 1565 |
inst.expect(3)?; |
| 1566 |
let type_id = self.next()?; |
| 1567 |
let id = self.next()?; |
| 1568 |
let type_lookup = self.lookup_type.lookup(type_id)?; |
| 1569 |
let ty = type_lookup.handle; |
| 1570 |
|
| 1571 |
self.lookup_expression.insert( |
| 1572 |
id, |
| 1573 |
LookupExpression { |
| 1574 |
handle: ctx |
| 1575 |
.expressions |
| 1576 |
.append(crate::Expression::ZeroValue(ty), span), |
| 1577 |
type_id, |
| 1578 |
block_id, |
| 1579 |
}, |
| 1580 |
); |
| 1581 |
} |
| 1582 |
Op::Variable => { |
| 1583 |
inst.expect_at_least(4)?; |
| 1584 |
block.extend(emitter.finish(ctx.expressions)); |
| 1585 |
|
| 1586 |
let result_type_id = self.next()?; |
| 1587 |
let result_id = self.next()?; |
| 1588 |
let _storage_class = self.next()?; |
| 1589 |
let init = if inst.wc > 4 { |
| 1590 |
inst.expect(5)?; |
| 1591 |
let init_id = self.next()?; |
| 1592 |
let lconst = self.lookup_constant.lookup(init_id)?; |
| 1593 |
Some(ctx.expressions.append(lconst.inner.to_expr(), span)) |
| 1594 |
} else { |
| 1595 |
None |
| 1596 |
}; |
| 1597 |
|
| 1598 |
let name = self |
| 1599 |
.future_decor |
| 1600 |
.remove(&result_id) |
| 1601 |
.and_then(|decor| decor.name); |
| 1602 |
if let Some(ref name) = name { |
| 1603 |
log::debug!("\t\t\tid={} name={}", result_id, name); |
| 1604 |
} |
| 1605 |
let lookup_ty = self.lookup_type.lookup(result_type_id)?; |
| 1606 |
let var_handle = ctx.local_arena.append( |
| 1607 |
crate::LocalVariable { |
| 1608 |
name, |
| 1609 |
ty: match ctx.module.types[lookup_ty.handle].inner { |
| 1610 |
crate::TypeInner::Pointer { base, .. } => base, |
| 1611 |
_ => lookup_ty.handle, |
| 1612 |
}, |
| 1613 |
init, |
| 1614 |
}, |
| 1615 |
span, |
| 1616 |
); |
| 1617 |
|
| 1618 |
self.lookup_expression.insert( |
| 1619 |
result_id, |
| 1620 |
LookupExpression { |
| 1621 |
handle: ctx |
| 1622 |
.expressions |
| 1623 |
.append(crate::Expression::LocalVariable(var_handle), span), |
| 1624 |
type_id: result_type_id, |
| 1625 |
block_id, |
| 1626 |
}, |
| 1627 |
); |
| 1628 |
emitter.start(ctx.expressions); |
| 1629 |
} |
| 1630 |
Op::Phi => { |
| 1631 |
inst.expect_at_least(3)?; |
| 1632 |
block.extend(emitter.finish(ctx.expressions)); |
| 1633 |
|
| 1634 |
let result_type_id = self.next()?; |
| 1635 |
let result_id = self.next()?; |
| 1636 |
|
| 1637 |
let name = format!("phi_{result_id}"); |
| 1638 |
let local = ctx.local_arena.append( |
| 1639 |
crate::LocalVariable { |
| 1640 |
name: Some(name), |
| 1641 |
ty: self.lookup_type.lookup(result_type_id)?.handle, |
| 1642 |
init: None, |
| 1643 |
}, |
| 1644 |
self.span_from(start), |
| 1645 |
); |
| 1646 |
let pointer = ctx |
| 1647 |
.expressions |
| 1648 |
.append(crate::Expression::LocalVariable(local), span); |
| 1649 |
|
| 1650 |
let in_count = (inst.wc - 3) / 2; |
| 1651 |
let mut phi = PhiExpression { |
| 1652 |
local, |
| 1653 |
expressions: Vec::with_capacity(in_count as usize), |
| 1654 |
}; |
| 1655 |
for _ in 0..in_count { |
| 1656 |
let expr = self.next()?; |
| 1657 |
let block = self.next()?; |
| 1658 |
phi.expressions.push((expr, block)); |
| 1659 |
} |
| 1660 |
|
| 1661 |
ctx.phis.push(phi); |
| 1662 |
emitter.start(ctx.expressions); |
| 1663 |
|
| 1664 |
// Associate the lookup with an actual value, which is emitted |
| 1665 |
// into the current block. |
| 1666 |
self.lookup_expression.insert( |
| 1667 |
result_id, |
| 1668 |
LookupExpression { |
| 1669 |
handle: ctx |
| 1670 |
.expressions |
| 1671 |
.append(crate::Expression::Load { pointer }, span), |
| 1672 |
type_id: result_type_id, |
| 1673 |
block_id, |
| 1674 |
}, |
| 1675 |
); |
| 1676 |
} |
| 1677 |
Op::AccessChain | Op::InBoundsAccessChain => { |
| 1678 |
struct AccessExpression { |
| 1679 |
base_handle: Handle<crate::Expression>, |
| 1680 |
type_id: spirv::Word, |
| 1681 |
load_override: Option<LookupLoadOverride>, |
| 1682 |
} |
| 1683 |
|
| 1684 |
inst.expect_at_least(4)?; |
| 1685 |
|
| 1686 |
let result_type_id = self.next()?; |
| 1687 |
let result_id = self.next()?; |
| 1688 |
let base_id = self.next()?; |
| 1689 |
log::trace!("\t\t\tlooking up expr {:?}", base_id); |
| 1690 |
|
| 1691 |
let mut acex = { |
| 1692 |
let lexp = self.lookup_expression.lookup(base_id)?; |
| 1693 |
let lty = self.lookup_type.lookup(lexp.type_id)?; |
| 1694 |
|
| 1695 |
// HACK `OpAccessChain` and `OpInBoundsAccessChain` |
| 1696 |
// require for the result type to be a pointer, but if |
| 1697 |
// we're given a pointer to an image / sampler, it will |
| 1698 |
// be *already* dereferenced, since we do that early |
| 1699 |
// during `parse_type_pointer()`. |
| 1700 |
// |
| 1701 |
// This can happen only through `BindingArray`, since |
| 1702 |
// that's the only case where one can obtain a pointer |
| 1703 |
// to an image / sampler, and so let's match on that: |
| 1704 |
let dereference = match ctx.module.types[lty.handle].inner { |
| 1705 |
crate::TypeInner::BindingArray { .. } => false, |
| 1706 |
_ => true, |
| 1707 |
}; |
| 1708 |
|
| 1709 |
let type_id = if dereference { |
| 1710 |
lty.base_id.ok_or(Error::InvalidAccessType(lexp.type_id))? |
| 1711 |
} else { |
| 1712 |
lexp.type_id |
| 1713 |
}; |
| 1714 |
|
| 1715 |
AccessExpression { |
| 1716 |
base_handle: get_expr_handle!(base_id, lexp), |
| 1717 |
type_id, |
| 1718 |
load_override: self.lookup_load_override.get(&base_id).cloned(), |
| 1719 |
} |
| 1720 |
}; |
| 1721 |
|
| 1722 |
for _ in 4..inst.wc { |
| 1723 |
let access_id = self.next()?; |
| 1724 |
log::trace!("\t\t\tlooking up index expr {:?}", access_id); |
| 1725 |
let index_expr = self.lookup_expression.lookup(access_id)?.clone(); |
| 1726 |
let index_expr_handle = get_expr_handle!(access_id, &index_expr); |
| 1727 |
let index_expr_data = &ctx.expressions[index_expr.handle]; |
| 1728 |
let index_maybe = match *index_expr_data { |
| 1729 |
crate::Expression::Constant(const_handle) => Some( |
| 1730 |
ctx.gctx() |
| 1731 |
.eval_expr_to_u32(ctx.module.constants[const_handle].init) |
| 1732 |
.map_err(|_| { |
| 1733 |
Error::InvalidAccess(crate::Expression::Constant( |
| 1734 |
const_handle, |
| 1735 |
)) |
| 1736 |
})?, |
| 1737 |
), |
| 1738 |
_ => None, |
| 1739 |
}; |
| 1740 |
|
| 1741 |
log::trace!("\t\t\tlooking up type {:?}", acex.type_id); |
| 1742 |
let type_lookup = self.lookup_type.lookup(acex.type_id)?; |
| 1743 |
let ty = &ctx.module.types[type_lookup.handle]; |
| 1744 |
acex = match ty.inner { |
| 1745 |
// can only index a struct with a constant |
| 1746 |
crate::TypeInner::Struct { ref members, .. } => { |
| 1747 |
let index = index_maybe |
| 1748 |
.ok_or_else(|| Error::InvalidAccess(index_expr_data.clone()))?; |
| 1749 |
|
| 1750 |
let lookup_member = self |
| 1751 |
.lookup_member |
| 1752 |
.get(&(type_lookup.handle, index)) |
| 1753 |
.ok_or(Error::InvalidAccessType(acex.type_id))?; |
| 1754 |
let base_handle = ctx.expressions.append( |
| 1755 |
crate::Expression::AccessIndex { |
| 1756 |
base: acex.base_handle, |
| 1757 |
index, |
| 1758 |
}, |
| 1759 |
span, |
| 1760 |
); |
| 1761 |
|
| 1762 |
if let Some(crate::Binding::BuiltIn(built_in)) = |
| 1763 |
members[index as usize].binding |
| 1764 |
{ |
| 1765 |
self.gl_per_vertex_builtin_access.insert(built_in); |
| 1766 |
} |
| 1767 |
|
| 1768 |
AccessExpression { |
| 1769 |
base_handle, |
| 1770 |
type_id: lookup_member.type_id, |
| 1771 |
load_override: if lookup_member.row_major { |
| 1772 |
debug_assert!(acex.load_override.is_none()); |
| 1773 |
let sub_type_lookup = |
| 1774 |
self.lookup_type.lookup(lookup_member.type_id)?; |
| 1775 |
Some(match ctx.module.types[sub_type_lookup.handle].inner { |
| 1776 |
// load it transposed, to match column major expectations |
| 1777 |
crate::TypeInner::Matrix { .. } => { |
| 1778 |
let loaded = ctx.expressions.append( |
| 1779 |
crate::Expression::Load { |
| 1780 |
pointer: base_handle, |
| 1781 |
}, |
| 1782 |
span, |
| 1783 |
); |
| 1784 |
let transposed = ctx.expressions.append( |
| 1785 |
crate::Expression::Math { |
| 1786 |
fun: crate::MathFunction::Transpose, |
| 1787 |
arg: loaded, |
| 1788 |
arg1: None, |
| 1789 |
arg2: None, |
| 1790 |
arg3: None, |
| 1791 |
}, |
| 1792 |
span, |
| 1793 |
); |
| 1794 |
LookupLoadOverride::Loaded(transposed) |
| 1795 |
} |
| 1796 |
_ => LookupLoadOverride::Pending, |
| 1797 |
}) |
| 1798 |
} else { |
| 1799 |
None |
| 1800 |
}, |
| 1801 |
} |
| 1802 |
} |
| 1803 |
crate::TypeInner::Matrix { .. } => { |
| 1804 |
let load_override = match acex.load_override { |
| 1805 |
// We are indexing inside a row-major matrix |
| 1806 |
Some(LookupLoadOverride::Loaded(load_expr)) => { |
| 1807 |
let index = index_maybe.ok_or_else(|| { |
| 1808 |
Error::InvalidAccess(index_expr_data.clone()) |
| 1809 |
})?; |
| 1810 |
let sub_handle = ctx.expressions.append( |
| 1811 |
crate::Expression::AccessIndex { |
| 1812 |
base: load_expr, |
| 1813 |
index, |
| 1814 |
}, |
| 1815 |
span, |
| 1816 |
); |
| 1817 |
Some(LookupLoadOverride::Loaded(sub_handle)) |
| 1818 |
} |
| 1819 |
_ => None, |
| 1820 |
}; |
| 1821 |
let sub_expr = match index_maybe { |
| 1822 |
Some(index) => crate::Expression::AccessIndex { |
| 1823 |
base: acex.base_handle, |
| 1824 |
index, |
| 1825 |
}, |
| 1826 |
None => crate::Expression::Access { |
| 1827 |
base: acex.base_handle, |
| 1828 |
index: index_expr_handle, |
| 1829 |
}, |
| 1830 |
}; |
| 1831 |
AccessExpression { |
| 1832 |
base_handle: ctx.expressions.append(sub_expr, span), |
| 1833 |
type_id: type_lookup |
| 1834 |
.base_id |
| 1835 |
.ok_or(Error::InvalidAccessType(acex.type_id))?, |
| 1836 |
load_override, |
| 1837 |
} |
| 1838 |
} |
| 1839 |
// This must be a vector or an array. |
| 1840 |
_ => { |
| 1841 |
let base_handle = ctx.expressions.append( |
| 1842 |
crate::Expression::Access { |
| 1843 |
base: acex.base_handle, |
| 1844 |
index: index_expr_handle, |
| 1845 |
}, |
| 1846 |
span, |
| 1847 |
); |
| 1848 |
let load_override = match acex.load_override { |
| 1849 |
// If there is a load override in place, then we always end up |
| 1850 |
// with a side-loaded value here. |
| 1851 |
Some(lookup_load_override) => { |
| 1852 |
let sub_expr = match lookup_load_override { |
| 1853 |
// We must be indexing into the array of row-major matrices. |
| 1854 |
// Let's load the result of indexing and transpose it. |
| 1855 |
LookupLoadOverride::Pending => { |
| 1856 |
let loaded = ctx.expressions.append( |
| 1857 |
crate::Expression::Load { |
| 1858 |
pointer: base_handle, |
| 1859 |
}, |
| 1860 |
span, |
| 1861 |
); |
| 1862 |
ctx.expressions.append( |
| 1863 |
crate::Expression::Math { |
| 1864 |
fun: crate::MathFunction::Transpose, |
| 1865 |
arg: loaded, |
| 1866 |
arg1: None, |
| 1867 |
arg2: None, |
| 1868 |
arg3: None, |
| 1869 |
}, |
| 1870 |
span, |
| 1871 |
) |
| 1872 |
} |
| 1873 |
// We are indexing inside a row-major matrix. |
| 1874 |
LookupLoadOverride::Loaded(load_expr) => { |
| 1875 |
ctx.expressions.append( |
| 1876 |
crate::Expression::Access { |
| 1877 |
base: load_expr, |
| 1878 |
index: index_expr_handle, |
| 1879 |
}, |
| 1880 |
span, |
| 1881 |
) |
| 1882 |
} |
| 1883 |
}; |
| 1884 |
Some(LookupLoadOverride::Loaded(sub_expr)) |
| 1885 |
} |
| 1886 |
None => None, |
| 1887 |
}; |
| 1888 |
AccessExpression { |
| 1889 |
base_handle, |
| 1890 |
type_id: type_lookup |
| 1891 |
.base_id |
| 1892 |
.ok_or(Error::InvalidAccessType(acex.type_id))?, |
| 1893 |
load_override, |
| 1894 |
} |
| 1895 |
} |
| 1896 |
}; |
| 1897 |
} |
| 1898 |
|
| 1899 |
if let Some(load_expr) = acex.load_override { |
| 1900 |
self.lookup_load_override.insert(result_id, load_expr); |
| 1901 |
} |
| 1902 |
let lookup_expression = LookupExpression { |
| 1903 |
handle: acex.base_handle, |
| 1904 |
type_id: result_type_id, |
| 1905 |
block_id, |
| 1906 |
}; |
| 1907 |
self.lookup_expression.insert(result_id, lookup_expression); |
| 1908 |
} |
| 1909 |
Op::VectorExtractDynamic => { |
| 1910 |
inst.expect(5)?; |
| 1911 |
|
| 1912 |
let result_type_id = self.next()?; |
| 1913 |
let id = self.next()?; |
| 1914 |
let composite_id = self.next()?; |
| 1915 |
let index_id = self.next()?; |
| 1916 |
|
| 1917 |
let root_lexp = self.lookup_expression.lookup(composite_id)?; |
| 1918 |
let root_handle = get_expr_handle!(composite_id, root_lexp); |
| 1919 |
let root_type_lookup = self.lookup_type.lookup(root_lexp.type_id)?; |
| 1920 |
let index_lexp = self.lookup_expression.lookup(index_id)?; |
| 1921 |
let index_handle = get_expr_handle!(index_id, index_lexp); |
| 1922 |
let index_type = self.lookup_type.lookup(index_lexp.type_id)?.handle; |
| 1923 |
|
| 1924 |
let num_components = match ctx.module.types[root_type_lookup.handle].inner { |
| 1925 |
crate::TypeInner::Vector { size, .. } => size as u32, |
| 1926 |
_ => return Err(Error::InvalidVectorType(root_type_lookup.handle)), |
| 1927 |
}; |
| 1928 |
|
| 1929 |
let mut make_index = |ctx: &mut BlockContext, index: u32| { |
| 1930 |
make_index_literal( |
| 1931 |
ctx, |
| 1932 |
index, |
| 1933 |
&mut block, |
| 1934 |
&mut emitter, |
| 1935 |
index_type, |
| 1936 |
index_lexp.type_id, |
| 1937 |
span, |
| 1938 |
) |
| 1939 |
}; |
| 1940 |
|
| 1941 |
let index_expr = make_index(ctx, 0)?; |
| 1942 |
let mut handle = ctx.expressions.append( |
| 1943 |
crate::Expression::Access { |
| 1944 |
base: root_handle, |
| 1945 |
index: index_expr, |
| 1946 |
}, |
| 1947 |
span, |
| 1948 |
); |
| 1949 |
for index in 1..num_components { |
| 1950 |
let index_expr = make_index(ctx, index)?; |
| 1951 |
let access_expr = ctx.expressions.append( |
| 1952 |
crate::Expression::Access { |
| 1953 |
base: root_handle, |
| 1954 |
index: index_expr, |
| 1955 |
}, |
| 1956 |
span, |
| 1957 |
); |
| 1958 |
let cond = ctx.expressions.append( |
| 1959 |
crate::Expression::Binary { |
| 1960 |
op: crate::BinaryOperator::Equal, |
| 1961 |
left: index_expr, |
| 1962 |
right: index_handle, |
| 1963 |
}, |
| 1964 |
span, |
| 1965 |
); |
| 1966 |
handle = ctx.expressions.append( |
| 1967 |
crate::Expression::Select { |
| 1968 |
condition: cond, |
| 1969 |
accept: access_expr, |
| 1970 |
reject: handle, |
| 1971 |
}, |
| 1972 |
span, |
| 1973 |
); |
| 1974 |
} |
| 1975 |
|
| 1976 |
self.lookup_expression.insert( |
| 1977 |
id, |
| 1978 |
LookupExpression { |
| 1979 |
handle, |
| 1980 |
type_id: result_type_id, |
| 1981 |
block_id, |
| 1982 |
}, |
| 1983 |
); |
| 1984 |
} |
| 1985 |
Op::VectorInsertDynamic => { |
| 1986 |
inst.expect(6)?; |
| 1987 |
|
| 1988 |
let result_type_id = self.next()?; |
| 1989 |
let id = self.next()?; |
| 1990 |
let composite_id = self.next()?; |
| 1991 |
let object_id = self.next()?; |
| 1992 |
let index_id = self.next()?; |
| 1993 |
|
| 1994 |
let object_lexp = self.lookup_expression.lookup(object_id)?; |
| 1995 |
let object_handle = get_expr_handle!(object_id, object_lexp); |
| 1996 |
let root_lexp = self.lookup_expression.lookup(composite_id)?; |
| 1997 |
let root_handle = get_expr_handle!(composite_id, root_lexp); |
| 1998 |
let root_type_lookup = self.lookup_type.lookup(root_lexp.type_id)?; |
| 1999 |
let index_lexp = self.lookup_expression.lookup(index_id)?; |
| 2000 |
let index_handle = get_expr_handle!(index_id, index_lexp); |
| 2001 |
let index_type = self.lookup_type.lookup(index_lexp.type_id)?.handle; |
| 2002 |
|
| 2003 |
let num_components = match ctx.module.types[root_type_lookup.handle].inner { |
| 2004 |
crate::TypeInner::Vector { size, .. } => size as u32, |
| 2005 |
_ => return Err(Error::InvalidVectorType(root_type_lookup.handle)), |
| 2006 |
}; |
| 2007 |
|
| 2008 |
let mut components = Vec::with_capacity(num_components as usize); |
| 2009 |
for index in 0..num_components { |
| 2010 |
let index_expr = make_index_literal( |
| 2011 |
ctx, |
| 2012 |
index, |
| 2013 |
&mut block, |
| 2014 |
&mut emitter, |
| 2015 |
index_type, |
| 2016 |
index_lexp.type_id, |
| 2017 |
span, |
| 2018 |
)?; |
| 2019 |
let access_expr = ctx.expressions.append( |
| 2020 |
crate::Expression::Access { |
| 2021 |
base: root_handle, |
| 2022 |
index: index_expr, |
| 2023 |
}, |
| 2024 |
span, |
| 2025 |
); |
| 2026 |
let cond = ctx.expressions.append( |
| 2027 |
crate::Expression::Binary { |
| 2028 |
op: crate::BinaryOperator::Equal, |
| 2029 |
left: index_expr, |
| 2030 |
right: index_handle, |
| 2031 |
}, |
| 2032 |
span, |
| 2033 |
); |
| 2034 |
let handle = ctx.expressions.append( |
| 2035 |
crate::Expression::Select { |
| 2036 |
condition: cond, |
| 2037 |
accept: object_handle, |
| 2038 |
reject: access_expr, |
| 2039 |
}, |
| 2040 |
span, |
| 2041 |
); |
| 2042 |
components.push(handle); |
| 2043 |
} |
| 2044 |
let handle = ctx.expressions.append( |
| 2045 |
crate::Expression::Compose { |
| 2046 |
ty: root_type_lookup.handle, |
| 2047 |
components, |
| 2048 |
}, |
| 2049 |
span, |
| 2050 |
); |
| 2051 |
|
| 2052 |
self.lookup_expression.insert( |
| 2053 |
id, |
| 2054 |
LookupExpression { |
| 2055 |
handle, |
| 2056 |
type_id: result_type_id, |
| 2057 |
block_id, |
| 2058 |
}, |
| 2059 |
); |
| 2060 |
} |
| 2061 |
Op::CompositeExtract => { |
| 2062 |
inst.expect_at_least(4)?; |
| 2063 |
|
| 2064 |
let result_type_id = self.next()?; |
| 2065 |
let result_id = self.next()?; |
| 2066 |
let base_id = self.next()?; |
| 2067 |
log::trace!("\t\t\tlooking up expr {:?}", base_id); |
| 2068 |
let mut lexp = self.lookup_expression.lookup(base_id)?.clone(); |
| 2069 |
lexp.handle = get_expr_handle!(base_id, &lexp); |
| 2070 |
for _ in 4..inst.wc { |
| 2071 |
let index = self.next()?; |
| 2072 |
log::trace!("\t\t\tlooking up type {:?}", lexp.type_id); |
| 2073 |
let type_lookup = self.lookup_type.lookup(lexp.type_id)?; |
| 2074 |
let type_id = match ctx.module.types[type_lookup.handle].inner { |
| 2075 |
crate::TypeInner::Struct { .. } => { |
| 2076 |
self.lookup_member |
| 2077 |
.get(&(type_lookup.handle, index)) |
| 2078 |
.ok_or(Error::InvalidAccessType(lexp.type_id))? |
| 2079 |
.type_id |
| 2080 |
} |
| 2081 |
crate::TypeInner::Array { .. } |
| 2082 |
| crate::TypeInner::Vector { .. } |
| 2083 |
| crate::TypeInner::Matrix { .. } => type_lookup |
| 2084 |
.base_id |
| 2085 |
.ok_or(Error::InvalidAccessType(lexp.type_id))?, |
| 2086 |
ref other => { |
| 2087 |
log::warn!("composite type {:?}", other); |
| 2088 |
return Err(Error::UnsupportedType(type_lookup.handle)); |
| 2089 |
} |
| 2090 |
}; |
| 2091 |
lexp = LookupExpression { |
| 2092 |
handle: ctx.expressions.append( |
| 2093 |
crate::Expression::AccessIndex { |
| 2094 |
base: lexp.handle, |
| 2095 |
index, |
| 2096 |
}, |
| 2097 |
span, |
| 2098 |
), |
| 2099 |
type_id, |
| 2100 |
block_id, |
| 2101 |
}; |
| 2102 |
} |
| 2103 |
|
| 2104 |
self.lookup_expression.insert( |
| 2105 |
result_id, |
| 2106 |
LookupExpression { |
| 2107 |
handle: lexp.handle, |
| 2108 |
type_id: result_type_id, |
| 2109 |
block_id, |
| 2110 |
}, |
| 2111 |
); |
| 2112 |
} |
| 2113 |
Op::CompositeInsert => { |
| 2114 |
inst.expect_at_least(5)?; |
| 2115 |
|
| 2116 |
let result_type_id = self.next()?; |
| 2117 |
let id = self.next()?; |
| 2118 |
let object_id = self.next()?; |
| 2119 |
let composite_id = self.next()?; |
| 2120 |
let mut selections = Vec::with_capacity(inst.wc as usize - 5); |
| 2121 |
for _ in 5..inst.wc { |
| 2122 |
selections.push(self.next()?); |
| 2123 |
} |
| 2124 |
|
| 2125 |
let object_lexp = self.lookup_expression.lookup(object_id)?.clone(); |
| 2126 |
let object_handle = get_expr_handle!(object_id, &object_lexp); |
| 2127 |
let root_lexp = self.lookup_expression.lookup(composite_id)?.clone(); |
| 2128 |
let root_handle = get_expr_handle!(composite_id, &root_lexp); |
| 2129 |
let handle = self.insert_composite( |
| 2130 |
root_handle, |
| 2131 |
result_type_id, |
| 2132 |
object_handle, |
| 2133 |
&selections, |
| 2134 |
&ctx.module.types, |
| 2135 |
ctx.expressions, |
| 2136 |
span, |
| 2137 |
)?; |
| 2138 |
|
| 2139 |
self.lookup_expression.insert( |
| 2140 |
id, |
| 2141 |
LookupExpression { |
| 2142 |
handle, |
| 2143 |
type_id: result_type_id, |
| 2144 |
block_id, |
| 2145 |
}, |
| 2146 |
); |
| 2147 |
} |
| 2148 |
Op::CompositeConstruct => { |
| 2149 |
inst.expect_at_least(3)?; |
| 2150 |
|
| 2151 |
let result_type_id = self.next()?; |
| 2152 |
let id = self.next()?; |
| 2153 |
let mut components = Vec::with_capacity(inst.wc as usize - 2); |
| 2154 |
for _ in 3..inst.wc { |
| 2155 |
let comp_id = self.next()?; |
| 2156 |
log::trace!("\t\t\tlooking up expr {:?}", comp_id); |
| 2157 |
let lexp = self.lookup_expression.lookup(comp_id)?; |
| 2158 |
let handle = get_expr_handle!(comp_id, lexp); |
| 2159 |
components.push(handle); |
| 2160 |
} |
| 2161 |
let ty = self.lookup_type.lookup(result_type_id)?.handle; |
| 2162 |
let first = components[0]; |
| 2163 |
let expr = match ctx.module.types[ty].inner { |
| 2164 |
// this is an optimization to detect the splat |
| 2165 |
crate::TypeInner::Vector { size, .. } |
| 2166 |
if components.len() == size as usize |
| 2167 |
&& components[1..].iter().all(|&c| c == first) => |
| 2168 |
{ |
| 2169 |
crate::Expression::Splat { size, value: first } |
| 2170 |
} |
| 2171 |
_ => crate::Expression::Compose { ty, components }, |
| 2172 |
}; |
| 2173 |
self.lookup_expression.insert( |
| 2174 |
id, |
| 2175 |
LookupExpression { |
| 2176 |
handle: ctx.expressions.append(expr, span), |
| 2177 |
type_id: result_type_id, |
| 2178 |
block_id, |
| 2179 |
}, |
| 2180 |
); |
| 2181 |
} |
| 2182 |
Op::Load => { |
| 2183 |
inst.expect_at_least(4)?; |
| 2184 |
|
| 2185 |
let result_type_id = self.next()?; |
| 2186 |
let result_id = self.next()?; |
| 2187 |
let pointer_id = self.next()?; |
| 2188 |
if inst.wc != 4 { |
| 2189 |
inst.expect(5)?; |
| 2190 |
let _memory_access = self.next()?; |
| 2191 |
} |
| 2192 |
|
| 2193 |
let base_lexp = self.lookup_expression.lookup(pointer_id)?; |
| 2194 |
let base_handle = get_expr_handle!(pointer_id, base_lexp); |
| 2195 |
let type_lookup = self.lookup_type.lookup(base_lexp.type_id)?; |
| 2196 |
let handle = match ctx.module.types[type_lookup.handle].inner { |
| 2197 |
crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => { |
| 2198 |
base_handle |
| 2199 |
} |
| 2200 |
_ => match self.lookup_load_override.get(&pointer_id) { |
| 2201 |
Some(&LookupLoadOverride::Loaded(handle)) => handle, |
| 2202 |
//Note: we aren't handling `LookupLoadOverride::Pending` properly here |
| 2203 |
_ => ctx.expressions.append( |
| 2204 |
crate::Expression::Load { |
| 2205 |
pointer: base_handle, |
| 2206 |
}, |
| 2207 |
span, |
| 2208 |
), |
| 2209 |
}, |
| 2210 |
}; |
| 2211 |
|
| 2212 |
self.lookup_expression.insert( |
| 2213 |
result_id, |
| 2214 |
LookupExpression { |
| 2215 |
handle, |
| 2216 |
type_id: result_type_id, |
| 2217 |
block_id, |
| 2218 |
}, |
| 2219 |
); |
| 2220 |
} |
| 2221 |
Op::Store => { |
| 2222 |
inst.expect_at_least(3)?; |
| 2223 |
|
| 2224 |
let pointer_id = self.next()?; |
| 2225 |
let value_id = self.next()?; |
| 2226 |
if inst.wc != 3 { |
| 2227 |
inst.expect(4)?; |
| 2228 |
let _memory_access = self.next()?; |
| 2229 |
} |
| 2230 |
let base_expr = self.lookup_expression.lookup(pointer_id)?; |
| 2231 |
let base_handle = get_expr_handle!(pointer_id, base_expr); |
| 2232 |
let value_expr = self.lookup_expression.lookup(value_id)?; |
| 2233 |
let value_handle = get_expr_handle!(value_id, value_expr); |
| 2234 |
|
| 2235 |
block.extend(emitter.finish(ctx.expressions)); |
| 2236 |
block.push( |
| 2237 |
crate::Statement::Store { |
| 2238 |
pointer: base_handle, |
| 2239 |
value: value_handle, |
| 2240 |
}, |
| 2241 |
span, |
| 2242 |
); |
| 2243 |
emitter.start(ctx.expressions); |
| 2244 |
} |
| 2245 |
// Arithmetic Instructions +, -, *, /, % |
| 2246 |
Op::SNegate | Op::FNegate => { |
| 2247 |
inst.expect(4)?; |
| 2248 |
self.parse_expr_unary_op_sign_adjusted( |
| 2249 |
ctx, |
| 2250 |
&mut emitter, |
| 2251 |
&mut block, |
| 2252 |
block_id, |
| 2253 |
body_idx, |
| 2254 |
crate::UnaryOperator::Negate, |
| 2255 |
)?; |
| 2256 |
} |
| 2257 |
Op::IAdd |
| 2258 |
| Op::ISub |
| 2259 |
| Op::IMul |
| 2260 |
| Op::BitwiseOr |
| 2261 |
| Op::BitwiseXor |
| 2262 |
| Op::BitwiseAnd |
| 2263 |
| Op::SDiv |
| 2264 |
| Op::SRem => { |
| 2265 |
inst.expect(5)?; |
| 2266 |
let operator = map_binary_operator(inst.op)?; |
| 2267 |
self.parse_expr_binary_op_sign_adjusted( |
| 2268 |
ctx, |
| 2269 |
&mut emitter, |
| 2270 |
&mut block, |
| 2271 |
block_id, |
| 2272 |
body_idx, |
| 2273 |
operator, |
| 2274 |
SignAnchor::Result, |
| 2275 |
)?; |
| 2276 |
} |
| 2277 |
Op::IEqual | Op::INotEqual => { |
| 2278 |
inst.expect(5)?; |
| 2279 |
let operator = map_binary_operator(inst.op)?; |
| 2280 |
self.parse_expr_binary_op_sign_adjusted( |
| 2281 |
ctx, |
| 2282 |
&mut emitter, |
| 2283 |
&mut block, |
| 2284 |
block_id, |
| 2285 |
body_idx, |
| 2286 |
operator, |
| 2287 |
SignAnchor::Operand, |
| 2288 |
)?; |
| 2289 |
} |
| 2290 |
Op::FAdd => { |
| 2291 |
inst.expect(5)?; |
| 2292 |
parse_expr_op!(crate::BinaryOperator::Add, BINARY)?; |
| 2293 |
} |
| 2294 |
Op::FSub => { |
| 2295 |
inst.expect(5)?; |
| 2296 |
parse_expr_op!(crate::BinaryOperator::Subtract, BINARY)?; |
| 2297 |
} |
| 2298 |
Op::FMul => { |
| 2299 |
inst.expect(5)?; |
| 2300 |
parse_expr_op!(crate::BinaryOperator::Multiply, BINARY)?; |
| 2301 |
} |
| 2302 |
Op::UDiv | Op::FDiv => { |
| 2303 |
inst.expect(5)?; |
| 2304 |
parse_expr_op!(crate::BinaryOperator::Divide, BINARY)?; |
| 2305 |
} |
| 2306 |
Op::UMod | Op::FRem => { |
| 2307 |
inst.expect(5)?; |
| 2308 |
parse_expr_op!(crate::BinaryOperator::Modulo, BINARY)?; |
| 2309 |
} |
| 2310 |
Op::SMod => { |
| 2311 |
inst.expect(5)?; |
| 2312 |
|
| 2313 |
// x - y * int(floor(float(x) / float(y))) |
| 2314 |
|
| 2315 |
let start = self.data_offset; |
| 2316 |
let result_type_id = self.next()?; |
| 2317 |
let result_id = self.next()?; |
| 2318 |
let p1_id = self.next()?; |
| 2319 |
let p2_id = self.next()?; |
| 2320 |
let span = self.span_from_with_op(start); |
| 2321 |
|
| 2322 |
let p1_lexp = self.lookup_expression.lookup(p1_id)?; |
| 2323 |
let left = self.get_expr_handle( |
| 2324 |
p1_id, |
| 2325 |
p1_lexp, |
| 2326 |
ctx, |
| 2327 |
&mut emitter, |
| 2328 |
&mut block, |
| 2329 |
body_idx, |
| 2330 |
); |
| 2331 |
let p2_lexp = self.lookup_expression.lookup(p2_id)?; |
| 2332 |
let right = self.get_expr_handle( |
| 2333 |
p2_id, |
| 2334 |
p2_lexp, |
| 2335 |
ctx, |
| 2336 |
&mut emitter, |
| 2337 |
&mut block, |
| 2338 |
body_idx, |
| 2339 |
); |
| 2340 |
|
| 2341 |
let result_ty = self.lookup_type.lookup(result_type_id)?; |
| 2342 |
let inner = &ctx.module.types[result_ty.handle].inner; |
| 2343 |
let kind = inner.scalar_kind().unwrap(); |
| 2344 |
let size = inner.size(ctx.gctx()) as u8; |
| 2345 |
|
| 2346 |
let left_cast = ctx.expressions.append( |
| 2347 |
crate::Expression::As { |
| 2348 |
expr: left, |
| 2349 |
kind: crate::ScalarKind::Float, |
| 2350 |
convert: Some(size), |
| 2351 |
}, |
| 2352 |
span, |
| 2353 |
); |
| 2354 |
let right_cast = ctx.expressions.append( |
| 2355 |
crate::Expression::As { |
| 2356 |
expr: right, |
| 2357 |
kind: crate::ScalarKind::Float, |
| 2358 |
convert: Some(size), |
| 2359 |
}, |
| 2360 |
span, |
| 2361 |
); |
| 2362 |
let div = ctx.expressions.append( |
| 2363 |
crate::Expression::Binary { |
| 2364 |
op: crate::BinaryOperator::Divide, |
| 2365 |
left: left_cast, |
| 2366 |
right: right_cast, |
| 2367 |
}, |
| 2368 |
span, |
| 2369 |
); |
| 2370 |
let floor = ctx.expressions.append( |
| 2371 |
crate::Expression::Math { |
| 2372 |
fun: crate::MathFunction::Floor, |
| 2373 |
arg: div, |
| 2374 |
arg1: None, |
| 2375 |
arg2: None, |
| 2376 |
arg3: None, |
| 2377 |
}, |
| 2378 |
span, |
| 2379 |
); |
| 2380 |
let cast = ctx.expressions.append( |
| 2381 |
crate::Expression::As { |
| 2382 |
expr: floor, |
| 2383 |
kind, |
| 2384 |
convert: Some(size), |
| 2385 |
}, |
| 2386 |
span, |
| 2387 |
); |
| 2388 |
let mult = ctx.expressions.append( |
| 2389 |
crate::Expression::Binary { |
| 2390 |
op: crate::BinaryOperator::Multiply, |
| 2391 |
left: cast, |
| 2392 |
right, |
| 2393 |
}, |
| 2394 |
span, |
| 2395 |
); |
| 2396 |
let sub = ctx.expressions.append( |
| 2397 |
crate::Expression::Binary { |
| 2398 |
op: crate::BinaryOperator::Subtract, |
| 2399 |
left, |
| 2400 |
right: mult, |
| 2401 |
}, |
| 2402 |
span, |
| 2403 |
); |
| 2404 |
self.lookup_expression.insert( |
| 2405 |
result_id, |
| 2406 |
LookupExpression { |
| 2407 |
handle: sub, |
| 2408 |
type_id: result_type_id, |
| 2409 |
block_id, |
| 2410 |
}, |
| 2411 |
); |
| 2412 |
} |
| 2413 |
Op::FMod => { |
| 2414 |
inst.expect(5)?; |
| 2415 |
|
| 2416 |
// x - y * floor(x / y) |
| 2417 |
|
| 2418 |
let start = self.data_offset; |
| 2419 |
let span = self.span_from_with_op(start); |
| 2420 |
|
| 2421 |
let result_type_id = self.next()?; |
| 2422 |
let result_id = self.next()?; |
| 2423 |
let p1_id = self.next()?; |
| 2424 |
let p2_id = self.next()?; |
| 2425 |
|
| 2426 |
let p1_lexp = self.lookup_expression.lookup(p1_id)?; |
| 2427 |
let left = self.get_expr_handle( |
| 2428 |
p1_id, |
| 2429 |
p1_lexp, |
| 2430 |
ctx, |
| 2431 |
&mut emitter, |
| 2432 |
&mut block, |
| 2433 |
body_idx, |
| 2434 |
); |
| 2435 |
let p2_lexp = self.lookup_expression.lookup(p2_id)?; |
| 2436 |
let right = self.get_expr_handle( |
| 2437 |
p2_id, |
| 2438 |
p2_lexp, |
| 2439 |
ctx, |
| 2440 |
&mut emitter, |
| 2441 |
&mut block, |
| 2442 |
body_idx, |
| 2443 |
); |
| 2444 |
|
| 2445 |
let div = ctx.expressions.append( |
| 2446 |
crate::Expression::Binary { |
| 2447 |
op: crate::BinaryOperator::Divide, |
| 2448 |
left, |
| 2449 |
right, |
| 2450 |
}, |
| 2451 |
span, |
| 2452 |
); |
| 2453 |
let floor = ctx.expressions.append( |
| 2454 |
crate::Expression::Math { |
| 2455 |
fun: crate::MathFunction::Floor, |
| 2456 |
arg: div, |
| 2457 |
arg1: None, |
| 2458 |
arg2: None, |
| 2459 |
arg3: None, |
| 2460 |
}, |
| 2461 |
span, |
| 2462 |
); |
| 2463 |
let mult = ctx.expressions.append( |
| 2464 |
crate::Expression::Binary { |
| 2465 |
op: crate::BinaryOperator::Multiply, |
| 2466 |
left: floor, |
| 2467 |
right, |
| 2468 |
}, |
| 2469 |
span, |
| 2470 |
); |
| 2471 |
let sub = ctx.expressions.append( |
| 2472 |
crate::Expression::Binary { |
| 2473 |
op: crate::BinaryOperator::Subtract, |
| 2474 |
left, |
| 2475 |
right: mult, |
| 2476 |
}, |
| 2477 |
span, |
| 2478 |
); |
| 2479 |
self.lookup_expression.insert( |
| 2480 |
result_id, |
| 2481 |
LookupExpression { |
| 2482 |
handle: sub, |
| 2483 |
type_id: result_type_id, |
| 2484 |
block_id, |
| 2485 |
}, |
| 2486 |
); |
| 2487 |
} |
| 2488 |
Op::VectorTimesScalar |
| 2489 |
| Op::VectorTimesMatrix |
| 2490 |
| Op::MatrixTimesScalar |
| 2491 |
| Op::MatrixTimesVector |
| 2492 |
| Op::MatrixTimesMatrix => { |
| 2493 |
inst.expect(5)?; |
| 2494 |
parse_expr_op!(crate::BinaryOperator::Multiply, BINARY)?; |
| 2495 |
} |
| 2496 |
Op::Transpose => { |
| 2497 |
inst.expect(4)?; |
| 2498 |
|
| 2499 |
let result_type_id = self.next()?; |
| 2500 |
let result_id = self.next()?; |
| 2501 |
let matrix_id = self.next()?; |
| 2502 |
let matrix_lexp = self.lookup_expression.lookup(matrix_id)?; |
| 2503 |
let matrix_handle = get_expr_handle!(matrix_id, matrix_lexp); |
| 2504 |
let expr = crate::Expression::Math { |
| 2505 |
fun: crate::MathFunction::Transpose, |
| 2506 |
arg: matrix_handle, |
| 2507 |
arg1: None, |
| 2508 |
arg2: None, |
| 2509 |
arg3: None, |
| 2510 |
}; |
| 2511 |
self.lookup_expression.insert( |
| 2512 |
result_id, |
| 2513 |
LookupExpression { |
| 2514 |
handle: ctx.expressions.append(expr, span), |
| 2515 |
type_id: result_type_id, |
| 2516 |
block_id, |
| 2517 |
}, |
| 2518 |
); |
| 2519 |
} |
| 2520 |
Op::Dot => { |
| 2521 |
inst.expect(5)?; |
| 2522 |
|
| 2523 |
let result_type_id = self.next()?; |
| 2524 |
let result_id = self.next()?; |
| 2525 |
let left_id = self.next()?; |
| 2526 |
let right_id = self.next()?; |
| 2527 |
let left_lexp = self.lookup_expression.lookup(left_id)?; |
| 2528 |
let left_handle = get_expr_handle!(left_id, left_lexp); |
| 2529 |
let right_lexp = self.lookup_expression.lookup(right_id)?; |
| 2530 |
let right_handle = get_expr_handle!(right_id, right_lexp); |
| 2531 |
let expr = crate::Expression::Math { |
| 2532 |
fun: crate::MathFunction::Dot, |
| 2533 |
arg: left_handle, |
| 2534 |
arg1: Some(right_handle), |
| 2535 |
arg2: None, |
| 2536 |
arg3: None, |
| 2537 |
}; |
| 2538 |
self.lookup_expression.insert( |
| 2539 |
result_id, |
| 2540 |
LookupExpression { |
| 2541 |
handle: ctx.expressions.append(expr, span), |
| 2542 |
type_id: result_type_id, |
| 2543 |
block_id, |
| 2544 |
}, |
| 2545 |
); |
| 2546 |
} |
| 2547 |
Op::BitFieldInsert => { |
| 2548 |
inst.expect(7)?; |
| 2549 |
|
| 2550 |
let start = self.data_offset; |
| 2551 |
let span = self.span_from_with_op(start); |
| 2552 |
|
| 2553 |
let result_type_id = self.next()?; |
| 2554 |
let result_id = self.next()?; |
| 2555 |
let base_id = self.next()?; |
| 2556 |
let insert_id = self.next()?; |
| 2557 |
let offset_id = self.next()?; |
| 2558 |
let count_id = self.next()?; |
| 2559 |
let base_lexp = self.lookup_expression.lookup(base_id)?; |
| 2560 |
let base_handle = get_expr_handle!(base_id, base_lexp); |
| 2561 |
let insert_lexp = self.lookup_expression.lookup(insert_id)?; |
| 2562 |
let insert_handle = get_expr_handle!(insert_id, insert_lexp); |
| 2563 |
let offset_lexp = self.lookup_expression.lookup(offset_id)?; |
| 2564 |
let offset_handle = get_expr_handle!(offset_id, offset_lexp); |
| 2565 |
let offset_lookup_ty = self.lookup_type.lookup(offset_lexp.type_id)?; |
| 2566 |
let count_lexp = self.lookup_expression.lookup(count_id)?; |
| 2567 |
let count_handle = get_expr_handle!(count_id, count_lexp); |
| 2568 |
let count_lookup_ty = self.lookup_type.lookup(count_lexp.type_id)?; |
| 2569 |
|
| 2570 |
let offset_kind = ctx.module.types[offset_lookup_ty.handle] |
| 2571 |
.inner |
| 2572 |
.scalar_kind() |
| 2573 |
.unwrap(); |
| 2574 |
let count_kind = ctx.module.types[count_lookup_ty.handle] |
| 2575 |
.inner |
| 2576 |
.scalar_kind() |
| 2577 |
.unwrap(); |
| 2578 |
|
| 2579 |
let offset_cast_handle = if offset_kind != crate::ScalarKind::Uint { |
| 2580 |
ctx.expressions.append( |
| 2581 |
crate::Expression::As { |
| 2582 |
expr: offset_handle, |
| 2583 |
kind: crate::ScalarKind::Uint, |
| 2584 |
convert: None, |
| 2585 |
}, |
| 2586 |
span, |
| 2587 |
) |
| 2588 |
} else { |
| 2589 |
offset_handle |
| 2590 |
}; |
| 2591 |
|
| 2592 |
let count_cast_handle = if count_kind != crate::ScalarKind::Uint { |
| 2593 |
ctx.expressions.append( |
| 2594 |
crate::Expression::As { |
| 2595 |
expr: count_handle, |
| 2596 |
kind: crate::ScalarKind::Uint, |
| 2597 |
convert: None, |
| 2598 |
}, |
| 2599 |
span, |
| 2600 |
) |
| 2601 |
} else { |
| 2602 |
count_handle |
| 2603 |
}; |
| 2604 |
|
| 2605 |
let expr = crate::Expression::Math { |
| 2606 |
fun: crate::MathFunction::InsertBits, |
| 2607 |
arg: base_handle, |
| 2608 |
arg1: Some(insert_handle), |
| 2609 |
arg2: Some(offset_cast_handle), |
| 2610 |
arg3: Some(count_cast_handle), |
| 2611 |
}; |
| 2612 |
self.lookup_expression.insert( |
| 2613 |
result_id, |
| 2614 |
LookupExpression { |
| 2615 |
handle: ctx.expressions.append(expr, span), |
| 2616 |
type_id: result_type_id, |
| 2617 |
block_id, |
| 2618 |
}, |
| 2619 |
); |
| 2620 |
} |
| 2621 |
Op::BitFieldSExtract | Op::BitFieldUExtract => { |
| 2622 |
inst.expect(6)?; |
| 2623 |
|
| 2624 |
let result_type_id = self.next()?; |
| 2625 |
let result_id = self.next()?; |
| 2626 |
let base_id = self.next()?; |
| 2627 |
let offset_id = self.next()?; |
| 2628 |
let count_id = self.next()?; |
| 2629 |
let base_lexp = self.lookup_expression.lookup(base_id)?; |
| 2630 |
let base_handle = get_expr_handle!(base_id, base_lexp); |
| 2631 |
let offset_lexp = self.lookup_expression.lookup(offset_id)?; |
| 2632 |
let offset_handle = get_expr_handle!(offset_id, offset_lexp); |
| 2633 |
let offset_lookup_ty = self.lookup_type.lookup(offset_lexp.type_id)?; |
| 2634 |
let count_lexp = self.lookup_expression.lookup(count_id)?; |
| 2635 |
let count_handle = get_expr_handle!(count_id, count_lexp); |
| 2636 |
let count_lookup_ty = self.lookup_type.lookup(count_lexp.type_id)?; |
| 2637 |
|
| 2638 |
let offset_kind = ctx.module.types[offset_lookup_ty.handle] |
| 2639 |
.inner |
| 2640 |
.scalar_kind() |
| 2641 |
.unwrap(); |
| 2642 |
let count_kind = ctx.module.types[count_lookup_ty.handle] |
| 2643 |
.inner |
| 2644 |
.scalar_kind() |
| 2645 |
.unwrap(); |
| 2646 |
|
| 2647 |
let offset_cast_handle = if offset_kind != crate::ScalarKind::Uint { |
| 2648 |
ctx.expressions.append( |
| 2649 |
crate::Expression::As { |
| 2650 |
expr: offset_handle, |
| 2651 |
kind: crate::ScalarKind::Uint, |
| 2652 |
convert: None, |
| 2653 |
}, |
| 2654 |
span, |
| 2655 |
) |
| 2656 |
} else { |
| 2657 |
offset_handle |
| 2658 |
}; |
| 2659 |
|
| 2660 |
let count_cast_handle = if count_kind != crate::ScalarKind::Uint { |
| 2661 |
ctx.expressions.append( |
| 2662 |
crate::Expression::As { |
| 2663 |
expr: count_handle, |
| 2664 |
kind: crate::ScalarKind::Uint, |
| 2665 |
convert: None, |
| 2666 |
}, |
| 2667 |
span, |
| 2668 |
) |
| 2669 |
} else { |
| 2670 |
count_handle |
| 2671 |
}; |
| 2672 |
|
| 2673 |
let expr = crate::Expression::Math { |
| 2674 |
fun: crate::MathFunction::ExtractBits, |
| 2675 |
arg: base_handle, |
| 2676 |
arg1: Some(offset_cast_handle), |
| 2677 |
arg2: Some(count_cast_handle), |
| 2678 |
arg3: None, |
| 2679 |
}; |
| 2680 |
self.lookup_expression.insert( |
| 2681 |
result_id, |
| 2682 |
LookupExpression { |
| 2683 |
handle: ctx.expressions.append(expr, span), |
| 2684 |
type_id: result_type_id, |
| 2685 |
block_id, |
| 2686 |
}, |
| 2687 |
); |
| 2688 |
} |
| 2689 |
Op::BitReverse | Op::BitCount => { |
| 2690 |
inst.expect(4)?; |
| 2691 |
|
| 2692 |
let result_type_id = self.next()?; |
| 2693 |
let result_id = self.next()?; |
| 2694 |
let base_id = self.next()?; |
| 2695 |
let base_lexp = self.lookup_expression.lookup(base_id)?; |
| 2696 |
let base_handle = get_expr_handle!(base_id, base_lexp); |
| 2697 |
let expr = crate::Expression::Math { |
| 2698 |
fun: match inst.op { |
| 2699 |
Op::BitReverse => crate::MathFunction::ReverseBits, |
| 2700 |
Op::BitCount => crate::MathFunction::CountOneBits, |
| 2701 |
_ => unreachable!(), |
| 2702 |
}, |
| 2703 |
arg: base_handle, |
| 2704 |
arg1: None, |
| 2705 |
arg2: None, |
| 2706 |
arg3: None, |
| 2707 |
}; |
| 2708 |
self.lookup_expression.insert( |
| 2709 |
result_id, |
| 2710 |
LookupExpression { |
| 2711 |
handle: ctx.expressions.append(expr, span), |
| 2712 |
type_id: result_type_id, |
| 2713 |
block_id, |
| 2714 |
}, |
| 2715 |
); |
| 2716 |
} |
| 2717 |
Op::OuterProduct => { |
| 2718 |
inst.expect(5)?; |
| 2719 |
|
| 2720 |
let result_type_id = self.next()?; |
| 2721 |
let result_id = self.next()?; |
| 2722 |
let left_id = self.next()?; |
| 2723 |
let right_id = self.next()?; |
| 2724 |
let left_lexp = self.lookup_expression.lookup(left_id)?; |
| 2725 |
let left_handle = get_expr_handle!(left_id, left_lexp); |
| 2726 |
let right_lexp = self.lookup_expression.lookup(right_id)?; |
| 2727 |
let right_handle = get_expr_handle!(right_id, right_lexp); |
| 2728 |
let expr = crate::Expression::Math { |
| 2729 |
fun: crate::MathFunction::Outer, |
| 2730 |
arg: left_handle, |
| 2731 |
arg1: Some(right_handle), |
| 2732 |
arg2: None, |
| 2733 |
arg3: None, |
| 2734 |
}; |
| 2735 |
self.lookup_expression.insert( |
| 2736 |
result_id, |
| 2737 |
LookupExpression { |
| 2738 |
handle: ctx.expressions.append(expr, span), |
| 2739 |
type_id: result_type_id, |
| 2740 |
block_id, |
| 2741 |
}, |
| 2742 |
); |
| 2743 |
} |
| 2744 |
// Bitwise instructions |
| 2745 |
Op::Not => { |
| 2746 |
inst.expect(4)?; |
| 2747 |
self.parse_expr_unary_op_sign_adjusted( |
| 2748 |
ctx, |
| 2749 |
&mut emitter, |
| 2750 |
&mut block, |
| 2751 |
block_id, |
| 2752 |
body_idx, |
| 2753 |
crate::UnaryOperator::BitwiseNot, |
| 2754 |
)?; |
| 2755 |
} |
| 2756 |
Op::ShiftRightLogical => { |
| 2757 |
inst.expect(5)?; |
| 2758 |
//TODO: convert input and result to unsigned |
| 2759 |
parse_expr_op!(crate::BinaryOperator::ShiftRight, SHIFT)?; |
| 2760 |
} |
| 2761 |
Op::ShiftRightArithmetic => { |
| 2762 |
inst.expect(5)?; |
| 2763 |
//TODO: convert input and result to signed |
| 2764 |
parse_expr_op!(crate::BinaryOperator::ShiftRight, SHIFT)?; |
| 2765 |
} |
| 2766 |
Op::ShiftLeftLogical => { |
| 2767 |
inst.expect(5)?; |
| 2768 |
parse_expr_op!(crate::BinaryOperator::ShiftLeft, SHIFT)?; |
| 2769 |
} |
| 2770 |
// Sampling |
| 2771 |
Op::Image => { |
| 2772 |
inst.expect(4)?; |
| 2773 |
self.parse_image_uncouple(block_id)?; |
| 2774 |
} |
| 2775 |
Op::SampledImage => { |
| 2776 |
inst.expect(5)?; |
| 2777 |
self.parse_image_couple()?; |
| 2778 |
} |
| 2779 |
Op::ImageWrite => { |
| 2780 |
let extra = inst.expect_at_least(4)?; |
| 2781 |
let stmt = |
| 2782 |
self.parse_image_write(extra, ctx, &mut emitter, &mut block, body_idx)?; |
| 2783 |
block.extend(emitter.finish(ctx.expressions)); |
| 2784 |
block.push(stmt, span); |
| 2785 |
emitter.start(ctx.expressions); |
| 2786 |
} |
| 2787 |
Op::ImageFetch | Op::ImageRead => { |
| 2788 |
let extra = inst.expect_at_least(5)?; |
| 2789 |
self.parse_image_load( |
| 2790 |
extra, |
| 2791 |
ctx, |
| 2792 |
&mut emitter, |
| 2793 |
&mut block, |
| 2794 |
block_id, |
| 2795 |
body_idx, |
| 2796 |
)?; |
| 2797 |
} |
| 2798 |
Op::ImageSampleImplicitLod | Op::ImageSampleExplicitLod => { |
| 2799 |
let extra = inst.expect_at_least(5)?; |
| 2800 |
let options = image::SamplingOptions { |
| 2801 |
compare: false, |
| 2802 |
project: false, |
| 2803 |
}; |
| 2804 |
self.parse_image_sample( |
| 2805 |
extra, |
| 2806 |
options, |
| 2807 |
ctx, |
| 2808 |
&mut emitter, |
| 2809 |
&mut block, |
| 2810 |
block_id, |
| 2811 |
body_idx, |
| 2812 |
)?; |
| 2813 |
} |
| 2814 |
Op::ImageSampleProjImplicitLod | Op::ImageSampleProjExplicitLod => { |
| 2815 |
let extra = inst.expect_at_least(5)?; |
| 2816 |
let options = image::SamplingOptions { |
| 2817 |
compare: false, |
| 2818 |
project: true, |
| 2819 |
}; |
| 2820 |
self.parse_image_sample( |
| 2821 |
extra, |
| 2822 |
options, |
| 2823 |
ctx, |
| 2824 |
&mut emitter, |
| 2825 |
&mut block, |
| 2826 |
block_id, |
| 2827 |
body_idx, |
| 2828 |
)?; |
| 2829 |
} |
| 2830 |
Op::ImageSampleDrefImplicitLod | Op::ImageSampleDrefExplicitLod => { |
| 2831 |
let extra = inst.expect_at_least(6)?; |
| 2832 |
let options = image::SamplingOptions { |
| 2833 |
compare: true, |
| 2834 |
project: false, |
| 2835 |
}; |
| 2836 |
self.parse_image_sample( |
| 2837 |
extra, |
| 2838 |
options, |
| 2839 |
ctx, |
| 2840 |
&mut emitter, |
| 2841 |
&mut block, |
| 2842 |
block_id, |
| 2843 |
body_idx, |
| 2844 |
)?; |
| 2845 |
} |
| 2846 |
Op::ImageSampleProjDrefImplicitLod | Op::ImageSampleProjDrefExplicitLod => { |
| 2847 |
let extra = inst.expect_at_least(6)?; |
| 2848 |
let options = image::SamplingOptions { |
| 2849 |
compare: true, |
| 2850 |
project: true, |
| 2851 |
}; |
| 2852 |
self.parse_image_sample( |
| 2853 |
extra, |
| 2854 |
options, |
| 2855 |
ctx, |
| 2856 |
&mut emitter, |
| 2857 |
&mut block, |
| 2858 |
block_id, |
| 2859 |
body_idx, |
| 2860 |
)?; |
| 2861 |
} |
| 2862 |
Op::ImageQuerySize => { |
| 2863 |
inst.expect(4)?; |
| 2864 |
self.parse_image_query_size( |
| 2865 |
false, |
| 2866 |
ctx, |
| 2867 |
&mut emitter, |
| 2868 |
&mut block, |
| 2869 |
block_id, |
| 2870 |
body_idx, |
| 2871 |
)?; |
| 2872 |
} |
| 2873 |
Op::ImageQuerySizeLod => { |
| 2874 |
inst.expect(5)?; |
| 2875 |
self.parse_image_query_size( |
| 2876 |
true, |
| 2877 |
ctx, |
| 2878 |
&mut emitter, |
| 2879 |
&mut block, |
| 2880 |
block_id, |
| 2881 |
body_idx, |
| 2882 |
)?; |
| 2883 |
} |
| 2884 |
Op::ImageQueryLevels => { |
| 2885 |
inst.expect(4)?; |
| 2886 |
self.parse_image_query_other(crate::ImageQuery::NumLevels, ctx, block_id)?; |
| 2887 |
} |
| 2888 |
Op::ImageQuerySamples => { |
| 2889 |
inst.expect(4)?; |
| 2890 |
self.parse_image_query_other(crate::ImageQuery::NumSamples, ctx, block_id)?; |
| 2891 |
} |
| 2892 |
// other ops |
| 2893 |
Op::Select => { |
| 2894 |
inst.expect(6)?; |
| 2895 |
let result_type_id = self.next()?; |
| 2896 |
let result_id = self.next()?; |
| 2897 |
let condition = self.next()?; |
| 2898 |
let o1_id = self.next()?; |
| 2899 |
let o2_id = self.next()?; |
| 2900 |
|
| 2901 |
let cond_lexp = self.lookup_expression.lookup(condition)?; |
| 2902 |
let cond_handle = get_expr_handle!(condition, cond_lexp); |
| 2903 |
let o1_lexp = self.lookup_expression.lookup(o1_id)?; |
| 2904 |
let o1_handle = get_expr_handle!(o1_id, o1_lexp); |
| 2905 |
let o2_lexp = self.lookup_expression.lookup(o2_id)?; |
| 2906 |
let o2_handle = get_expr_handle!(o2_id, o2_lexp); |
| 2907 |
|
| 2908 |
let expr = crate::Expression::Select { |
| 2909 |
condition: cond_handle, |
| 2910 |
accept: o1_handle, |
| 2911 |
reject: o2_handle, |
| 2912 |
}; |
| 2913 |
self.lookup_expression.insert( |
| 2914 |
result_id, |
| 2915 |
LookupExpression { |
| 2916 |
handle: ctx.expressions.append(expr, span), |
| 2917 |
type_id: result_type_id, |
| 2918 |
block_id, |
| 2919 |
}, |
| 2920 |
); |
| 2921 |
} |
| 2922 |
Op::VectorShuffle => { |
| 2923 |
inst.expect_at_least(5)?; |
| 2924 |
let result_type_id = self.next()?; |
| 2925 |
let result_id = self.next()?; |
| 2926 |
let v1_id = self.next()?; |
| 2927 |
let v2_id = self.next()?; |
| 2928 |
|
| 2929 |
let v1_lexp = self.lookup_expression.lookup(v1_id)?; |
| 2930 |
let v1_lty = self.lookup_type.lookup(v1_lexp.type_id)?; |
| 2931 |
let v1_handle = get_expr_handle!(v1_id, v1_lexp); |
| 2932 |
let n1 = match ctx.module.types[v1_lty.handle].inner { |
| 2933 |
crate::TypeInner::Vector { size, .. } => size as u32, |
| 2934 |
_ => return Err(Error::InvalidInnerType(v1_lexp.type_id)), |
| 2935 |
}; |
| 2936 |
let v2_lexp = self.lookup_expression.lookup(v2_id)?; |
| 2937 |
let v2_lty = self.lookup_type.lookup(v2_lexp.type_id)?; |
| 2938 |
let v2_handle = get_expr_handle!(v2_id, v2_lexp); |
| 2939 |
let n2 = match ctx.module.types[v2_lty.handle].inner { |
| 2940 |
crate::TypeInner::Vector { size, .. } => size as u32, |
| 2941 |
_ => return Err(Error::InvalidInnerType(v2_lexp.type_id)), |
| 2942 |
}; |
| 2943 |
|
| 2944 |
self.temp_bytes.clear(); |
| 2945 |
let mut max_component = 0; |
| 2946 |
for _ in 5..inst.wc as usize { |
| 2947 |
let mut index = self.next()?; |
| 2948 |
if index == u32::MAX { |
| 2949 |
// treat Undefined as X |
| 2950 |
index = 0; |
| 2951 |
} |
| 2952 |
max_component = max_component.max(index); |
| 2953 |
self.temp_bytes.push(index as u8); |
| 2954 |
} |
| 2955 |
|
| 2956 |
// Check for swizzle first. |
| 2957 |
let expr = if max_component < n1 { |
| 2958 |
use crate::SwizzleComponent as Sc; |
| 2959 |
let size = match self.temp_bytes.len() { |
| 2960 |
2 => crate::VectorSize::Bi, |
| 2961 |
3 => crate::VectorSize::Tri, |
| 2962 |
_ => crate::VectorSize::Quad, |
| 2963 |
}; |
| 2964 |
let mut pattern = [Sc::X; 4]; |
| 2965 |
for (pat, index) in pattern.iter_mut().zip(self.temp_bytes.drain(..)) { |
| 2966 |
*pat = match index { |
| 2967 |
0 => Sc::X, |
| 2968 |
1 => Sc::Y, |
| 2969 |
2 => Sc::Z, |
| 2970 |
_ => Sc::W, |
| 2971 |
}; |
| 2972 |
} |
| 2973 |
crate::Expression::Swizzle { |
| 2974 |
size, |
| 2975 |
vector: v1_handle, |
| 2976 |
pattern, |
| 2977 |
} |
| 2978 |
} else { |
| 2979 |
// Fall back to access + compose |
| 2980 |
let mut components = Vec::with_capacity(self.temp_bytes.len()); |
| 2981 |
for index in self.temp_bytes.drain(..).map(|i| i as u32) { |
| 2982 |
let expr = if index < n1 { |
| 2983 |
crate::Expression::AccessIndex { |
| 2984 |
base: v1_handle, |
| 2985 |
index, |
| 2986 |
} |
| 2987 |
} else if index < n1 + n2 { |
| 2988 |
crate::Expression::AccessIndex { |
| 2989 |
base: v2_handle, |
| 2990 |
index: index - n1, |
| 2991 |
} |
| 2992 |
} else { |
| 2993 |
return Err(Error::InvalidAccessIndex(index)); |
| 2994 |
}; |
| 2995 |
components.push(ctx.expressions.append(expr, span)); |
| 2996 |
} |
| 2997 |
crate::Expression::Compose { |
| 2998 |
ty: self.lookup_type.lookup(result_type_id)?.handle, |
| 2999 |
components, |
| 3000 |
} |
| 3001 |
}; |
| 3002 |
|
| 3003 |
self.lookup_expression.insert( |
| 3004 |
result_id, |
| 3005 |
LookupExpression { |
| 3006 |
handle: ctx.expressions.append(expr, span), |
| 3007 |
type_id: result_type_id, |
| 3008 |
block_id, |
| 3009 |
}, |
| 3010 |
); |
| 3011 |
} |
| 3012 |
Op::Bitcast |
| 3013 |
| Op::ConvertSToF |
| 3014 |
| Op::ConvertUToF |
| 3015 |
| Op::ConvertFToU |
| 3016 |
| Op::ConvertFToS |
| 3017 |
| Op::FConvert |
| 3018 |
| Op::UConvert |
| 3019 |
| Op::SConvert => { |
| 3020 |
inst.expect(4)?; |
| 3021 |
let result_type_id = self.next()?; |
| 3022 |
let result_id = self.next()?; |
| 3023 |
let value_id = self.next()?; |
| 3024 |
|
| 3025 |
let value_lexp = self.lookup_expression.lookup(value_id)?; |
| 3026 |
let ty_lookup = self.lookup_type.lookup(result_type_id)?; |
| 3027 |
let scalar = match ctx.module.types[ty_lookup.handle].inner { |
| 3028 |
crate::TypeInner::Scalar(scalar) |
| 3029 |
| crate::TypeInner::Vector { scalar, .. } |
| 3030 |
| crate::TypeInner::Matrix { scalar, .. } => scalar, |
| 3031 |
_ => return Err(Error::InvalidAsType(ty_lookup.handle)), |
| 3032 |
}; |
| 3033 |
|
| 3034 |
let expr = crate::Expression::As { |
| 3035 |
expr: get_expr_handle!(value_id, value_lexp), |
| 3036 |
kind: scalar.kind, |
| 3037 |
convert: if scalar.kind == crate::ScalarKind::Bool { |
| 3038 |
Some(crate::BOOL_WIDTH) |
| 3039 |
} else if inst.op == Op::Bitcast { |
| 3040 |
None |
| 3041 |
} else { |
| 3042 |
Some(scalar.width) |
| 3043 |
}, |
| 3044 |
}; |
| 3045 |
self.lookup_expression.insert( |
| 3046 |
result_id, |
| 3047 |
LookupExpression { |
| 3048 |
handle: ctx.expressions.append(expr, span), |
| 3049 |
type_id: result_type_id, |
| 3050 |
block_id, |
| 3051 |
}, |
| 3052 |
); |
| 3053 |
} |
| 3054 |
Op::FunctionCall => { |
| 3055 |
inst.expect_at_least(4)?; |
| 3056 |
|
| 3057 |
let result_type_id = self.next()?; |
| 3058 |
let result_id = self.next()?; |
| 3059 |
let func_id = self.next()?; |
| 3060 |
|
| 3061 |
let mut arguments = Vec::with_capacity(inst.wc as usize - 4); |
| 3062 |
for _ in 0..arguments.capacity() { |
| 3063 |
let arg_id = self.next()?; |
| 3064 |
let lexp = self.lookup_expression.lookup(arg_id)?; |
| 3065 |
arguments.push(get_expr_handle!(arg_id, lexp)); |
| 3066 |
} |
| 3067 |
|
| 3068 |
block.extend(emitter.finish(ctx.expressions)); |
| 3069 |
|
| 3070 |
// We just need an unique handle here, nothing more. |
| 3071 |
let function = self.add_call(ctx.function_id, func_id); |
| 3072 |
|
| 3073 |
let result = if self.lookup_void_type == Some(result_type_id) { |
| 3074 |
None |
| 3075 |
} else { |
| 3076 |
let expr_handle = ctx |
| 3077 |
.expressions |
| 3078 |
.append(crate::Expression::CallResult(function), span); |
| 3079 |
self.lookup_expression.insert( |
| 3080 |
result_id, |
| 3081 |
LookupExpression { |
| 3082 |
handle: expr_handle, |
| 3083 |
type_id: result_type_id, |
| 3084 |
block_id, |
| 3085 |
}, |
| 3086 |
); |
| 3087 |
Some(expr_handle) |
| 3088 |
}; |
| 3089 |
block.push( |
| 3090 |
crate::Statement::Call { |
| 3091 |
function, |
| 3092 |
arguments, |
| 3093 |
result, |
| 3094 |
}, |
| 3095 |
span, |
| 3096 |
); |
| 3097 |
emitter.start(ctx.expressions); |
| 3098 |
} |
| 3099 |
Op::ExtInst => { |
| 3100 |
use crate::MathFunction as Mf; |
| 3101 |
use spirv::GLOp as Glo; |
| 3102 |
|
| 3103 |
let base_wc = 5; |
| 3104 |
inst.expect_at_least(base_wc)?; |
| 3105 |
|
| 3106 |
let result_type_id = self.next()?; |
| 3107 |
let result_id = self.next()?; |
| 3108 |
let set_id = self.next()?; |
| 3109 |
if Some(set_id) != self.ext_glsl_id { |
| 3110 |
return Err(Error::UnsupportedExtInstSet(set_id)); |
| 3111 |
} |
| 3112 |
let inst_id = self.next()?; |
| 3113 |
let gl_op = Glo::from_u32(inst_id).ok_or(Error::UnsupportedExtInst(inst_id))?; |
| 3114 |
|
| 3115 |
let fun = match gl_op { |
| 3116 |
Glo::Round => Mf::Round, |
| 3117 |
Glo::RoundEven => Mf::Round, |
| 3118 |
Glo::Trunc => Mf::Trunc, |
| 3119 |
Glo::FAbs | Glo::SAbs => Mf::Abs, |
| 3120 |
Glo::FSign | Glo::SSign => Mf::Sign, |
| 3121 |
Glo::Floor => Mf::Floor, |
| 3122 |
Glo::Ceil => Mf::Ceil, |
| 3123 |
Glo::Fract => Mf::Fract, |
| 3124 |
Glo::Sin => Mf::Sin, |
| 3125 |
Glo::Cos => Mf::Cos, |
| 3126 |
Glo::Tan => Mf::Tan, |
| 3127 |
Glo::Asin => Mf::Asin, |
| 3128 |
Glo::Acos => Mf::Acos, |
| 3129 |
Glo::Atan => Mf::Atan, |
| 3130 |
Glo::Sinh => Mf::Sinh, |
| 3131 |
Glo::Cosh => Mf::Cosh, |
| 3132 |
Glo::Tanh => Mf::Tanh, |
| 3133 |
Glo::Atan2 => Mf::Atan2, |
| 3134 |
Glo::Asinh => Mf::Asinh, |
| 3135 |
Glo::Acosh => Mf::Acosh, |
| 3136 |
Glo::Atanh => Mf::Atanh, |
| 3137 |
Glo::Radians => Mf::Radians, |
| 3138 |
Glo::Degrees => Mf::Degrees, |
| 3139 |
Glo::Pow => Mf::Pow, |
| 3140 |
Glo::Exp => Mf::Exp, |
| 3141 |
Glo::Log => Mf::Log, |
| 3142 |
Glo::Exp2 => Mf::Exp2, |
| 3143 |
Glo::Log2 => Mf::Log2, |
| 3144 |
Glo::Sqrt => Mf::Sqrt, |
| 3145 |
Glo::InverseSqrt => Mf::InverseSqrt, |
| 3146 |
Glo::MatrixInverse => Mf::Inverse, |
| 3147 |
Glo::Determinant => Mf::Determinant, |
| 3148 |
Glo::ModfStruct => Mf::Modf, |
| 3149 |
Glo::FMin | Glo::UMin | Glo::SMin | Glo::NMin => Mf::Min, |
| 3150 |
Glo::FMax | Glo::UMax | Glo::SMax | Glo::NMax => Mf::Max, |
| 3151 |
Glo::FClamp | Glo::UClamp | Glo::SClamp | Glo::NClamp => Mf::Clamp, |
| 3152 |
Glo::FMix => Mf::Mix, |
| 3153 |
Glo::Step => Mf::Step, |
| 3154 |
Glo::SmoothStep => Mf::SmoothStep, |
| 3155 |
Glo::Fma => Mf::Fma, |
| 3156 |
Glo::FrexpStruct => Mf::Frexp, |
| 3157 |
Glo::Ldexp => Mf::Ldexp, |
| 3158 |
Glo::Length => Mf::Length, |
| 3159 |
Glo::Distance => Mf::Distance, |
| 3160 |
Glo::Cross => Mf::Cross, |
| 3161 |
Glo::Normalize => Mf::Normalize, |
| 3162 |
Glo::FaceForward => Mf::FaceForward, |
| 3163 |
Glo::Reflect => Mf::Reflect, |
| 3164 |
Glo::Refract => Mf::Refract, |
| 3165 |
Glo::PackUnorm4x8 => Mf::Pack4x8unorm, |
| 3166 |
Glo::PackSnorm4x8 => Mf::Pack4x8snorm, |
| 3167 |
Glo::PackHalf2x16 => Mf::Pack2x16float, |
| 3168 |
Glo::PackUnorm2x16 => Mf::Pack2x16unorm, |
| 3169 |
Glo::PackSnorm2x16 => Mf::Pack2x16snorm, |
| 3170 |
Glo::UnpackUnorm4x8 => Mf::Unpack4x8unorm, |
| 3171 |
Glo::UnpackSnorm4x8 => Mf::Unpack4x8snorm, |
| 3172 |
Glo::UnpackHalf2x16 => Mf::Unpack2x16float, |
| 3173 |
Glo::UnpackUnorm2x16 => Mf::Unpack2x16unorm, |
| 3174 |
Glo::UnpackSnorm2x16 => Mf::Unpack2x16snorm, |
| 3175 |
Glo::FindILsb => Mf::FirstTrailingBit, |
| 3176 |
Glo::FindUMsb | Glo::FindSMsb => Mf::FirstLeadingBit, |
| 3177 |
// TODO: https://github.com/gfx-rs/naga/issues/2526 |
| 3178 |
Glo::Modf | Glo::Frexp => return Err(Error::UnsupportedExtInst(inst_id)), |
| 3179 |
Glo::IMix |
| 3180 |
| Glo::PackDouble2x32 |
| 3181 |
| Glo::UnpackDouble2x32 |
| 3182 |
| Glo::InterpolateAtCentroid |
| 3183 |
| Glo::InterpolateAtSample |
| 3184 |
| Glo::InterpolateAtOffset => { |
| 3185 |
return Err(Error::UnsupportedExtInst(inst_id)) |
| 3186 |
} |
| 3187 |
}; |
| 3188 |
|
| 3189 |
let arg_count = fun.argument_count(); |
| 3190 |
inst.expect(base_wc + arg_count as u16)?; |
| 3191 |
let arg = { |
| 3192 |
let arg_id = self.next()?; |
| 3193 |
let lexp = self.lookup_expression.lookup(arg_id)?; |
| 3194 |
get_expr_handle!(arg_id, lexp) |
| 3195 |
}; |
| 3196 |
let arg1 = if arg_count > 1 { |
| 3197 |
let arg_id = self.next()?; |
| 3198 |
let lexp = self.lookup_expression.lookup(arg_id)?; |
| 3199 |
Some(get_expr_handle!(arg_id, lexp)) |
| 3200 |
} else { |
| 3201 |
None |
| 3202 |
}; |
| 3203 |
let arg2 = if arg_count > 2 { |
| 3204 |
let arg_id = self.next()?; |
| 3205 |
let lexp = self.lookup_expression.lookup(arg_id)?; |
| 3206 |
Some(get_expr_handle!(arg_id, lexp)) |
| 3207 |
} else { |
| 3208 |
None |
| 3209 |
}; |
| 3210 |
let arg3 = if arg_count > 3 { |
| 3211 |
let arg_id = self.next()?; |
| 3212 |
let lexp = self.lookup_expression.lookup(arg_id)?; |
| 3213 |
Some(get_expr_handle!(arg_id, lexp)) |
| 3214 |
} else { |
| 3215 |
None |
| 3216 |
}; |
| 3217 |
|
| 3218 |
let expr = crate::Expression::Math { |
| 3219 |
fun, |
| 3220 |
arg, |
| 3221 |
arg1, |
| 3222 |
arg2, |
| 3223 |
arg3, |
| 3224 |
}; |
| 3225 |
self.lookup_expression.insert( |
| 3226 |
result_id, |
| 3227 |
LookupExpression { |
| 3228 |
handle: ctx.expressions.append(expr, span), |
| 3229 |
type_id: result_type_id, |
| 3230 |
block_id, |
| 3231 |
}, |
| 3232 |
); |
| 3233 |
} |
| 3234 |
// Relational and Logical Instructions |
| 3235 |
Op::LogicalNot => { |
| 3236 |
inst.expect(4)?; |
| 3237 |
parse_expr_op!(crate::UnaryOperator::LogicalNot, UNARY)?; |
| 3238 |
} |
| 3239 |
Op::LogicalOr => { |
| 3240 |
inst.expect(5)?; |
| 3241 |
parse_expr_op!(crate::BinaryOperator::LogicalOr, BINARY)?; |
| 3242 |
} |
| 3243 |
Op::LogicalAnd => { |
| 3244 |
inst.expect(5)?; |
| 3245 |
parse_expr_op!(crate::BinaryOperator::LogicalAnd, BINARY)?; |
| 3246 |
} |
| 3247 |
Op::SGreaterThan | Op::SGreaterThanEqual | Op::SLessThan | Op::SLessThanEqual => { |
| 3248 |
inst.expect(5)?; |
| 3249 |
self.parse_expr_int_comparison( |
| 3250 |
ctx, |
| 3251 |
&mut emitter, |
| 3252 |
&mut block, |
| 3253 |
block_id, |
| 3254 |
body_idx, |
| 3255 |
map_binary_operator(inst.op)?, |
| 3256 |
crate::ScalarKind::Sint, |
| 3257 |
)?; |
| 3258 |
} |
| 3259 |
Op::UGreaterThan | Op::UGreaterThanEqual | Op::ULessThan | Op::ULessThanEqual => { |
| 3260 |
inst.expect(5)?; |
| 3261 |
self.parse_expr_int_comparison( |
| 3262 |
ctx, |
| 3263 |
&mut emitter, |
| 3264 |
&mut block, |
| 3265 |
block_id, |
| 3266 |
body_idx, |
| 3267 |
map_binary_operator(inst.op)?, |
| 3268 |
crate::ScalarKind::Uint, |
| 3269 |
)?; |
| 3270 |
} |
| 3271 |
Op::FOrdEqual |
| 3272 |
| Op::FUnordEqual |
| 3273 |
| Op::FOrdNotEqual |
| 3274 |
| Op::FUnordNotEqual |
| 3275 |
| Op::FOrdLessThan |
| 3276 |
| Op::FUnordLessThan |
| 3277 |
| Op::FOrdGreaterThan |
| 3278 |
| Op::FUnordGreaterThan |
| 3279 |
| Op::FOrdLessThanEqual |
| 3280 |
| Op::FUnordLessThanEqual |
| 3281 |
| Op::FOrdGreaterThanEqual |
| 3282 |
| Op::FUnordGreaterThanEqual |
| 3283 |
| Op::LogicalEqual |
| 3284 |
| Op::LogicalNotEqual => { |
| 3285 |
inst.expect(5)?; |
| 3286 |
let operator = map_binary_operator(inst.op)?; |
| 3287 |
parse_expr_op!(operator, BINARY)?; |
| 3288 |
} |
| 3289 |
Op::Any | Op::All | Op::IsNan | Op::IsInf | Op::IsFinite | Op::IsNormal => { |
| 3290 |
inst.expect(4)?; |
| 3291 |
let result_type_id = self.next()?; |
| 3292 |
let result_id = self.next()?; |
| 3293 |
let arg_id = self.next()?; |
| 3294 |
|
| 3295 |
let arg_lexp = self.lookup_expression.lookup(arg_id)?; |
| 3296 |
let arg_handle = get_expr_handle!(arg_id, arg_lexp); |
| 3297 |
|
| 3298 |
let expr = crate::Expression::Relational { |
| 3299 |
fun: map_relational_fun(inst.op)?, |
| 3300 |
argument: arg_handle, |
| 3301 |
}; |
| 3302 |
self.lookup_expression.insert( |
| 3303 |
result_id, |
| 3304 |
LookupExpression { |
| 3305 |
handle: ctx.expressions.append(expr, span), |
| 3306 |
type_id: result_type_id, |
| 3307 |
block_id, |
| 3308 |
}, |
| 3309 |
); |
| 3310 |
} |
| 3311 |
Op::Kill => { |
| 3312 |
inst.expect(1)?; |
| 3313 |
break Some(crate::Statement::Kill); |
| 3314 |
} |
| 3315 |
Op::Unreachable => { |
| 3316 |
inst.expect(1)?; |
| 3317 |
break None; |
| 3318 |
} |
| 3319 |
Op::Return => { |
| 3320 |
inst.expect(1)?; |
| 3321 |
break Some(crate::Statement::Return { value: None }); |
| 3322 |
} |
| 3323 |
Op::ReturnValue => { |
| 3324 |
inst.expect(2)?; |
| 3325 |
let value_id = self.next()?; |
| 3326 |
let value_lexp = self.lookup_expression.lookup(value_id)?; |
| 3327 |
let value_handle = get_expr_handle!(value_id, value_lexp); |
| 3328 |
break Some(crate::Statement::Return { |
| 3329 |
value: Some(value_handle), |
| 3330 |
}); |
| 3331 |
} |
| 3332 |
Op::Branch => { |
| 3333 |
inst.expect(2)?; |
| 3334 |
let target_id = self.next()?; |
| 3335 |
|
| 3336 |
// If this is a branch to a merge or continue block, then |
| 3337 |
// that ends the current body. |
| 3338 |
// |
| 3339 |
// Why can we count on finding an entry here when it's |
| 3340 |
// needed? SPIR-V requires dominators to appear before |
| 3341 |
// blocks they dominate, so we will have visited a |
| 3342 |
// structured control construct's header block before |
| 3343 |
// anything that could exit it. |
| 3344 |
if let Some(info) = ctx.mergers.get(&target_id) { |
| 3345 |
block.extend(emitter.finish(ctx.expressions)); |
| 3346 |
ctx.blocks.insert(block_id, block); |
| 3347 |
let body = &mut ctx.bodies[body_idx]; |
| 3348 |
body.data.push(BodyFragment::BlockId(block_id)); |
| 3349 |
|
| 3350 |
merger(body, info); |
| 3351 |
|
| 3352 |
return Ok(()); |
| 3353 |
} |
| 3354 |
|
| 3355 |
// If `target_id` has no entry in `ctx.body_for_label`, then |
| 3356 |
// this must be the only branch to it: |
| 3357 |
// |
| 3358 |
// - We've already established that it's not anybody's merge |
| 3359 |
// block. |
| 3360 |
// |
| 3361 |
// - It can't be a switch case. Only switch header blocks |
| 3362 |
// and other switch cases can branch to a switch case. |
| 3363 |
// Switch header blocks must dominate all their cases, so |
| 3364 |
// they must appear in the file before them, and when we |
| 3365 |
// see `Op::Switch` we populate `ctx.body_for_label` for |
| 3366 |
// every switch case. |
| 3367 |
// |
| 3368 |
// Thus, `target_id` must be a simple extension of the |
| 3369 |
// current block, which we dominate, so we know we'll |
| 3370 |
// encounter it later in the file. |
| 3371 |
ctx.body_for_label.entry(target_id).or_insert(body_idx); |
| 3372 |
|
| 3373 |
break None; |
| 3374 |
} |
| 3375 |
Op::BranchConditional => { |
| 3376 |
inst.expect_at_least(4)?; |
| 3377 |
|
| 3378 |
let condition = { |
| 3379 |
let condition_id = self.next()?; |
| 3380 |
let lexp = self.lookup_expression.lookup(condition_id)?; |
| 3381 |
get_expr_handle!(condition_id, lexp) |
| 3382 |
}; |
| 3383 |
|
| 3384 |
// HACK(eddyb) Naga doesn't seem to have this helper, |
| 3385 |
// so it's declared on the fly here for convenience. |
| 3386 |
#[derive(Copy, Clone)] |
| 3387 |
struct BranchTarget { |
| 3388 |
label_id: spirv::Word, |
| 3389 |
merge_info: Option<MergeBlockInformation>, |
| 3390 |
} |
| 3391 |
let branch_target = |label_id| BranchTarget { |
| 3392 |
label_id, |
| 3393 |
merge_info: ctx.mergers.get(&label_id).copied(), |
| 3394 |
}; |
| 3395 |
|
| 3396 |
let true_target = branch_target(self.next()?); |
| 3397 |
let false_target = branch_target(self.next()?); |
| 3398 |
|
| 3399 |
// Consume branch weights |
| 3400 |
for _ in 4..inst.wc { |
| 3401 |
let _ = self.next()?; |
| 3402 |
} |
| 3403 |
|
| 3404 |
// Handle `OpBranchConditional`s used at the end of a loop |
| 3405 |
// body's "continuing" section as a "conditional backedge", |
| 3406 |
// i.e. a `do`-`while` condition, or `break if` in WGSL. |
| 3407 |
|
| 3408 |
// HACK(eddyb) this has to go to the parent *twice*, because |
| 3409 |
// `OpLoopMerge` left the "continuing" section nested in the |
| 3410 |
// loop body in terms of `parent`, but not `BodyFragment`. |
| 3411 |
let parent_body_idx = ctx.bodies[body_idx].parent; |
| 3412 |
let parent_parent_body_idx = ctx.bodies[parent_body_idx].parent; |
| 3413 |
match ctx.bodies[parent_parent_body_idx].data[..] { |
| 3414 |
// The `OpLoopMerge`'s `continuing` block and the loop's |
| 3415 |
// backedge block may not be the same, but they'll both |
| 3416 |
// belong to the same body. |
| 3417 |
[.., BodyFragment::Loop { |
| 3418 |
body: loop_body_idx, |
| 3419 |
continuing: loop_continuing_idx, |
| 3420 |
break_if: ref mut break_if_slot @ None, |
| 3421 |
}] if body_idx == loop_continuing_idx => { |
| 3422 |
// Try both orderings of break-vs-backedge, because |
| 3423 |
// SPIR-V is symmetrical here, unlike WGSL `break if`. |
| 3424 |
let break_if_cond = [true, false].into_iter().find_map(|true_breaks| { |
| 3425 |
let (break_candidate, backedge_candidate) = if true_breaks { |
| 3426 |
(true_target, false_target) |
| 3427 |
} else { |
| 3428 |
(false_target, true_target) |
| 3429 |
}; |
| 3430 |
|
| 3431 |
if break_candidate.merge_info |
| 3432 |
!= Some(MergeBlockInformation::LoopMerge) |
| 3433 |
{ |
| 3434 |
return None; |
| 3435 |
} |
| 3436 |
|
| 3437 |
// HACK(eddyb) since Naga doesn't explicitly track |
| 3438 |
// backedges, this is checking for the outcome of |
| 3439 |
// `OpLoopMerge` below (even if it looks weird). |
| 3440 |
let backedge_candidate_is_backedge = |
| 3441 |
backedge_candidate.merge_info.is_none() |
| 3442 |
&& ctx.body_for_label.get(&backedge_candidate.label_id) |
| 3443 |
== Some(&loop_body_idx); |
| 3444 |
if !backedge_candidate_is_backedge { |
| 3445 |
return None; |
| 3446 |
} |
| 3447 |
|
| 3448 |
Some(if true_breaks { |
| 3449 |
condition |
| 3450 |
} else { |
| 3451 |
ctx.expressions.append( |
| 3452 |
crate::Expression::Unary { |
| 3453 |
op: crate::UnaryOperator::LogicalNot, |
| 3454 |
expr: condition, |
| 3455 |
}, |
| 3456 |
span, |
| 3457 |
) |
| 3458 |
}) |
| 3459 |
}); |
| 3460 |
|
| 3461 |
if let Some(break_if_cond) = break_if_cond { |
| 3462 |
*break_if_slot = Some(break_if_cond); |
| 3463 |
|
| 3464 |
// This `OpBranchConditional` ends the "continuing" |
| 3465 |
// section of the loop body as normal, with the |
| 3466 |
// `break if` condition having been stashed above. |
| 3467 |
break None; |
| 3468 |
} |
| 3469 |
} |
| 3470 |
_ => {} |
| 3471 |
} |
| 3472 |
|
| 3473 |
block.extend(emitter.finish(ctx.expressions)); |
| 3474 |
ctx.blocks.insert(block_id, block); |
| 3475 |
let body = &mut ctx.bodies[body_idx]; |
| 3476 |
body.data.push(BodyFragment::BlockId(block_id)); |
| 3477 |
|
| 3478 |
let same_target = true_target.label_id == false_target.label_id; |
| 3479 |
|
| 3480 |
// Start a body block for the `accept` branch. |
| 3481 |
let accept = ctx.bodies.len(); |
| 3482 |
let mut accept_block = Body::with_parent(body_idx); |
| 3483 |
|
| 3484 |
// If the `OpBranchConditional` target is somebody else's |
| 3485 |
// merge or continue block, then put a `Break` or `Continue` |
| 3486 |
// statement in this new body block. |
| 3487 |
if let Some(info) = true_target.merge_info { |
| 3488 |
merger( |
| 3489 |
match same_target { |
| 3490 |
true => &mut ctx.bodies[body_idx], |
| 3491 |
false => &mut accept_block, |
| 3492 |
}, |
| 3493 |
&info, |
| 3494 |
) |
| 3495 |
} else { |
| 3496 |
// Note the body index for the block we're branching to. |
| 3497 |
let prev = ctx.body_for_label.insert( |
| 3498 |
true_target.label_id, |
| 3499 |
match same_target { |
| 3500 |
true => body_idx, |
| 3501 |
false => accept, |
| 3502 |
}, |
| 3503 |
); |
| 3504 |
debug_assert!(prev.is_none()); |
| 3505 |
} |
| 3506 |
|
| 3507 |
if same_target { |
| 3508 |
return Ok(()); |
| 3509 |
} |
| 3510 |
|
| 3511 |
ctx.bodies.push(accept_block); |
| 3512 |
|
| 3513 |
// Handle the `reject` branch just like the `accept` block. |
| 3514 |
let reject = ctx.bodies.len(); |
| 3515 |
let mut reject_block = Body::with_parent(body_idx); |
| 3516 |
|
| 3517 |
if let Some(info) = false_target.merge_info { |
| 3518 |
merger(&mut reject_block, &info) |
| 3519 |
} else { |
| 3520 |
let prev = ctx.body_for_label.insert(false_target.label_id, reject); |
| 3521 |
debug_assert!(prev.is_none()); |
| 3522 |
} |
| 3523 |
|
| 3524 |
ctx.bodies.push(reject_block); |
| 3525 |
|
| 3526 |
let body = &mut ctx.bodies[body_idx]; |
| 3527 |
body.data.push(BodyFragment::If { |
| 3528 |
condition, |
| 3529 |
accept, |
| 3530 |
reject, |
| 3531 |
}); |
| 3532 |
|
| 3533 |
return Ok(()); |
| 3534 |
} |
| 3535 |
Op::Switch => { |
| 3536 |
inst.expect_at_least(3)?; |
| 3537 |
let selector = self.next()?; |
| 3538 |
let default_id = self.next()?; |
| 3539 |
|
| 3540 |
// If the previous instruction was a `OpSelectionMerge` then we must |
| 3541 |
// promote the `MergeBlockInformation` to a `SwitchMerge` |
| 3542 |
if let Some(merge) = selection_merge_block { |
| 3543 |
ctx.mergers |
| 3544 |
.insert(merge, MergeBlockInformation::SwitchMerge); |
| 3545 |
} |
| 3546 |
|
| 3547 |
let default = ctx.bodies.len(); |
| 3548 |
ctx.bodies.push(Body::with_parent(body_idx)); |
| 3549 |
ctx.body_for_label.entry(default_id).or_insert(default); |
| 3550 |
|
| 3551 |
let selector_lexp = &self.lookup_expression[&selector]; |
| 3552 |
let selector_lty = self.lookup_type.lookup(selector_lexp.type_id)?; |
| 3553 |
let selector_handle = get_expr_handle!(selector, selector_lexp); |
| 3554 |
let selector = match ctx.module.types[selector_lty.handle].inner { |
| 3555 |
crate::TypeInner::Scalar(crate::Scalar { |
| 3556 |
kind: crate::ScalarKind::Uint, |
| 3557 |
width: _, |
| 3558 |
}) => { |
| 3559 |
// IR expects a signed integer, so do a bitcast |
| 3560 |
ctx.expressions.append( |
| 3561 |
crate::Expression::As { |
| 3562 |
kind: crate::ScalarKind::Sint, |
| 3563 |
expr: selector_handle, |
| 3564 |
convert: None, |
| 3565 |
}, |
| 3566 |
span, |
| 3567 |
) |
| 3568 |
} |
| 3569 |
crate::TypeInner::Scalar(crate::Scalar { |
| 3570 |
kind: crate::ScalarKind::Sint, |
| 3571 |
width: _, |
| 3572 |
}) => selector_handle, |
| 3573 |
ref other => unimplemented!("Unexpected selector {:?}", other), |
| 3574 |
}; |
| 3575 |
|
| 3576 |
// Clear past switch cases to prevent them from entering this one |
| 3577 |
self.switch_cases.clear(); |
| 3578 |
|
| 3579 |
for _ in 0..(inst.wc - 3) / 2 { |
| 3580 |
let literal = self.next()?; |
| 3581 |
let target = self.next()?; |
| 3582 |
|
| 3583 |
let case_body_idx = ctx.bodies.len(); |
| 3584 |
|
| 3585 |
// Check if any previous case already used this target block id, if so |
| 3586 |
// group them together to reorder them later so that no weird |
| 3587 |
// fallthrough cases happen. |
| 3588 |
if let Some(&mut (_, ref mut literals)) = self.switch_cases.get_mut(&target) |
| 3589 |
{ |
| 3590 |
literals.push(literal as i32); |
| 3591 |
continue; |
| 3592 |
} |
| 3593 |
|
| 3594 |
let mut body = Body::with_parent(body_idx); |
| 3595 |
|
| 3596 |
if let Some(info) = ctx.mergers.get(&target) { |
| 3597 |
merger(&mut body, info); |
| 3598 |
} |
| 3599 |
|
| 3600 |
ctx.bodies.push(body); |
| 3601 |
ctx.body_for_label.entry(target).or_insert(case_body_idx); |
| 3602 |
|
| 3603 |
// Register this target block id as already having been processed and |
| 3604 |
// the respective body index assigned and the first case value |
| 3605 |
self.switch_cases |
| 3606 |
.insert(target, (case_body_idx, vec![literal as i32])); |
| 3607 |
} |
| 3608 |
|
| 3609 |
// Loop through the collected target blocks creating a new case for each |
| 3610 |
// literal pointing to it, only one case will have the true body and all the |
| 3611 |
// others will be empty fallthrough so that they all execute the same body |
| 3612 |
// without duplicating code. |
| 3613 |
// |
| 3614 |
// Since `switch_cases` is an indexmap the order of insertion is preserved |
| 3615 |
// this is needed because spir-v defines fallthrough order in the switch |
| 3616 |
// instruction. |
| 3617 |
let mut cases = Vec::with_capacity((inst.wc as usize - 3) / 2); |
| 3618 |
for &(case_body_idx, ref literals) in self.switch_cases.values() { |
| 3619 |
let value = literals[0]; |
| 3620 |
|
| 3621 |
for &literal in literals.iter().skip(1) { |
| 3622 |
let empty_body_idx = ctx.bodies.len(); |
| 3623 |
let body = Body::with_parent(body_idx); |
| 3624 |
|
| 3625 |
ctx.bodies.push(body); |
| 3626 |
|
| 3627 |
cases.push((literal, empty_body_idx)); |
| 3628 |
} |
| 3629 |
|
| 3630 |
cases.push((value, case_body_idx)); |
| 3631 |
} |
| 3632 |
|
| 3633 |
block.extend(emitter.finish(ctx.expressions)); |
| 3634 |
|
| 3635 |
let body = &mut ctx.bodies[body_idx]; |
| 3636 |
ctx.blocks.insert(block_id, block); |
| 3637 |
// Make sure the vector has space for at least two more allocations |
| 3638 |
body.data.reserve(2); |
| 3639 |
body.data.push(BodyFragment::BlockId(block_id)); |
| 3640 |
body.data.push(BodyFragment::Switch { |
| 3641 |
selector, |
| 3642 |
cases, |
| 3643 |
default, |
| 3644 |
}); |
| 3645 |
|
| 3646 |
return Ok(()); |
| 3647 |
} |
| 3648 |
Op::SelectionMerge => { |
| 3649 |
inst.expect(3)?; |
| 3650 |
let merge_block_id = self.next()?; |
| 3651 |
// TODO: Selection Control Mask |
| 3652 |
let _selection_control = self.next()?; |
| 3653 |
|
| 3654 |
// Indicate that the merge block is a continuation of the |
| 3655 |
// current `Body`. |
| 3656 |
ctx.body_for_label.entry(merge_block_id).or_insert(body_idx); |
| 3657 |
|
| 3658 |
// Let subsequent branches to the merge block know that |
| 3659 |
// they've reached the end of the selection construct. |
| 3660 |
ctx.mergers |
| 3661 |
.insert(merge_block_id, MergeBlockInformation::SelectionMerge); |
| 3662 |
|
| 3663 |
selection_merge_block = Some(merge_block_id); |
| 3664 |
} |
| 3665 |
Op::LoopMerge => { |
| 3666 |
inst.expect_at_least(4)?; |
| 3667 |
let merge_block_id = self.next()?; |
| 3668 |
let continuing = self.next()?; |
| 3669 |
|
| 3670 |
// TODO: Loop Control Parameters |
| 3671 |
for _ in 0..inst.wc - 3 { |
| 3672 |
self.next()?; |
| 3673 |
} |
| 3674 |
|
| 3675 |
// Indicate that the merge block is a continuation of the |
| 3676 |
// current `Body`. |
| 3677 |
ctx.body_for_label.entry(merge_block_id).or_insert(body_idx); |
| 3678 |
// Let subsequent branches to the merge block know that |
| 3679 |
// they're `Break` statements. |
| 3680 |
ctx.mergers |
| 3681 |
.insert(merge_block_id, MergeBlockInformation::LoopMerge); |
| 3682 |
|
| 3683 |
let loop_body_idx = ctx.bodies.len(); |
| 3684 |
ctx.bodies.push(Body::with_parent(body_idx)); |
| 3685 |
|
| 3686 |
let continue_idx = ctx.bodies.len(); |
| 3687 |
// The continue block inherits the scope of the loop body |
| 3688 |
ctx.bodies.push(Body::with_parent(loop_body_idx)); |
| 3689 |
ctx.body_for_label.entry(continuing).or_insert(continue_idx); |
| 3690 |
// Let subsequent branches to the continue block know that |
| 3691 |
// they're `Continue` statements. |
| 3692 |
ctx.mergers |
| 3693 |
.insert(continuing, MergeBlockInformation::LoopContinue); |
| 3694 |
|
| 3695 |
// The loop header always belongs to the loop body |
| 3696 |
ctx.body_for_label.insert(block_id, loop_body_idx); |
| 3697 |
|
| 3698 |
let parent_body = &mut ctx.bodies[body_idx]; |
| 3699 |
parent_body.data.push(BodyFragment::Loop { |
| 3700 |
body: loop_body_idx, |
| 3701 |
continuing: continue_idx, |
| 3702 |
break_if: None, |
| 3703 |
}); |
| 3704 |
body_idx = loop_body_idx; |
| 3705 |
} |
| 3706 |
Op::DPdxCoarse => { |
| 3707 |
parse_expr_op!( |
| 3708 |
crate::DerivativeAxis::X, |
| 3709 |
crate::DerivativeControl::Coarse, |
| 3710 |
DERIVATIVE |
| 3711 |
)?; |
| 3712 |
} |
| 3713 |
Op::DPdyCoarse => { |
| 3714 |
parse_expr_op!( |
| 3715 |
crate::DerivativeAxis::Y, |
| 3716 |
crate::DerivativeControl::Coarse, |
| 3717 |
DERIVATIVE |
| 3718 |
)?; |
| 3719 |
} |
| 3720 |
Op::FwidthCoarse => { |
| 3721 |
parse_expr_op!( |
| 3722 |
crate::DerivativeAxis::Width, |
| 3723 |
crate::DerivativeControl::Coarse, |
| 3724 |
DERIVATIVE |
| 3725 |
)?; |
| 3726 |
} |
| 3727 |
Op::DPdxFine => { |
| 3728 |
parse_expr_op!( |
| 3729 |
crate::DerivativeAxis::X, |
| 3730 |
crate::DerivativeControl::Fine, |
| 3731 |
DERIVATIVE |
| 3732 |
)?; |
| 3733 |
} |
| 3734 |
Op::DPdyFine => { |
| 3735 |
parse_expr_op!( |
| 3736 |
crate::DerivativeAxis::Y, |
| 3737 |
crate::DerivativeControl::Fine, |
| 3738 |
DERIVATIVE |
| 3739 |
)?; |
| 3740 |
} |
| 3741 |
Op::FwidthFine => { |
| 3742 |
parse_expr_op!( |
| 3743 |
crate::DerivativeAxis::Width, |
| 3744 |
crate::DerivativeControl::Fine, |
| 3745 |
DERIVATIVE |
| 3746 |
)?; |
| 3747 |
} |
| 3748 |
Op::DPdx => { |
| 3749 |
parse_expr_op!( |
| 3750 |
crate::DerivativeAxis::X, |
| 3751 |
crate::DerivativeControl::None, |
| 3752 |
DERIVATIVE |
| 3753 |
)?; |
| 3754 |
} |
| 3755 |
Op::DPdy => { |
| 3756 |
parse_expr_op!( |
| 3757 |
crate::DerivativeAxis::Y, |
| 3758 |
crate::DerivativeControl::None, |
| 3759 |
DERIVATIVE |
| 3760 |
)?; |
| 3761 |
} |
| 3762 |
Op::Fwidth => { |
| 3763 |
parse_expr_op!( |
| 3764 |
crate::DerivativeAxis::Width, |
| 3765 |
crate::DerivativeControl::None, |
| 3766 |
DERIVATIVE |
| 3767 |
)?; |
| 3768 |
} |
| 3769 |
Op::ArrayLength => { |
| 3770 |
inst.expect(5)?; |
| 3771 |
let result_type_id = self.next()?; |
| 3772 |
let result_id = self.next()?; |
| 3773 |
let structure_id = self.next()?; |
| 3774 |
let member_index = self.next()?; |
| 3775 |
|
| 3776 |
// We're assuming that the validation pass, if it's run, will catch if the |
| 3777 |
// wrong types or parameters are supplied here. |
| 3778 |
|
| 3779 |
let structure_ptr = self.lookup_expression.lookup(structure_id)?; |
| 3780 |
let structure_handle = get_expr_handle!(structure_id, structure_ptr); |
| 3781 |
|
| 3782 |
let member_ptr = ctx.expressions.append( |
| 3783 |
crate::Expression::AccessIndex { |
| 3784 |
base: structure_handle, |
| 3785 |
index: member_index, |
| 3786 |
}, |
| 3787 |
span, |
| 3788 |
); |
| 3789 |
|
| 3790 |
let length = ctx |
| 3791 |
.expressions |
| 3792 |
.append(crate::Expression::ArrayLength(member_ptr), span); |
| 3793 |
|
| 3794 |
self.lookup_expression.insert( |
| 3795 |
result_id, |
| 3796 |
LookupExpression { |
| 3797 |
handle: length, |
| 3798 |
type_id: result_type_id, |
| 3799 |
block_id, |
| 3800 |
}, |
| 3801 |
); |
| 3802 |
} |
| 3803 |
Op::CopyMemory => { |
| 3804 |
inst.expect_at_least(3)?; |
| 3805 |
let target_id = self.next()?; |
| 3806 |
let source_id = self.next()?; |
| 3807 |
let _memory_access = if inst.wc != 3 { |
| 3808 |
inst.expect(4)?; |
| 3809 |
spirv::MemoryAccess::from_bits(self.next()?) |
| 3810 |
.ok_or(Error::InvalidParameter(Op::CopyMemory))? |
| 3811 |
} else { |
| 3812 |
spirv::MemoryAccess::NONE |
| 3813 |
}; |
| 3814 |
|
| 3815 |
// TODO: check if the source and target types are the same? |
| 3816 |
let target = self.lookup_expression.lookup(target_id)?; |
| 3817 |
let target_handle = get_expr_handle!(target_id, target); |
| 3818 |
let source = self.lookup_expression.lookup(source_id)?; |
| 3819 |
let source_handle = get_expr_handle!(source_id, source); |
| 3820 |
|
| 3821 |
// This operation is practically the same as loading and then storing, I think. |
| 3822 |
let value_expr = ctx.expressions.append( |
| 3823 |
crate::Expression::Load { |
| 3824 |
pointer: source_handle, |
| 3825 |
}, |
| 3826 |
span, |
| 3827 |
); |
| 3828 |
|
| 3829 |
block.extend(emitter.finish(ctx.expressions)); |
| 3830 |
block.push( |
| 3831 |
crate::Statement::Store { |
| 3832 |
pointer: target_handle, |
| 3833 |
value: value_expr, |
| 3834 |
}, |
| 3835 |
span, |
| 3836 |
); |
| 3837 |
|
| 3838 |
emitter.start(ctx.expressions); |
| 3839 |
} |
| 3840 |
Op::ControlBarrier => { |
| 3841 |
inst.expect(4)?; |
| 3842 |
let exec_scope_id = self.next()?; |
| 3843 |
let _mem_scope_raw = self.next()?; |
| 3844 |
let semantics_id = self.next()?; |
| 3845 |
let exec_scope_const = self.lookup_constant.lookup(exec_scope_id)?; |
| 3846 |
let semantics_const = self.lookup_constant.lookup(semantics_id)?; |
| 3847 |
|
| 3848 |
let exec_scope = resolve_constant(ctx.gctx(), &exec_scope_const.inner) |
| 3849 |
.ok_or(Error::InvalidBarrierScope(exec_scope_id))?; |
| 3850 |
let semantics = resolve_constant(ctx.gctx(), &semantics_const.inner) |
| 3851 |
.ok_or(Error::InvalidBarrierMemorySemantics(semantics_id))?; |
| 3852 |
|
| 3853 |
if exec_scope == spirv::Scope::Workgroup as u32 { |
| 3854 |
let mut flags = crate::Barrier::empty(); |
| 3855 |
flags.set( |
| 3856 |
crate::Barrier::STORAGE, |
| 3857 |
semantics & spirv::MemorySemantics::UNIFORM_MEMORY.bits() != 0, |
| 3858 |
); |
| 3859 |
flags.set( |
| 3860 |
crate::Barrier::WORK_GROUP, |
| 3861 |
semantics |
| 3862 |
& (spirv::MemorySemantics::SUBGROUP_MEMORY |
| 3863 |
| spirv::MemorySemantics::WORKGROUP_MEMORY) |
| 3864 |
.bits() |
| 3865 |
!= 0, |
| 3866 |
); |
| 3867 |
flags.set( |
| 3868 |
crate::Barrier::TEXTURE, |
| 3869 |
semantics & spirv::MemorySemantics::IMAGE_MEMORY.bits() != 0, |
| 3870 |
); |
| 3871 |
block.push(crate::Statement::Barrier(flags), span); |
| 3872 |
} else { |
| 3873 |
log::warn!("Unsupported barrier execution scope: {}", exec_scope); |
| 3874 |
} |
| 3875 |
} |
| 3876 |
Op::CopyObject => { |
| 3877 |
inst.expect(4)?; |
| 3878 |
let result_type_id = self.next()?; |
| 3879 |
let result_id = self.next()?; |
| 3880 |
let operand_id = self.next()?; |
| 3881 |
|
| 3882 |
let lookup = self.lookup_expression.lookup(operand_id)?; |
| 3883 |
let handle = get_expr_handle!(operand_id, lookup); |
| 3884 |
|
| 3885 |
self.lookup_expression.insert( |
| 3886 |
result_id, |
| 3887 |
LookupExpression { |
| 3888 |
handle, |
| 3889 |
type_id: result_type_id, |
| 3890 |
block_id, |
| 3891 |
}, |
| 3892 |
); |
| 3893 |
} |
| 3894 |
Op::GroupNonUniformBallot => { |
| 3895 |
inst.expect(5)?; |
| 3896 |
block.extend(emitter.finish(ctx.expressions)); |
| 3897 |
let result_type_id = self.next()?; |
| 3898 |
let result_id = self.next()?; |
| 3899 |
let exec_scope_id = self.next()?; |
| 3900 |
let predicate_id = self.next()?; |
| 3901 |
|
| 3902 |
let exec_scope_const = self.lookup_constant.lookup(exec_scope_id)?; |
| 3903 |
let _exec_scope = resolve_constant(ctx.gctx(), &exec_scope_const.inner) |
| 3904 |
.filter(|exec_scope| *exec_scope == spirv::Scope::Subgroup as u32) |
| 3905 |
.ok_or(Error::InvalidBarrierScope(exec_scope_id))?; |
| 3906 |
|
| 3907 |
let predicate = if self |
| 3908 |
.lookup_constant |
| 3909 |
.lookup(predicate_id) |
| 3910 |
.ok() |
| 3911 |
.filter(|predicate_const| match predicate_const.inner { |
| 3912 |
Constant::Constant(constant) => matches!( |
| 3913 |
ctx.gctx().global_expressions[ctx.gctx().constants[constant].init], |
| 3914 |
crate::Expression::Literal(crate::Literal::Bool(true)), |
| 3915 |
), |
| 3916 |
Constant::Override(_) => false, |
| 3917 |
}) |
| 3918 |
.is_some() |
| 3919 |
{ |
| 3920 |
None |
| 3921 |
} else { |
| 3922 |
let predicate_lookup = self.lookup_expression.lookup(predicate_id)?; |
| 3923 |
let predicate_handle = get_expr_handle!(predicate_id, predicate_lookup); |
| 3924 |
Some(predicate_handle) |
| 3925 |
}; |
| 3926 |
|
| 3927 |
let result_handle = ctx |
| 3928 |
.expressions |
| 3929 |
.append(crate::Expression::SubgroupBallotResult, span); |
| 3930 |
self.lookup_expression.insert( |
| 3931 |
result_id, |
| 3932 |
LookupExpression { |
| 3933 |
handle: result_handle, |
| 3934 |
type_id: result_type_id, |
| 3935 |
block_id, |
| 3936 |
}, |
| 3937 |
); |
| 3938 |
|
| 3939 |
block.push( |
| 3940 |
crate::Statement::SubgroupBallot { |
| 3941 |
result: result_handle, |
| 3942 |
predicate, |
| 3943 |
}, |
| 3944 |
span, |
| 3945 |
); |
| 3946 |
emitter.start(ctx.expressions); |
| 3947 |
} |
| 3948 |
Op::GroupNonUniformAll |
| 3949 |
| Op::GroupNonUniformAny |
| 3950 |
| Op::GroupNonUniformIAdd |
| 3951 |
| Op::GroupNonUniformFAdd |
| 3952 |
| Op::GroupNonUniformIMul |
| 3953 |
| Op::GroupNonUniformFMul |
| 3954 |
| Op::GroupNonUniformSMax |
| 3955 |
| Op::GroupNonUniformUMax |
| 3956 |
| Op::GroupNonUniformFMax |
| 3957 |
| Op::GroupNonUniformSMin |
| 3958 |
| Op::GroupNonUniformUMin |
| 3959 |
| Op::GroupNonUniformFMin |
| 3960 |
| Op::GroupNonUniformBitwiseAnd |
| 3961 |
| Op::GroupNonUniformBitwiseOr |
| 3962 |
| Op::GroupNonUniformBitwiseXor |
| 3963 |
| Op::GroupNonUniformLogicalAnd |
| 3964 |
| Op::GroupNonUniformLogicalOr |
| 3965 |
| Op::GroupNonUniformLogicalXor => { |
| 3966 |
block.extend(emitter.finish(ctx.expressions)); |
| 3967 |
inst.expect( |
| 3968 |
if matches!(inst.op, Op::GroupNonUniformAll | Op::GroupNonUniformAny) { |
| 3969 |
5 |
| 3970 |
} else { |
| 3971 |
6 |
| 3972 |
}, |
| 3973 |
)?; |
| 3974 |
let result_type_id = self.next()?; |
| 3975 |
let result_id = self.next()?; |
| 3976 |
let exec_scope_id = self.next()?; |
| 3977 |
let collective_op_id = match inst.op { |
| 3978 |
Op::GroupNonUniformAll | Op::GroupNonUniformAny => { |
| 3979 |
crate::CollectiveOperation::Reduce |
| 3980 |
} |
| 3981 |
_ => { |
| 3982 |
let group_op_id = self.next()?; |
| 3983 |
match spirv::GroupOperation::from_u32(group_op_id) { |
| 3984 |
Some(spirv::GroupOperation::Reduce) => { |
| 3985 |
crate::CollectiveOperation::Reduce |
| 3986 |
} |
| 3987 |
Some(spirv::GroupOperation::InclusiveScan) => { |
| 3988 |
crate::CollectiveOperation::InclusiveScan |
| 3989 |
} |
| 3990 |
Some(spirv::GroupOperation::ExclusiveScan) => { |
| 3991 |
crate::CollectiveOperation::ExclusiveScan |
| 3992 |
} |
| 3993 |
_ => return Err(Error::UnsupportedGroupOperation(group_op_id)), |
| 3994 |
} |
| 3995 |
} |
| 3996 |
}; |
| 3997 |
let argument_id = self.next()?; |
| 3998 |
|
| 3999 |
let argument_lookup = self.lookup_expression.lookup(argument_id)?; |
| 4000 |
let argument_handle = get_expr_handle!(argument_id, argument_lookup); |
| 4001 |
|
| 4002 |
let exec_scope_const = self.lookup_constant.lookup(exec_scope_id)?; |
| 4003 |
let _exec_scope = resolve_constant(ctx.gctx(), &exec_scope_const.inner) |
| 4004 |
.filter(|exec_scope| *exec_scope == spirv::Scope::Subgroup as u32) |
| 4005 |
.ok_or(Error::InvalidBarrierScope(exec_scope_id))?; |
| 4006 |
|
| 4007 |
let op_id = match inst.op { |
| 4008 |
Op::GroupNonUniformAll => crate::SubgroupOperation::All, |
| 4009 |
Op::GroupNonUniformAny => crate::SubgroupOperation::Any, |
| 4010 |
Op::GroupNonUniformIAdd | Op::GroupNonUniformFAdd => { |
| 4011 |
crate::SubgroupOperation::Add |
| 4012 |
} |
| 4013 |
Op::GroupNonUniformIMul | Op::GroupNonUniformFMul => { |
| 4014 |
crate::SubgroupOperation::Mul |
| 4015 |
} |
| 4016 |
Op::GroupNonUniformSMax |
| 4017 |
| Op::GroupNonUniformUMax |
| 4018 |
| Op::GroupNonUniformFMax => crate::SubgroupOperation::Max, |
| 4019 |
Op::GroupNonUniformSMin |
| 4020 |
| Op::GroupNonUniformUMin |
| 4021 |
| Op::GroupNonUniformFMin => crate::SubgroupOperation::Min, |
| 4022 |
Op::GroupNonUniformBitwiseAnd | Op::GroupNonUniformLogicalAnd => { |
| 4023 |
crate::SubgroupOperation::And |
| 4024 |
} |
| 4025 |
Op::GroupNonUniformBitwiseOr | Op::GroupNonUniformLogicalOr => { |
| 4026 |
crate::SubgroupOperation::Or |
| 4027 |
} |
| 4028 |
Op::GroupNonUniformBitwiseXor | Op::GroupNonUniformLogicalXor => { |
| 4029 |
crate::SubgroupOperation::Xor |
| 4030 |
} |
| 4031 |
_ => unreachable!(), |
| 4032 |
}; |
| 4033 |
|
| 4034 |
let result_type = self.lookup_type.lookup(result_type_id)?; |
| 4035 |
|
| 4036 |
let result_handle = ctx.expressions.append( |
| 4037 |
crate::Expression::SubgroupOperationResult { |
| 4038 |
ty: result_type.handle, |
| 4039 |
}, |
| 4040 |
span, |
| 4041 |
); |
| 4042 |
self.lookup_expression.insert( |
| 4043 |
result_id, |
| 4044 |
LookupExpression { |
| 4045 |
handle: result_handle, |
| 4046 |
type_id: result_type_id, |
| 4047 |
block_id, |
| 4048 |
}, |
| 4049 |
); |
| 4050 |
|
| 4051 |
block.push( |
| 4052 |
crate::Statement::SubgroupCollectiveOperation { |
| 4053 |
result: result_handle, |
| 4054 |
op: op_id, |
| 4055 |
collective_op: collective_op_id, |
| 4056 |
argument: argument_handle, |
| 4057 |
}, |
| 4058 |
span, |
| 4059 |
); |
| 4060 |
emitter.start(ctx.expressions); |
| 4061 |
} |
| 4062 |
Op::GroupNonUniformBroadcastFirst |
| 4063 |
| Op::GroupNonUniformBroadcast |
| 4064 |
| Op::GroupNonUniformShuffle |
| 4065 |
| Op::GroupNonUniformShuffleDown |
| 4066 |
| Op::GroupNonUniformShuffleUp |
| 4067 |
| Op::GroupNonUniformShuffleXor => { |
| 4068 |
inst.expect(if matches!(inst.op, Op::GroupNonUniformBroadcastFirst) { |
| 4069 |
5 |
| 4070 |
} else { |
| 4071 |
6 |
| 4072 |
})?; |
| 4073 |
block.extend(emitter.finish(ctx.expressions)); |
| 4074 |
let result_type_id = self.next()?; |
| 4075 |
let result_id = self.next()?; |
| 4076 |
let exec_scope_id = self.next()?; |
| 4077 |
let argument_id = self.next()?; |
| 4078 |
|
| 4079 |
let argument_lookup = self.lookup_expression.lookup(argument_id)?; |
| 4080 |
let argument_handle = get_expr_handle!(argument_id, argument_lookup); |
| 4081 |
|
| 4082 |
let exec_scope_const = self.lookup_constant.lookup(exec_scope_id)?; |
| 4083 |
let _exec_scope = resolve_constant(ctx.gctx(), &exec_scope_const.inner) |
| 4084 |
.filter(|exec_scope| *exec_scope == spirv::Scope::Subgroup as u32) |
| 4085 |
.ok_or(Error::InvalidBarrierScope(exec_scope_id))?; |
| 4086 |
|
| 4087 |
let mode = if matches!(inst.op, Op::GroupNonUniformBroadcastFirst) { |
| 4088 |
crate::GatherMode::BroadcastFirst |
| 4089 |
} else { |
| 4090 |
let index_id = self.next()?; |
| 4091 |
let index_lookup = self.lookup_expression.lookup(index_id)?; |
| 4092 |
let index_handle = get_expr_handle!(index_id, index_lookup); |
| 4093 |
match inst.op { |
| 4094 |
Op::GroupNonUniformBroadcast => { |
| 4095 |
crate::GatherMode::Broadcast(index_handle) |
| 4096 |
} |
| 4097 |
Op::GroupNonUniformShuffle => crate::GatherMode::Shuffle(index_handle), |
| 4098 |
Op::GroupNonUniformShuffleDown => { |
| 4099 |
crate::GatherMode::ShuffleDown(index_handle) |
| 4100 |
} |
| 4101 |
Op::GroupNonUniformShuffleUp => { |
| 4102 |
crate::GatherMode::ShuffleUp(index_handle) |
| 4103 |
} |
| 4104 |
Op::GroupNonUniformShuffleXor => { |
| 4105 |
crate::GatherMode::ShuffleXor(index_handle) |
| 4106 |
} |
| 4107 |
_ => unreachable!(), |
| 4108 |
} |
| 4109 |
}; |
| 4110 |
|
| 4111 |
let result_type = self.lookup_type.lookup(result_type_id)?; |
| 4112 |
|
| 4113 |
let result_handle = ctx.expressions.append( |
| 4114 |
crate::Expression::SubgroupOperationResult { |
| 4115 |
ty: result_type.handle, |
| 4116 |
}, |
| 4117 |
span, |
| 4118 |
); |
| 4119 |
self.lookup_expression.insert( |
| 4120 |
result_id, |
| 4121 |
LookupExpression { |
| 4122 |
handle: result_handle, |
| 4123 |
type_id: result_type_id, |
| 4124 |
block_id, |
| 4125 |
}, |
| 4126 |
); |
| 4127 |
|
| 4128 |
block.push( |
| 4129 |
crate::Statement::SubgroupGather { |
| 4130 |
result: result_handle, |
| 4131 |
mode, |
| 4132 |
argument: argument_handle, |
| 4133 |
}, |
| 4134 |
span, |
| 4135 |
); |
| 4136 |
emitter.start(ctx.expressions); |
| 4137 |
} |
| 4138 |
Op::AtomicLoad => { |
| 4139 |
inst.expect(6)?; |
| 4140 |
let start = self.data_offset; |
| 4141 |
let result_type_id = self.next()?; |
| 4142 |
let result_id = self.next()?; |
| 4143 |
let pointer_id = self.next()?; |
| 4144 |
let _scope_id = self.next()?; |
| 4145 |
let _memory_semantics_id = self.next()?; |
| 4146 |
let span = self.span_from_with_op(start); |
| 4147 |
|
| 4148 |
log::trace!("\t\t\tlooking up expr {:?}", pointer_id); |
| 4149 |
let p_lexp_handle = |
| 4150 |
get_expr_handle!(pointer_id, self.lookup_expression.lookup(pointer_id)?); |
| 4151 |
|
| 4152 |
// Create an expression for our result |
| 4153 |
let expr = crate::Expression::Load { |
| 4154 |
pointer: p_lexp_handle, |
| 4155 |
}; |
| 4156 |
let handle = ctx.expressions.append(expr, span); |
| 4157 |
self.lookup_expression.insert( |
| 4158 |
result_id, |
| 4159 |
LookupExpression { |
| 4160 |
handle, |
| 4161 |
type_id: result_type_id, |
| 4162 |
block_id, |
| 4163 |
}, |
| 4164 |
); |
| 4165 |
|
| 4166 |
// Store any associated global variables so we can upgrade their types later |
| 4167 |
self.record_atomic_access(ctx, p_lexp_handle)?; |
| 4168 |
} |
| 4169 |
Op::AtomicStore => { |
| 4170 |
inst.expect(5)?; |
| 4171 |
let start = self.data_offset; |
| 4172 |
let pointer_id = self.next()?; |
| 4173 |
let _scope_id = self.next()?; |
| 4174 |
let _memory_semantics_id = self.next()?; |
| 4175 |
let value_id = self.next()?; |
| 4176 |
let span = self.span_from_with_op(start); |
| 4177 |
|
| 4178 |
log::trace!("\t\t\tlooking up pointer expr {:?}", pointer_id); |
| 4179 |
let p_lexp_handle = |
| 4180 |
get_expr_handle!(pointer_id, self.lookup_expression.lookup(pointer_id)?); |
| 4181 |
|
| 4182 |
log::trace!("\t\t\tlooking up value expr {:?}", pointer_id); |
| 4183 |
let v_lexp_handle = |
| 4184 |
get_expr_handle!(value_id, self.lookup_expression.lookup(value_id)?); |
| 4185 |
|
| 4186 |
block.extend(emitter.finish(ctx.expressions)); |
| 4187 |
// Create a statement for the op itself |
| 4188 |
let stmt = crate::Statement::Store { |
| 4189 |
pointer: p_lexp_handle, |
| 4190 |
value: v_lexp_handle, |
| 4191 |
}; |
| 4192 |
block.push(stmt, span); |
| 4193 |
emitter.start(ctx.expressions); |
| 4194 |
|
| 4195 |
// Store any associated global variables so we can upgrade their types later |
| 4196 |
self.record_atomic_access(ctx, p_lexp_handle)?; |
| 4197 |
} |
| 4198 |
Op::AtomicIIncrement | Op::AtomicIDecrement => { |
| 4199 |
inst.expect(6)?; |
| 4200 |
let start = self.data_offset; |
| 4201 |
let result_type_id = self.next()?; |
| 4202 |
let result_id = self.next()?; |
| 4203 |
let pointer_id = self.next()?; |
| 4204 |
let _scope_id = self.next()?; |
| 4205 |
let _memory_semantics_id = self.next()?; |
| 4206 |
let span = self.span_from_with_op(start); |
| 4207 |
|
| 4208 |
let (p_exp_h, p_base_ty_h) = self.get_exp_and_base_ty_handles( |
| 4209 |
pointer_id, |
| 4210 |
ctx, |
| 4211 |
&mut emitter, |
| 4212 |
&mut block, |
| 4213 |
body_idx, |
| 4214 |
)?; |
| 4215 |
|
| 4216 |
block.extend(emitter.finish(ctx.expressions)); |
| 4217 |
// Create an expression for our result |
| 4218 |
let r_lexp_handle = { |
| 4219 |
let expr = crate::Expression::AtomicResult { |
| 4220 |
ty: p_base_ty_h, |
| 4221 |
comparison: false, |
| 4222 |
}; |
| 4223 |
let handle = ctx.expressions.append(expr, span); |
| 4224 |
self.lookup_expression.insert( |
| 4225 |
result_id, |
| 4226 |
LookupExpression { |
| 4227 |
handle, |
| 4228 |
type_id: result_type_id, |
| 4229 |
block_id, |
| 4230 |
}, |
| 4231 |
); |
| 4232 |
handle |
| 4233 |
}; |
| 4234 |
emitter.start(ctx.expressions); |
| 4235 |
|
| 4236 |
// Create a literal "1" to use as our value |
| 4237 |
let one_lexp_handle = make_index_literal( |
| 4238 |
ctx, |
| 4239 |
1, |
| 4240 |
&mut block, |
| 4241 |
&mut emitter, |
| 4242 |
p_base_ty_h, |
| 4243 |
result_type_id, |
| 4244 |
span, |
| 4245 |
)?; |
| 4246 |
|
| 4247 |
// Create a statement for the op itself |
| 4248 |
let stmt = crate::Statement::Atomic { |
| 4249 |
pointer: p_exp_h, |
| 4250 |
fun: match inst.op { |
| 4251 |
Op::AtomicIIncrement => crate::AtomicFunction::Add, |
| 4252 |
_ => crate::AtomicFunction::Subtract, |
| 4253 |
}, |
| 4254 |
value: one_lexp_handle, |
| 4255 |
result: Some(r_lexp_handle), |
| 4256 |
}; |
| 4257 |
block.push(stmt, span); |
| 4258 |
|
| 4259 |
// Store any associated global variables so we can upgrade their types later |
| 4260 |
self.record_atomic_access(ctx, p_exp_h)?; |
| 4261 |
} |
| 4262 |
Op::AtomicCompareExchange => { |
| 4263 |
inst.expect(9)?; |
| 4264 |
|
| 4265 |
let start = self.data_offset; |
| 4266 |
let span = self.span_from_with_op(start); |
| 4267 |
let result_type_id = self.next()?; |
| 4268 |
let result_id = self.next()?; |
| 4269 |
let pointer_id = self.next()?; |
| 4270 |
let _memory_scope_id = self.next()?; |
| 4271 |
let _equal_memory_semantics_id = self.next()?; |
| 4272 |
let _unequal_memory_semantics_id = self.next()?; |
| 4273 |
let value_id = self.next()?; |
| 4274 |
let comparator_id = self.next()?; |
| 4275 |
|
| 4276 |
let (p_exp_h, p_base_ty_h) = self.get_exp_and_base_ty_handles( |
| 4277 |
pointer_id, |
| 4278 |
ctx, |
| 4279 |
&mut emitter, |
| 4280 |
&mut block, |
| 4281 |
body_idx, |
| 4282 |
)?; |
| 4283 |
|
| 4284 |
log::trace!("\t\t\tlooking up value expr {:?}", value_id); |
| 4285 |
let v_lexp_handle = |
| 4286 |
get_expr_handle!(value_id, self.lookup_expression.lookup(value_id)?); |
| 4287 |
|
| 4288 |
log::trace!("\t\t\tlooking up comparator expr {:?}", value_id); |
| 4289 |
let c_lexp_handle = get_expr_handle!( |
| 4290 |
comparator_id, |
| 4291 |
self.lookup_expression.lookup(comparator_id)? |
| 4292 |
); |
| 4293 |
|
| 4294 |
// We know from the SPIR-V spec that the result type must be an integer |
| 4295 |
// scalar, and we'll need the type itself to get a handle to the atomic |
| 4296 |
// result struct. |
| 4297 |
let crate::TypeInner::Scalar(scalar) = ctx.module.types[p_base_ty_h].inner |
| 4298 |
else { |
| 4299 |
return Err( |
| 4300 |
crate::front::atomic_upgrade::Error::CompareExchangeNonScalarBaseType |
| 4301 |
.into(), |
| 4302 |
); |
| 4303 |
}; |
| 4304 |
|
| 4305 |
// Get a handle to the atomic result struct type. |
| 4306 |
let atomic_result_struct_ty_h = ctx.module.generate_predeclared_type( |
| 4307 |
crate::PredeclaredType::AtomicCompareExchangeWeakResult(scalar), |
| 4308 |
); |
| 4309 |
|
| 4310 |
block.extend(emitter.finish(ctx.expressions)); |
| 4311 |
|
| 4312 |
// Create an expression for our atomic result |
| 4313 |
let atomic_lexp_handle = { |
| 4314 |
let expr = crate::Expression::AtomicResult { |
| 4315 |
ty: atomic_result_struct_ty_h, |
| 4316 |
comparison: true, |
| 4317 |
}; |
| 4318 |
ctx.expressions.append(expr, span) |
| 4319 |
}; |
| 4320 |
|
| 4321 |
// Create an dot accessor to extract the value from the |
| 4322 |
// result struct __atomic_compare_exchange_result<T> and use that |
| 4323 |
// as the expression for the result_id |
| 4324 |
{ |
| 4325 |
let expr = crate::Expression::AccessIndex { |
| 4326 |
base: atomic_lexp_handle, |
| 4327 |
index: 0, |
| 4328 |
}; |
| 4329 |
let handle = ctx.expressions.append(expr, span); |
| 4330 |
// Use this dot accessor as the result id's expression |
| 4331 |
let _ = self.lookup_expression.insert( |
| 4332 |
result_id, |
| 4333 |
LookupExpression { |
| 4334 |
handle, |
| 4335 |
type_id: result_type_id, |
| 4336 |
block_id, |
| 4337 |
}, |
| 4338 |
); |
| 4339 |
} |
| 4340 |
|
| 4341 |
emitter.start(ctx.expressions); |
| 4342 |
|
| 4343 |
// Create a statement for the op itself |
| 4344 |
let stmt = crate::Statement::Atomic { |
| 4345 |
pointer: p_exp_h, |
| 4346 |
fun: crate::AtomicFunction::Exchange { |
| 4347 |
compare: Some(c_lexp_handle), |
| 4348 |
}, |
| 4349 |
value: v_lexp_handle, |
| 4350 |
result: Some(atomic_lexp_handle), |
| 4351 |
}; |
| 4352 |
block.push(stmt, span); |
| 4353 |
|
| 4354 |
// Store any associated global variables so we can upgrade their types later |
| 4355 |
self.record_atomic_access(ctx, p_exp_h)?; |
| 4356 |
} |
| 4357 |
Op::AtomicExchange |
| 4358 |
| Op::AtomicIAdd |
| 4359 |
| Op::AtomicISub |
| 4360 |
| Op::AtomicSMin |
| 4361 |
| Op::AtomicUMin |
| 4362 |
| Op::AtomicSMax |
| 4363 |
| Op::AtomicUMax |
| 4364 |
| Op::AtomicAnd |
| 4365 |
| Op::AtomicOr |
| 4366 |
| Op::AtomicXor |
| 4367 |
| Op::AtomicFAddEXT => self.parse_atomic_expr_with_value( |
| 4368 |
inst, |
| 4369 |
&mut emitter, |
| 4370 |
ctx, |
| 4371 |
&mut block, |
| 4372 |
block_id, |
| 4373 |
body_idx, |
| 4374 |
match inst.op { |
| 4375 |
Op::AtomicExchange => crate::AtomicFunction::Exchange { compare: None }, |
| 4376 |
Op::AtomicIAdd | Op::AtomicFAddEXT => crate::AtomicFunction::Add, |
| 4377 |
Op::AtomicISub => crate::AtomicFunction::Subtract, |
| 4378 |
Op::AtomicSMin => crate::AtomicFunction::Min, |
| 4379 |
Op::AtomicUMin => crate::AtomicFunction::Min, |
| 4380 |
Op::AtomicSMax => crate::AtomicFunction::Max, |
| 4381 |
Op::AtomicUMax => crate::AtomicFunction::Max, |
| 4382 |
Op::AtomicAnd => crate::AtomicFunction::And, |
| 4383 |
Op::AtomicOr => crate::AtomicFunction::InclusiveOr, |
| 4384 |
Op::AtomicXor => crate::AtomicFunction::ExclusiveOr, |
| 4385 |
_ => unreachable!(), |
| 4386 |
}, |
| 4387 |
)?, |
| 4388 |
|
| 4389 |
_ => { |
| 4390 |
return Err(Error::UnsupportedInstruction(self.state, inst.op)); |
| 4391 |
} |
| 4392 |
} |
| 4393 |
}; |
| 4394 |
|
| 4395 |
block.extend(emitter.finish(ctx.expressions)); |
| 4396 |
if let Some(stmt) = terminator { |
| 4397 |
block.push(stmt, crate::Span::default()); |
| 4398 |
} |
| 4399 |
|
| 4400 |
// Save this block fragment in `block_ctx.blocks`, and mark it to be |
| 4401 |
// incorporated into the current body at `Statement` assembly time. |
| 4402 |
ctx.blocks.insert(block_id, block); |
| 4403 |
let body = &mut ctx.bodies[body_idx]; |
| 4404 |
body.data.push(BodyFragment::BlockId(block_id)); |
| 4405 |
Ok(()) |
| 4406 |
} |
| 4407 |
|
| 4408 |
fn make_expression_storage( |
| 4409 |
&mut self, |
| 4410 |
globals: &Arena<crate::GlobalVariable>, |
| 4411 |
constants: &Arena<crate::Constant>, |
| 4412 |
overrides: &Arena<crate::Override>, |
| 4413 |
) -> Arena<crate::Expression> { |
| 4414 |
let mut expressions = Arena::new(); |
| 4415 |
#[allow(clippy::panic)] |
| 4416 |
{ |
| 4417 |
assert!(self.lookup_expression.is_empty()); |
| 4418 |
} |
| 4419 |
// register global variables |
| 4420 |
for (&id, var) in self.lookup_variable.iter() { |
| 4421 |
let span = globals.get_span(var.handle); |
| 4422 |
let handle = expressions.append(crate::Expression::GlobalVariable(var.handle), span); |
| 4423 |
self.lookup_expression.insert( |
| 4424 |
id, |
| 4425 |
LookupExpression { |
| 4426 |
type_id: var.type_id, |
| 4427 |
handle, |
| 4428 |
// Setting this to an invalid id will cause get_expr_handle |
| 4429 |
// to default to the main body making sure no load/stores |
| 4430 |
// are added. |
| 4431 |
block_id: 0, |
| 4432 |
}, |
| 4433 |
); |
| 4434 |
} |
| 4435 |
// register constants |
| 4436 |
for (&id, con) in self.lookup_constant.iter() { |
| 4437 |
let (expr, span) = match con.inner { |
| 4438 |
Constant::Constant(c) => (crate::Expression::Constant(c), constants.get_span(c)), |
| 4439 |
Constant::Override(o) => (crate::Expression::Override(o), overrides.get_span(o)), |
| 4440 |
}; |
| 4441 |
let handle = expressions.append(expr, span); |
| 4442 |
self.lookup_expression.insert( |
| 4443 |
id, |
| 4444 |
LookupExpression { |
| 4445 |
type_id: con.type_id, |
| 4446 |
handle, |
| 4447 |
// Setting this to an invalid id will cause get_expr_handle |
| 4448 |
// to default to the main body making sure no load/stores |
| 4449 |
// are added. |
| 4450 |
block_id: 0, |
| 4451 |
}, |
| 4452 |
); |
| 4453 |
} |
| 4454 |
// done |
| 4455 |
expressions |
| 4456 |
} |
| 4457 |
|
| 4458 |
fn switch(&mut self, state: ModuleState, op: spirv::Op) -> Result<(), Error> { |
| 4459 |
if state < self.state { |
| 4460 |
Err(Error::UnsupportedInstruction(self.state, op)) |
| 4461 |
} else { |
| 4462 |
self.state = state; |
| 4463 |
Ok(()) |
| 4464 |
} |
| 4465 |
} |
| 4466 |
|
| 4467 |
/// Walk the statement tree and patch it in the following cases: |
| 4468 |
/// 1. Function call targets are replaced by `deferred_function_calls` map |
| 4469 |
fn patch_statements( |
| 4470 |
&mut self, |
| 4471 |
statements: &mut crate::Block, |
| 4472 |
expressions: &mut Arena<crate::Expression>, |
| 4473 |
fun_parameter_sampling: &mut [image::SamplingFlags], |
| 4474 |
) -> Result<(), Error> { |
| 4475 |
use crate::Statement as S; |
| 4476 |
let mut i = 0usize; |
| 4477 |
while i < statements.len() { |
| 4478 |
match statements[i] { |
| 4479 |
S::Emit(_) => {} |
| 4480 |
S::Block(ref mut block) => { |
| 4481 |
self.patch_statements(block, expressions, fun_parameter_sampling)?; |
| 4482 |
} |
| 4483 |
S::If { |
| 4484 |
condition: _, |
| 4485 |
ref mut accept, |
| 4486 |
ref mut reject, |
| 4487 |
} => { |
| 4488 |
self.patch_statements(reject, expressions, fun_parameter_sampling)?; |
| 4489 |
self.patch_statements(accept, expressions, fun_parameter_sampling)?; |
| 4490 |
} |
| 4491 |
S::Switch { |
| 4492 |
selector: _, |
| 4493 |
ref mut cases, |
| 4494 |
} => { |
| 4495 |
for case in cases.iter_mut() { |
| 4496 |
self.patch_statements(&mut case.body, expressions, fun_parameter_sampling)?; |
| 4497 |
} |
| 4498 |
} |
| 4499 |
S::Loop { |
| 4500 |
ref mut body, |
| 4501 |
ref mut continuing, |
| 4502 |
break_if: _, |
| 4503 |
} => { |
| 4504 |
self.patch_statements(body, expressions, fun_parameter_sampling)?; |
| 4505 |
self.patch_statements(continuing, expressions, fun_parameter_sampling)?; |
| 4506 |
} |
| 4507 |
S::Break |
| 4508 |
| S::Continue |
| 4509 |
| S::Return { .. } |
| 4510 |
| S::Kill |
| 4511 |
| S::Barrier(_) |
| 4512 |
| S::Store { .. } |
| 4513 |
| S::ImageStore { .. } |
| 4514 |
| S::Atomic { .. } |
| 4515 |
| S::ImageAtomic { .. } |
| 4516 |
| S::RayQuery { .. } |
| 4517 |
| S::SubgroupBallot { .. } |
| 4518 |
| S::SubgroupCollectiveOperation { .. } |
| 4519 |
| S::SubgroupGather { .. } => {} |
| 4520 |
S::Call { |
| 4521 |
function: ref mut callee, |
| 4522 |
ref arguments, |
| 4523 |
.. |
| 4524 |
} => { |
| 4525 |
let fun_id = self.deferred_function_calls[callee.index()]; |
| 4526 |
let fun_lookup = self.lookup_function.lookup(fun_id)?; |
| 4527 |
*callee = fun_lookup.handle; |
| 4528 |
|
| 4529 |
// Patch sampling flags |
| 4530 |
for (arg_index, arg) in arguments.iter().enumerate() { |
| 4531 |
let flags = match fun_lookup.parameters_sampling.get(arg_index) { |
| 4532 |
Some(&flags) if !flags.is_empty() => flags, |
| 4533 |
_ => continue, |
| 4534 |
}; |
| 4535 |
|
| 4536 |
match expressions[*arg] { |
| 4537 |
crate::Expression::GlobalVariable(handle) => { |
| 4538 |
if let Some(sampling) = self.handle_sampling.get_mut(&handle) { |
| 4539 |
*sampling |= flags |
| 4540 |
} |
| 4541 |
} |
| 4542 |
crate::Expression::FunctionArgument(i) => { |
| 4543 |
fun_parameter_sampling[i as usize] |= flags; |
| 4544 |
} |
| 4545 |
ref other => return Err(Error::InvalidGlobalVar(other.clone())), |
| 4546 |
} |
| 4547 |
} |
| 4548 |
} |
| 4549 |
S::WorkGroupUniformLoad { .. } => unreachable!(), |
| 4550 |
} |
| 4551 |
i += 1; |
| 4552 |
} |
| 4553 |
Ok(()) |
| 4554 |
} |
| 4555 |
|
| 4556 |
fn patch_function( |
| 4557 |
&mut self, |
| 4558 |
handle: Option<Handle<crate::Function>>, |
| 4559 |
fun: &mut crate::Function, |
| 4560 |
) -> Result<(), Error> { |
| 4561 |
// Note: this search is a bit unfortunate |
| 4562 |
let (fun_id, mut parameters_sampling) = match handle { |
| 4563 |
Some(h) => { |
| 4564 |
let (&fun_id, lookup) = self |
| 4565 |
.lookup_function |
| 4566 |
.iter_mut() |
| 4567 |
.find(|&(_, ref lookup)| lookup.handle == h) |
| 4568 |
.unwrap(); |
| 4569 |
(fun_id, mem::take(&mut lookup.parameters_sampling)) |
| 4570 |
} |
| 4571 |
None => (0, Vec::new()), |
| 4572 |
}; |
| 4573 |
|
| 4574 |
for (_, expr) in fun.expressions.iter_mut() { |
| 4575 |
if let crate::Expression::CallResult(ref mut function) = *expr { |
| 4576 |
let fun_id = self.deferred_function_calls[function.index()]; |
| 4577 |
*function = self.lookup_function.lookup(fun_id)?.handle; |
| 4578 |
} |
| 4579 |
} |
| 4580 |
|
| 4581 |
self.patch_statements( |
| 4582 |
&mut fun.body, |
| 4583 |
&mut fun.expressions, |
| 4584 |
&mut parameters_sampling, |
| 4585 |
)?; |
| 4586 |
|
| 4587 |
if let Some(lookup) = self.lookup_function.get_mut(&fun_id) { |
| 4588 |
lookup.parameters_sampling = parameters_sampling; |
| 4589 |
} |
| 4590 |
Ok(()) |
| 4591 |
} |
| 4592 |
|
| 4593 |
pub fn parse(mut self) -> Result<crate::Module, Error> { |
| 4594 |
let mut module = { |
| 4595 |
if self.next()? != spirv::MAGIC_NUMBER { |
| 4596 |
return Err(Error::InvalidHeader); |
| 4597 |
} |
| 4598 |
let version_raw = self.next()?; |
| 4599 |
let generator = self.next()?; |
| 4600 |
let _bound = self.next()?; |
| 4601 |
let _schema = self.next()?; |
| 4602 |
log::info!("Generated by {} version {:x}", generator, version_raw); |
| 4603 |
crate::Module::default() |
| 4604 |
}; |
| 4605 |
|
| 4606 |
self.layouter.clear(); |
| 4607 |
self.dummy_functions = Arena::new(); |
| 4608 |
self.lookup_function.clear(); |
| 4609 |
self.function_call_graph.clear(); |
| 4610 |
|
| 4611 |
loop { |
| 4612 |
use spirv::Op; |
| 4613 |
|
| 4614 |
let inst = match self.next_inst() { |
| 4615 |
Ok(inst) => inst, |
| 4616 |
Err(Error::IncompleteData) => break, |
| 4617 |
Err(other) => return Err(other), |
| 4618 |
}; |
| 4619 |
log::debug!("\t{:?} [{}]", inst.op, inst.wc); |
| 4620 |
|
| 4621 |
match inst.op { |
| 4622 |
Op::Capability => self.parse_capability(inst), |
| 4623 |
Op::Extension => self.parse_extension(inst), |
| 4624 |
Op::ExtInstImport => self.parse_ext_inst_import(inst), |
| 4625 |
Op::MemoryModel => self.parse_memory_model(inst), |
| 4626 |
Op::EntryPoint => self.parse_entry_point(inst), |
| 4627 |
Op::ExecutionMode => self.parse_execution_mode(inst), |
| 4628 |
Op::String => self.parse_string(inst), |
| 4629 |
Op::Source => self.parse_source(inst), |
| 4630 |
Op::SourceExtension => self.parse_source_extension(inst), |
| 4631 |
Op::Name => self.parse_name(inst), |
| 4632 |
Op::MemberName => self.parse_member_name(inst), |
| 4633 |
Op::ModuleProcessed => self.parse_module_processed(inst), |
| 4634 |
Op::Decorate => self.parse_decorate(inst), |
| 4635 |
Op::MemberDecorate => self.parse_member_decorate(inst), |
| 4636 |
Op::TypeVoid => self.parse_type_void(inst), |
| 4637 |
Op::TypeBool => self.parse_type_bool(inst, &mut module), |
| 4638 |
Op::TypeInt => self.parse_type_int(inst, &mut module), |
| 4639 |
Op::TypeFloat => self.parse_type_float(inst, &mut module), |
| 4640 |
Op::TypeVector => self.parse_type_vector(inst, &mut module), |
| 4641 |
Op::TypeMatrix => self.parse_type_matrix(inst, &mut module), |
| 4642 |
Op::TypeFunction => self.parse_type_function(inst), |
| 4643 |
Op::TypePointer => self.parse_type_pointer(inst, &mut module), |
| 4644 |
Op::TypeArray => self.parse_type_array(inst, &mut module), |
| 4645 |
Op::TypeRuntimeArray => self.parse_type_runtime_array(inst, &mut module), |
| 4646 |
Op::TypeStruct => self.parse_type_struct(inst, &mut module), |
| 4647 |
Op::TypeImage => self.parse_type_image(inst, &mut module), |
| 4648 |
Op::TypeSampledImage => self.parse_type_sampled_image(inst), |
| 4649 |
Op::TypeSampler => self.parse_type_sampler(inst, &mut module), |
| 4650 |
Op::Constant | Op::SpecConstant => self.parse_constant(inst, &mut module), |
| 4651 |
Op::ConstantComposite | Op::SpecConstantComposite => { |
| 4652 |
self.parse_composite_constant(inst, &mut module) |
| 4653 |
} |
| 4654 |
Op::ConstantNull | Op::Undef => self.parse_null_constant(inst, &mut module), |
| 4655 |
Op::ConstantTrue | Op::SpecConstantTrue => { |
| 4656 |
self.parse_bool_constant(inst, true, &mut module) |
| 4657 |
} |
| 4658 |
Op::ConstantFalse | Op::SpecConstantFalse => { |
| 4659 |
self.parse_bool_constant(inst, false, &mut module) |
| 4660 |
} |
| 4661 |
Op::Variable => self.parse_global_variable(inst, &mut module), |
| 4662 |
Op::Function => { |
| 4663 |
self.switch(ModuleState::Function, inst.op)?; |
| 4664 |
inst.expect(5)?; |
| 4665 |
self.parse_function(&mut module) |
| 4666 |
} |
| 4667 |
_ => Err(Error::UnsupportedInstruction(self.state, inst.op)), //TODO |
| 4668 |
}?; |
| 4669 |
} |
| 4670 |
|
| 4671 |
if !self.upgrade_atomics.is_empty() { |
| 4672 |
log::info!("Upgrading atomic pointers..."); |
| 4673 |
module.upgrade_atomics(&self.upgrade_atomics)?; |
| 4674 |
} |
| 4675 |
|
| 4676 |
// Do entry point specific processing after all functions are parsed so that we can |
| 4677 |
// cull unused problematic builtins of gl_PerVertex. |
| 4678 |
for (ep, fun_id) in mem::take(&mut self.deferred_entry_points) { |
| 4679 |
self.process_entry_point(&mut module, ep, fun_id)?; |
| 4680 |
} |
| 4681 |
|
| 4682 |
log::info!("Patching..."); |
| 4683 |
{ |
| 4684 |
let mut nodes = petgraph::algo::toposort(&self.function_call_graph, None) |
| 4685 |
.map_err(|cycle| Error::FunctionCallCycle(cycle.node_id()))?; |
| 4686 |
nodes.reverse(); // we need dominated first |
| 4687 |
let mut functions = mem::take(&mut module.functions); |
| 4688 |
for fun_id in nodes { |
| 4689 |
if fun_id > !(functions.len() as u32) { |
| 4690 |
// skip all the fake IDs registered for the entry points |
| 4691 |
continue; |
| 4692 |
} |
| 4693 |
let lookup = self.lookup_function.get_mut(&fun_id).unwrap(); |
| 4694 |
// take out the function from the old array |
| 4695 |
let fun = mem::take(&mut functions[lookup.handle]); |
| 4696 |
// add it to the newly formed arena, and adjust the lookup |
| 4697 |
lookup.handle = module |
| 4698 |
.functions |
| 4699 |
.append(fun, functions.get_span(lookup.handle)); |
| 4700 |
} |
| 4701 |
} |
| 4702 |
// patch all the functions |
| 4703 |
for (handle, fun) in module.functions.iter_mut() { |
| 4704 |
self.patch_function(Some(handle), fun)?; |
| 4705 |
} |
| 4706 |
for ep in module.entry_points.iter_mut() { |
| 4707 |
self.patch_function(None, &mut ep.function)?; |
| 4708 |
} |
| 4709 |
|
| 4710 |
// Check all the images and samplers to have consistent comparison property. |
| 4711 |
for (handle, flags) in self.handle_sampling.drain() { |
| 4712 |
if !image::patch_comparison_type( |
| 4713 |
flags, |
| 4714 |
module.global_variables.get_mut(handle), |
| 4715 |
&mut module.types, |
| 4716 |
) { |
| 4717 |
return Err(Error::InconsistentComparisonSampling(handle)); |
| 4718 |
} |
| 4719 |
} |
| 4720 |
|
| 4721 |
if !self.future_decor.is_empty() { |
| 4722 |
log::warn!("Unused item decorations: {:?}", self.future_decor); |
| 4723 |
self.future_decor.clear(); |
| 4724 |
} |
| 4725 |
if !self.future_member_decor.is_empty() { |
| 4726 |
log::warn!("Unused member decorations: {:?}", self.future_member_decor); |
| 4727 |
self.future_member_decor.clear(); |
| 4728 |
} |
| 4729 |
|
| 4730 |
Ok(module) |
| 4731 |
} |
| 4732 |
|
| 4733 |
fn parse_capability(&mut self, inst: Instruction) -> Result<(), Error> { |
| 4734 |
self.switch(ModuleState::Capability, inst.op)?; |
| 4735 |
inst.expect(2)?; |
| 4736 |
let capability = self.next()?; |
| 4737 |
let cap = |
| 4738 |
spirv::Capability::from_u32(capability).ok_or(Error::UnknownCapability(capability))?; |
| 4739 |
if !SUPPORTED_CAPABILITIES.contains(&cap) { |
| 4740 |
if self.options.strict_capabilities { |
| 4741 |
return Err(Error::UnsupportedCapability(cap)); |
| 4742 |
} else { |
| 4743 |
log::warn!("Unknown capability {:?}", cap); |
| 4744 |
} |
| 4745 |
} |
| 4746 |
Ok(()) |
| 4747 |
} |
| 4748 |
|
| 4749 |
fn parse_extension(&mut self, inst: Instruction) -> Result<(), Error> { |
| 4750 |
self.switch(ModuleState::Extension, inst.op)?; |
| 4751 |
inst.expect_at_least(2)?; |
| 4752 |
let (name, left) = self.next_string(inst.wc - 1)?; |
| 4753 |
if left != 0 { |
| 4754 |
return Err(Error::InvalidOperand); |
| 4755 |
} |
| 4756 |
if !SUPPORTED_EXTENSIONS.contains(&name.as_str()) { |
| 4757 |
return Err(Error::UnsupportedExtension(name)); |
| 4758 |
} |
| 4759 |
Ok(()) |
| 4760 |
} |
| 4761 |
|
| 4762 |
fn parse_ext_inst_import(&mut self, inst: Instruction) -> Result<(), Error> { |
| 4763 |
self.switch(ModuleState::Extension, inst.op)?; |
| 4764 |
inst.expect_at_least(3)?; |
| 4765 |
let result_id = self.next()?; |
| 4766 |
let (name, left) = self.next_string(inst.wc - 2)?; |
| 4767 |
if left != 0 { |
| 4768 |
return Err(Error::InvalidOperand); |
| 4769 |
} |
| 4770 |
if !SUPPORTED_EXT_SETS.contains(&name.as_str()) { |
| 4771 |
return Err(Error::UnsupportedExtSet(name)); |
| 4772 |
} |
| 4773 |
self.ext_glsl_id = Some(result_id); |
| 4774 |
Ok(()) |
| 4775 |
} |
| 4776 |
|
| 4777 |
fn parse_memory_model(&mut self, inst: Instruction) -> Result<(), Error> { |
| 4778 |
self.switch(ModuleState::MemoryModel, inst.op)?; |
| 4779 |
inst.expect(3)?; |
| 4780 |
let _addressing_model = self.next()?; |
| 4781 |
let _memory_model = self.next()?; |
| 4782 |
Ok(()) |
| 4783 |
} |
| 4784 |
|
| 4785 |
fn parse_entry_point(&mut self, inst: Instruction) -> Result<(), Error> { |
| 4786 |
self.switch(ModuleState::EntryPoint, inst.op)?; |
| 4787 |
inst.expect_at_least(4)?; |
| 4788 |
let exec_model = self.next()?; |
| 4789 |
let exec_model = spirv::ExecutionModel::from_u32(exec_model) |
| 4790 |
.ok_or(Error::UnsupportedExecutionModel(exec_model))?; |
| 4791 |
let function_id = self.next()?; |
| 4792 |
let (name, left) = self.next_string(inst.wc - 3)?; |
| 4793 |
let ep = EntryPoint { |
| 4794 |
stage: match exec_model { |
| 4795 |
spirv::ExecutionModel::Vertex => crate::ShaderStage::Vertex, |
| 4796 |
spirv::ExecutionModel::Fragment => crate::ShaderStage::Fragment, |
| 4797 |
spirv::ExecutionModel::GLCompute => crate::ShaderStage::Compute, |
| 4798 |
_ => return Err(Error::UnsupportedExecutionModel(exec_model as u32)), |
| 4799 |
}, |
| 4800 |
name, |
| 4801 |
early_depth_test: None, |
| 4802 |
workgroup_size: [0; 3], |
| 4803 |
variable_ids: self.data.by_ref().take(left as usize).collect(), |
| 4804 |
}; |
| 4805 |
self.lookup_entry_point.insert(function_id, ep); |
| 4806 |
Ok(()) |
| 4807 |
} |
| 4808 |
|
| 4809 |
fn parse_execution_mode(&mut self, inst: Instruction) -> Result<(), Error> { |
| 4810 |
use spirv::ExecutionMode; |
| 4811 |
|
| 4812 |
self.switch(ModuleState::ExecutionMode, inst.op)?; |
| 4813 |
inst.expect_at_least(3)?; |
| 4814 |
|
| 4815 |
let ep_id = self.next()?; |
| 4816 |
let mode_id = self.next()?; |
| 4817 |
let args: Vec<spirv::Word> = self.data.by_ref().take(inst.wc as usize - 3).collect(); |
| 4818 |
|
| 4819 |
let ep = self |
| 4820 |
.lookup_entry_point |
| 4821 |
.get_mut(&ep_id) |
| 4822 |
.ok_or(Error::InvalidId(ep_id))?; |
| 4823 |
let mode = |
| 4824 |
ExecutionMode::from_u32(mode_id).ok_or(Error::UnsupportedExecutionMode(mode_id))?; |
| 4825 |
|
| 4826 |
match mode { |
| 4827 |
ExecutionMode::EarlyFragmentTests => { |
| 4828 |
if ep.early_depth_test.is_none() { |
| 4829 |
ep.early_depth_test = Some(crate::EarlyDepthTest { conservative: None }); |
| 4830 |
} |
| 4831 |
} |
| 4832 |
ExecutionMode::DepthUnchanged => { |
| 4833 |
ep.early_depth_test = Some(crate::EarlyDepthTest { |
| 4834 |
conservative: Some(crate::ConservativeDepth::Unchanged), |
| 4835 |
}); |
| 4836 |
} |
| 4837 |
ExecutionMode::DepthGreater => { |
| 4838 |
ep.early_depth_test = Some(crate::EarlyDepthTest { |
| 4839 |
conservative: Some(crate::ConservativeDepth::GreaterEqual), |
| 4840 |
}); |
| 4841 |
} |
| 4842 |
ExecutionMode::DepthLess => { |
| 4843 |
ep.early_depth_test = Some(crate::EarlyDepthTest { |
| 4844 |
conservative: Some(crate::ConservativeDepth::LessEqual), |
| 4845 |
}); |
| 4846 |
} |
| 4847 |
ExecutionMode::DepthReplacing => { |
| 4848 |
// Ignored because it can be deduced from the IR. |
| 4849 |
} |
| 4850 |
ExecutionMode::OriginUpperLeft => { |
| 4851 |
// Ignored because the other option (OriginLowerLeft) is not valid in Vulkan mode. |
| 4852 |
} |
| 4853 |
ExecutionMode::LocalSize => { |
| 4854 |
ep.workgroup_size = [args[0], args[1], args[2]]; |
| 4855 |
} |
| 4856 |
_ => { |
| 4857 |
return Err(Error::UnsupportedExecutionMode(mode_id)); |
| 4858 |
} |
| 4859 |
} |
| 4860 |
|
| 4861 |
Ok(()) |
| 4862 |
} |
| 4863 |
|
| 4864 |
fn parse_string(&mut self, inst: Instruction) -> Result<(), Error> { |
| 4865 |
self.switch(ModuleState::Source, inst.op)?; |
| 4866 |
inst.expect_at_least(3)?; |
| 4867 |
let _id = self.next()?; |
| 4868 |
let (_name, _) = self.next_string(inst.wc - 2)?; |
| 4869 |
Ok(()) |
| 4870 |
} |
| 4871 |
|
| 4872 |
fn parse_source(&mut self, inst: Instruction) -> Result<(), Error> { |
| 4873 |
self.switch(ModuleState::Source, inst.op)?; |
| 4874 |
for _ in 1..inst.wc { |
| 4875 |
let _ = self.next()?; |
| 4876 |
} |
| 4877 |
Ok(()) |
| 4878 |
} |
| 4879 |
|
| 4880 |
fn parse_source_extension(&mut self, inst: Instruction) -> Result<(), Error> { |
| 4881 |
self.switch(ModuleState::Source, inst.op)?; |
| 4882 |
inst.expect_at_least(2)?; |
| 4883 |
let (_name, _) = self.next_string(inst.wc - 1)?; |
| 4884 |
Ok(()) |
| 4885 |
} |
| 4886 |
|
| 4887 |
fn parse_name(&mut self, inst: Instruction) -> Result<(), Error> { |
| 4888 |
self.switch(ModuleState::Name, inst.op)?; |
| 4889 |
inst.expect_at_least(3)?; |
| 4890 |
let id = self.next()?; |
| 4891 |
let (name, left) = self.next_string(inst.wc - 2)?; |
| 4892 |
if left != 0 { |
| 4893 |
return Err(Error::InvalidOperand); |
| 4894 |
} |
| 4895 |
self.future_decor.entry(id).or_default().name = Some(name); |
| 4896 |
Ok(()) |
| 4897 |
} |
| 4898 |
|
| 4899 |
fn parse_member_name(&mut self, inst: Instruction) -> Result<(), Error> { |
| 4900 |
self.switch(ModuleState::Name, inst.op)?; |
| 4901 |
inst.expect_at_least(4)?; |
| 4902 |
let id = self.next()?; |
| 4903 |
let member = self.next()?; |
| 4904 |
let (name, left) = self.next_string(inst.wc - 3)?; |
| 4905 |
if left != 0 { |
| 4906 |
return Err(Error::InvalidOperand); |
| 4907 |
} |
| 4908 |
|
| 4909 |
self.future_member_decor |
| 4910 |
.entry((id, member)) |
| 4911 |
.or_default() |
| 4912 |
.name = Some(name); |
| 4913 |
Ok(()) |
| 4914 |
} |
| 4915 |
|
| 4916 |
fn parse_module_processed(&mut self, inst: Instruction) -> Result<(), Error> { |
| 4917 |
self.switch(ModuleState::Name, inst.op)?; |
| 4918 |
inst.expect_at_least(2)?; |
| 4919 |
let (_info, left) = self.next_string(inst.wc - 1)?; |
| 4920 |
//Note: string is ignored |
| 4921 |
if left != 0 { |
| 4922 |
return Err(Error::InvalidOperand); |
| 4923 |
} |
| 4924 |
Ok(()) |
| 4925 |
} |
| 4926 |
|
| 4927 |
fn parse_decorate(&mut self, inst: Instruction) -> Result<(), Error> { |
| 4928 |
self.switch(ModuleState::Annotation, inst.op)?; |
| 4929 |
inst.expect_at_least(3)?; |
| 4930 |
let id = self.next()?; |
| 4931 |
let mut dec = self.future_decor.remove(&id).unwrap_or_default(); |
| 4932 |
self.next_decoration(inst, 2, &mut dec)?; |
| 4933 |
self.future_decor.insert(id, dec); |
| 4934 |
Ok(()) |
| 4935 |
} |
| 4936 |
|
| 4937 |
fn parse_member_decorate(&mut self, inst: Instruction) -> Result<(), Error> { |
| 4938 |
self.switch(ModuleState::Annotation, inst.op)?; |
| 4939 |
inst.expect_at_least(4)?; |
| 4940 |
let id = self.next()?; |
| 4941 |
let member = self.next()?; |
| 4942 |
|
| 4943 |
let mut dec = self |
| 4944 |
.future_member_decor |
| 4945 |
.remove(&(id, member)) |
| 4946 |
.unwrap_or_default(); |
| 4947 |
self.next_decoration(inst, 3, &mut dec)?; |
| 4948 |
self.future_member_decor.insert((id, member), dec); |
| 4949 |
Ok(()) |
| 4950 |
} |
| 4951 |
|
| 4952 |
fn parse_type_void(&mut self, inst: Instruction) -> Result<(), Error> { |
| 4953 |
self.switch(ModuleState::Type, inst.op)?; |
| 4954 |
inst.expect(2)?; |
| 4955 |
let id = self.next()?; |
| 4956 |
self.lookup_void_type = Some(id); |
| 4957 |
Ok(()) |
| 4958 |
} |
| 4959 |
|
| 4960 |
fn parse_type_bool( |
| 4961 |
&mut self, |
| 4962 |
inst: Instruction, |
| 4963 |
module: &mut crate::Module, |
| 4964 |
) -> Result<(), Error> { |
| 4965 |
let start = self.data_offset; |
| 4966 |
self.switch(ModuleState::Type, inst.op)?; |
| 4967 |
inst.expect(2)?; |
| 4968 |
let id = self.next()?; |
| 4969 |
let inner = crate::TypeInner::Scalar(crate::Scalar::BOOL); |
| 4970 |
self.lookup_type.insert( |
| 4971 |
id, |
| 4972 |
LookupType { |
| 4973 |
handle: module.types.insert( |
| 4974 |
crate::Type { |
| 4975 |
name: self.future_decor.remove(&id).and_then(|dec| dec.name), |
| 4976 |
inner, |
| 4977 |
}, |
| 4978 |
self.span_from_with_op(start), |
| 4979 |
), |
| 4980 |
base_id: None, |
| 4981 |
}, |
| 4982 |
); |
| 4983 |
Ok(()) |
| 4984 |
} |
| 4985 |
|
| 4986 |
fn parse_type_int( |
| 4987 |
&mut self, |
| 4988 |
inst: Instruction, |
| 4989 |
module: &mut crate::Module, |
| 4990 |
) -> Result<(), Error> { |
| 4991 |
let start = self.data_offset; |
| 4992 |
self.switch(ModuleState::Type, inst.op)?; |
| 4993 |
inst.expect(4)?; |
| 4994 |
let id = self.next()?; |
| 4995 |
let width = self.next()?; |
| 4996 |
let sign = self.next()?; |
| 4997 |
let inner = crate::TypeInner::Scalar(crate::Scalar { |
| 4998 |
kind: match sign { |
| 4999 |
0 => crate::ScalarKind::Uint, |
| 5000 |
1 => crate::ScalarKind::Sint, |
| 5001 |
_ => return Err(Error::InvalidSign(sign)), |
| 5002 |
}, |
| 5003 |
width: map_width(width)?, |
| 5004 |
}); |
| 5005 |
self.lookup_type.insert( |
| 5006 |
id, |
| 5007 |
LookupType { |
| 5008 |
handle: module.types.insert( |
| 5009 |
crate::Type { |
| 5010 |
name: self.future_decor.remove(&id).and_then(|dec| dec.name), |
| 5011 |
inner, |
| 5012 |
}, |
| 5013 |
self.span_from_with_op(start), |
| 5014 |
), |
| 5015 |
base_id: None, |
| 5016 |
}, |
| 5017 |
); |
| 5018 |
Ok(()) |
| 5019 |
} |
| 5020 |
|
| 5021 |
fn parse_type_float( |
| 5022 |
&mut self, |
| 5023 |
inst: Instruction, |
| 5024 |
module: &mut crate::Module, |
| 5025 |
) -> Result<(), Error> { |
| 5026 |
let start = self.data_offset; |
| 5027 |
self.switch(ModuleState::Type, inst.op)?; |
| 5028 |
inst.expect(3)?; |
| 5029 |
let id = self.next()?; |
| 5030 |
let width = self.next()?; |
| 5031 |
let inner = crate::TypeInner::Scalar(crate::Scalar::float(map_width(width)?)); |
| 5032 |
self.lookup_type.insert( |
| 5033 |
id, |
| 5034 |
LookupType { |
| 5035 |
handle: module.types.insert( |
| 5036 |
crate::Type { |
| 5037 |
name: self.future_decor.remove(&id).and_then(|dec| dec.name), |
| 5038 |
inner, |
| 5039 |
}, |
| 5040 |
self.span_from_with_op(start), |
| 5041 |
), |
| 5042 |
base_id: None, |
| 5043 |
}, |
| 5044 |
); |
| 5045 |
Ok(()) |
| 5046 |
} |
| 5047 |
|
| 5048 |
fn parse_type_vector( |
| 5049 |
&mut self, |
| 5050 |
inst: Instruction, |
| 5051 |
module: &mut crate::Module, |
| 5052 |
) -> Result<(), Error> { |
| 5053 |
let start = self.data_offset; |
| 5054 |
self.switch(ModuleState::Type, inst.op)?; |
| 5055 |
inst.expect(4)?; |
| 5056 |
let id = self.next()?; |
| 5057 |
let type_id = self.next()?; |
| 5058 |
let type_lookup = self.lookup_type.lookup(type_id)?; |
| 5059 |
let scalar = match module.types[type_lookup.handle].inner { |
| 5060 |
crate::TypeInner::Scalar(scalar) => scalar, |
| 5061 |
_ => return Err(Error::InvalidInnerType(type_id)), |
| 5062 |
}; |
| 5063 |
let component_count = self.next()?; |
| 5064 |
let inner = crate::TypeInner::Vector { |
| 5065 |
size: map_vector_size(component_count)?, |
| 5066 |
scalar, |
| 5067 |
}; |
| 5068 |
self.lookup_type.insert( |
| 5069 |
id, |
| 5070 |
LookupType { |
| 5071 |
handle: module.types.insert( |
| 5072 |
crate::Type { |
| 5073 |
name: self.future_decor.remove(&id).and_then(|dec| dec.name), |
| 5074 |
inner, |
| 5075 |
}, |
| 5076 |
self.span_from_with_op(start), |
| 5077 |
), |
| 5078 |
base_id: Some(type_id), |
| 5079 |
}, |
| 5080 |
); |
| 5081 |
Ok(()) |
| 5082 |
} |
| 5083 |
|
| 5084 |
fn parse_type_matrix( |
| 5085 |
&mut self, |
| 5086 |
inst: Instruction, |
| 5087 |
module: &mut crate::Module, |
| 5088 |
) -> Result<(), Error> { |
| 5089 |
let start = self.data_offset; |
| 5090 |
self.switch(ModuleState::Type, inst.op)?; |
| 5091 |
inst.expect(4)?; |
| 5092 |
let id = self.next()?; |
| 5093 |
let vector_type_id = self.next()?; |
| 5094 |
let num_columns = self.next()?; |
| 5095 |
let decor = self.future_decor.remove(&id); |
| 5096 |
|
| 5097 |
let vector_type_lookup = self.lookup_type.lookup(vector_type_id)?; |
| 5098 |
let inner = match module.types[vector_type_lookup.handle].inner { |
| 5099 |
crate::TypeInner::Vector { size, scalar } => crate::TypeInner::Matrix { |
| 5100 |
columns: map_vector_size(num_columns)?, |
| 5101 |
rows: size, |
| 5102 |
scalar, |
| 5103 |
}, |
| 5104 |
_ => return Err(Error::InvalidInnerType(vector_type_id)), |
| 5105 |
}; |
| 5106 |
|
| 5107 |
self.lookup_type.insert( |
| 5108 |
id, |
| 5109 |
LookupType { |
| 5110 |
handle: module.types.insert( |
| 5111 |
crate::Type { |
| 5112 |
name: decor.and_then(|dec| dec.name), |
| 5113 |
inner, |
| 5114 |
}, |
| 5115 |
self.span_from_with_op(start), |
| 5116 |
), |
| 5117 |
base_id: Some(vector_type_id), |
| 5118 |
}, |
| 5119 |
); |
| 5120 |
Ok(()) |
| 5121 |
} |
| 5122 |
|
| 5123 |
fn parse_type_function(&mut self, inst: Instruction) -> Result<(), Error> { |
| 5124 |
self.switch(ModuleState::Type, inst.op)?; |
| 5125 |
inst.expect_at_least(3)?; |
| 5126 |
let id = self.next()?; |
| 5127 |
let return_type_id = self.next()?; |
| 5128 |
let parameter_type_ids = self.data.by_ref().take(inst.wc as usize - 3).collect(); |
| 5129 |
self.lookup_function_type.insert( |
| 5130 |
id, |
| 5131 |
LookupFunctionType { |
| 5132 |
parameter_type_ids, |
| 5133 |
return_type_id, |
| 5134 |
}, |
| 5135 |
); |
| 5136 |
Ok(()) |
| 5137 |
} |
| 5138 |
|
| 5139 |
fn parse_type_pointer( |
| 5140 |
&mut self, |
| 5141 |
inst: Instruction, |
| 5142 |
module: &mut crate::Module, |
| 5143 |
) -> Result<(), Error> { |
| 5144 |
let start = self.data_offset; |
| 5145 |
self.switch(ModuleState::Type, inst.op)?; |
| 5146 |
inst.expect(4)?; |
| 5147 |
let id = self.next()?; |
| 5148 |
let storage_class = self.next()?; |
| 5149 |
let type_id = self.next()?; |
| 5150 |
|
| 5151 |
let decor = self.future_decor.remove(&id); |
| 5152 |
let base_lookup_ty = self.lookup_type.lookup(type_id)?; |
| 5153 |
let base_inner = &module.types[base_lookup_ty.handle].inner; |
| 5154 |
|
| 5155 |
let space = if let Some(space) = base_inner.pointer_space() { |
| 5156 |
space |
| 5157 |
} else if self |
| 5158 |
.lookup_storage_buffer_types |
| 5159 |
.contains_key(&base_lookup_ty.handle) |
| 5160 |
{ |
| 5161 |
crate::AddressSpace::Storage { |
| 5162 |
access: crate::StorageAccess::default(), |
| 5163 |
} |
| 5164 |
} else { |
| 5165 |
match map_storage_class(storage_class)? { |
| 5166 |
ExtendedClass::Global(space) => space, |
| 5167 |
ExtendedClass::Input | ExtendedClass::Output => crate::AddressSpace::Private, |
| 5168 |
} |
| 5169 |
}; |
| 5170 |
|
| 5171 |
// We don't support pointers to runtime-sized arrays in the `Uniform` |
| 5172 |
// storage class with the `BufferBlock` decoration. Runtime-sized arrays |
| 5173 |
// should be in the StorageBuffer class. |
| 5174 |
if let crate::TypeInner::Array { |
| 5175 |
size: crate::ArraySize::Dynamic, |
| 5176 |
.. |
| 5177 |
} = *base_inner |
| 5178 |
{ |
| 5179 |
match space { |
| 5180 |
crate::AddressSpace::Storage { .. } => {} |
| 5181 |
_ => { |
| 5182 |
return Err(Error::UnsupportedRuntimeArrayStorageClass); |
| 5183 |
} |
| 5184 |
} |
| 5185 |
} |
| 5186 |
|
| 5187 |
// Don't bother with pointer stuff for `Handle` types. |
| 5188 |
let lookup_ty = if space == crate::AddressSpace::Handle { |
| 5189 |
base_lookup_ty.clone() |
| 5190 |
} else { |
| 5191 |
LookupType { |
| 5192 |
handle: module.types.insert( |
| 5193 |
crate::Type { |
| 5194 |
name: decor.and_then(|dec| dec.name), |
| 5195 |
inner: crate::TypeInner::Pointer { |
| 5196 |
base: base_lookup_ty.handle, |
| 5197 |
space, |
| 5198 |
}, |
| 5199 |
}, |
| 5200 |
self.span_from_with_op(start), |
| 5201 |
), |
| 5202 |
base_id: Some(type_id), |
| 5203 |
} |
| 5204 |
}; |
| 5205 |
self.lookup_type.insert(id, lookup_ty); |
| 5206 |
Ok(()) |
| 5207 |
} |
| 5208 |
|
| 5209 |
fn parse_type_array( |
| 5210 |
&mut self, |
| 5211 |
inst: Instruction, |
| 5212 |
module: &mut crate::Module, |
| 5213 |
) -> Result<(), Error> { |
| 5214 |
let start = self.data_offset; |
| 5215 |
self.switch(ModuleState::Type, inst.op)?; |
| 5216 |
inst.expect(4)?; |
| 5217 |
let id = self.next()?; |
| 5218 |
let type_id = self.next()?; |
| 5219 |
let length_id = self.next()?; |
| 5220 |
let length_const = self.lookup_constant.lookup(length_id)?; |
| 5221 |
|
| 5222 |
let size = resolve_constant(module.to_ctx(), &length_const.inner) |
| 5223 |
.and_then(NonZeroU32::new) |
| 5224 |
.ok_or(Error::InvalidArraySize(length_id))?; |
| 5225 |
|
| 5226 |
let decor = self.future_decor.remove(&id).unwrap_or_default(); |
| 5227 |
let base = self.lookup_type.lookup(type_id)?.handle; |
| 5228 |
|
| 5229 |
self.layouter.update(module.to_ctx()).unwrap(); |
| 5230 |
|
| 5231 |
// HACK if the underlying type is an image or a sampler, let's assume |
| 5232 |
// that we're dealing with a binding-array |
| 5233 |
// |
| 5234 |
// Note that it's not a strictly correct assumption, but rather a trade |
| 5235 |
// off caused by an impedance mismatch between SPIR-V's and Naga's type |
| 5236 |
// systems - Naga distinguishes between arrays and binding-arrays via |
| 5237 |
// types (i.e. both kinds of arrays are just different types), while |
| 5238 |
// SPIR-V distinguishes between them through usage - e.g. given: |
| 5239 |
// |
| 5240 |
// ``` |
| 5241 |
// %image = OpTypeImage %float 2D 2 0 0 2 Rgba16f |
| 5242 |
// %uint_256 = OpConstant %uint 256 |
| 5243 |
// %image_array = OpTypeArray %image %uint_256 |
| 5244 |
// ``` |
| 5245 |
// |
| 5246 |
// ``` |
| 5247 |
// %image = OpTypeImage %float 2D 2 0 0 2 Rgba16f |
| 5248 |
// %uint_256 = OpConstant %uint 256 |
| 5249 |
// %image_array = OpTypeArray %image %uint_256 |
| 5250 |
// %image_array_ptr = OpTypePointer UniformConstant %image_array |
| 5251 |
// ``` |
| 5252 |
// |
| 5253 |
// ... in the first case, `%image_array` should technically correspond |
| 5254 |
// to `TypeInner::Array`, while in the second case it should say |
| 5255 |
// `TypeInner::BindingArray` (kinda, depending on whether `%image_array` |
| 5256 |
// is ever used as a freestanding type or rather always through the |
| 5257 |
// pointer-indirection). |
| 5258 |
// |
| 5259 |
// Anyway, at the moment we don't support other kinds of image / sampler |
| 5260 |
// arrays than those binding-based, so this assumption is pretty safe |
| 5261 |
// for now. |
| 5262 |
let inner = if let crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } = |
| 5263 |
module.types[base].inner |
| 5264 |
{ |
| 5265 |
crate::TypeInner::BindingArray { |
| 5266 |
base, |
| 5267 |
size: crate::ArraySize::Constant(size), |
| 5268 |
} |
| 5269 |
} else { |
| 5270 |
crate::TypeInner::Array { |
| 5271 |
base, |
| 5272 |
size: crate::ArraySize::Constant(size), |
| 5273 |
stride: match decor.array_stride { |
| 5274 |
Some(stride) => stride.get(), |
| 5275 |
None => self.layouter[base].to_stride(), |
| 5276 |
}, |
| 5277 |
} |
| 5278 |
}; |
| 5279 |
|
| 5280 |
self.lookup_type.insert( |
| 5281 |
id, |
| 5282 |
LookupType { |
| 5283 |
handle: module.types.insert( |
| 5284 |
crate::Type { |
| 5285 |
name: decor.name, |
| 5286 |
inner, |
| 5287 |
}, |
| 5288 |
self.span_from_with_op(start), |
| 5289 |
), |
| 5290 |
base_id: Some(type_id), |
| 5291 |
}, |
| 5292 |
); |
| 5293 |
Ok(()) |
| 5294 |
} |
| 5295 |
|
| 5296 |
fn parse_type_runtime_array( |
| 5297 |
&mut self, |
| 5298 |
inst: Instruction, |
| 5299 |
module: &mut crate::Module, |
| 5300 |
) -> Result<(), Error> { |
| 5301 |
let start = self.data_offset; |
| 5302 |
self.switch(ModuleState::Type, inst.op)?; |
| 5303 |
inst.expect(3)?; |
| 5304 |
let id = self.next()?; |
| 5305 |
let type_id = self.next()?; |
| 5306 |
|
| 5307 |
let decor = self.future_decor.remove(&id).unwrap_or_default(); |
| 5308 |
let base = self.lookup_type.lookup(type_id)?.handle; |
| 5309 |
|
| 5310 |
self.layouter.update(module.to_ctx()).unwrap(); |
| 5311 |
|
| 5312 |
// HACK same case as in `parse_type_array()` |
| 5313 |
let inner = if let crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } = |
| 5314 |
module.types[base].inner |
| 5315 |
{ |
| 5316 |
crate::TypeInner::BindingArray { |
| 5317 |
base: self.lookup_type.lookup(type_id)?.handle, |
| 5318 |
size: crate::ArraySize::Dynamic, |
| 5319 |
} |
| 5320 |
} else { |
| 5321 |
crate::TypeInner::Array { |
| 5322 |
base: self.lookup_type.lookup(type_id)?.handle, |
| 5323 |
size: crate::ArraySize::Dynamic, |
| 5324 |
stride: match decor.array_stride { |
| 5325 |
Some(stride) => stride.get(), |
| 5326 |
None => self.layouter[base].to_stride(), |
| 5327 |
}, |
| 5328 |
} |
| 5329 |
}; |
| 5330 |
|
| 5331 |
self.lookup_type.insert( |
| 5332 |
id, |
| 5333 |
LookupType { |
| 5334 |
handle: module.types.insert( |
| 5335 |
crate::Type { |
| 5336 |
name: decor.name, |
| 5337 |
inner, |
| 5338 |
}, |
| 5339 |
self.span_from_with_op(start), |
| 5340 |
), |
| 5341 |
base_id: Some(type_id), |
| 5342 |
}, |
| 5343 |
); |
| 5344 |
Ok(()) |
| 5345 |
} |
| 5346 |
|
| 5347 |
fn parse_type_struct( |
| 5348 |
&mut self, |
| 5349 |
inst: Instruction, |
| 5350 |
module: &mut crate::Module, |
| 5351 |
) -> Result<(), Error> { |
| 5352 |
let start = self.data_offset; |
| 5353 |
self.switch(ModuleState::Type, inst.op)?; |
| 5354 |
inst.expect_at_least(2)?; |
| 5355 |
let id = self.next()?; |
| 5356 |
let parent_decor = self.future_decor.remove(&id); |
| 5357 |
let is_storage_buffer = parent_decor |
| 5358 |
.as_ref() |
| 5359 |
.is_some_and(|decor| decor.storage_buffer); |
| 5360 |
|
| 5361 |
self.layouter.update(module.to_ctx()).unwrap(); |
| 5362 |
|
| 5363 |
let mut members = Vec::<crate::StructMember>::with_capacity(inst.wc as usize - 2); |
| 5364 |
let mut member_lookups = Vec::with_capacity(members.capacity()); |
| 5365 |
let mut storage_access = crate::StorageAccess::empty(); |
| 5366 |
let mut span = 0; |
| 5367 |
let mut alignment = Alignment::ONE; |
| 5368 |
for i in 0..u32::from(inst.wc) - 2 { |
| 5369 |
let type_id = self.next()?; |
| 5370 |
let ty = self.lookup_type.lookup(type_id)?.handle; |
| 5371 |
let decor = self |
| 5372 |
.future_member_decor |
| 5373 |
.remove(&(id, i)) |
| 5374 |
.unwrap_or_default(); |
| 5375 |
|
| 5376 |
storage_access |= decor.flags.to_storage_access(); |
| 5377 |
|
| 5378 |
member_lookups.push(LookupMember { |
| 5379 |
type_id, |
| 5380 |
row_major: decor.matrix_major == Some(Majority::Row), |
| 5381 |
}); |
| 5382 |
|
| 5383 |
let member_alignment = self.layouter[ty].alignment; |
| 5384 |
span = member_alignment.round_up(span); |
| 5385 |
alignment = member_alignment.max(alignment); |
| 5386 |
|
| 5387 |
let binding = decor.io_binding().ok(); |
| 5388 |
if let Some(offset) = decor.offset { |
| 5389 |
span = offset; |
| 5390 |
} |
| 5391 |
let offset = span; |
| 5392 |
|
| 5393 |
span += self.layouter[ty].size; |
| 5394 |
|
| 5395 |
let inner = &module.types[ty].inner; |
| 5396 |
if let crate::TypeInner::Matrix { |
| 5397 |
columns, |
| 5398 |
rows, |
| 5399 |
scalar, |
| 5400 |
} = *inner |
| 5401 |
{ |
| 5402 |
if let Some(stride) = decor.matrix_stride { |
| 5403 |
let expected_stride = Alignment::from(rows) * scalar.width as u32; |
| 5404 |
if stride.get() != expected_stride { |
| 5405 |
return Err(Error::UnsupportedMatrixStride { |
| 5406 |
stride: stride.get(), |
| 5407 |
columns: columns as u8, |
| 5408 |
rows: rows as u8, |
| 5409 |
width: scalar.width, |
| 5410 |
}); |
| 5411 |
} |
| 5412 |
} |
| 5413 |
} |
| 5414 |
|
| 5415 |
members.push(crate::StructMember { |
| 5416 |
name: decor.name, |
| 5417 |
ty, |
| 5418 |
binding, |
| 5419 |
offset, |
| 5420 |
}); |
| 5421 |
} |
| 5422 |
|
| 5423 |
span = alignment.round_up(span); |
| 5424 |
|
| 5425 |
let inner = crate::TypeInner::Struct { span, members }; |
| 5426 |
|
| 5427 |
let ty_handle = module.types.insert( |
| 5428 |
crate::Type { |
| 5429 |
name: parent_decor.and_then(|dec| dec.name), |
| 5430 |
inner, |
| 5431 |
}, |
| 5432 |
self.span_from_with_op(start), |
| 5433 |
); |
| 5434 |
|
| 5435 |
if is_storage_buffer { |
| 5436 |
self.lookup_storage_buffer_types |
| 5437 |
.insert(ty_handle, storage_access); |
| 5438 |
} |
| 5439 |
for (i, member_lookup) in member_lookups.into_iter().enumerate() { |
| 5440 |
self.lookup_member |
| 5441 |
.insert((ty_handle, i as u32), member_lookup); |
| 5442 |
} |
| 5443 |
self.lookup_type.insert( |
| 5444 |
id, |
| 5445 |
LookupType { |
| 5446 |
handle: ty_handle, |
| 5447 |
base_id: None, |
| 5448 |
}, |
| 5449 |
); |
| 5450 |
Ok(()) |
| 5451 |
} |
| 5452 |
|
| 5453 |
fn parse_type_image( |
| 5454 |
&mut self, |
| 5455 |
inst: Instruction, |
| 5456 |
module: &mut crate::Module, |
| 5457 |
) -> Result<(), Error> { |
| 5458 |
let start = self.data_offset; |
| 5459 |
self.switch(ModuleState::Type, inst.op)?; |
| 5460 |
inst.expect(9)?; |
| 5461 |
|
| 5462 |
let id = self.next()?; |
| 5463 |
let sample_type_id = self.next()?; |
| 5464 |
let dim = self.next()?; |
| 5465 |
let is_depth = self.next()?; |
| 5466 |
let is_array = self.next()? != 0; |
| 5467 |
let is_msaa = self.next()? != 0; |
| 5468 |
let _is_sampled = self.next()?; |
| 5469 |
let format = self.next()?; |
| 5470 |
|
| 5471 |
let dim = map_image_dim(dim)?; |
| 5472 |
let decor = self.future_decor.remove(&id).unwrap_or_default(); |
| 5473 |
|
| 5474 |
// ensure there is a type for texture coordinate without extra components |
| 5475 |
module.types.insert( |
| 5476 |
crate::Type { |
| 5477 |
name: None, |
| 5478 |
inner: { |
| 5479 |
let scalar = crate::Scalar::F32; |
| 5480 |
match dim.required_coordinate_size() { |
| 5481 |
None => crate::TypeInner::Scalar(scalar), |
| 5482 |
Some(size) => crate::TypeInner::Vector { size, scalar }, |
| 5483 |
} |
| 5484 |
}, |
| 5485 |
}, |
| 5486 |
Default::default(), |
| 5487 |
); |
| 5488 |
|
| 5489 |
let base_handle = self.lookup_type.lookup(sample_type_id)?.handle; |
| 5490 |
let kind = module.types[base_handle] |
| 5491 |
.inner |
| 5492 |
.scalar_kind() |
| 5493 |
.ok_or(Error::InvalidImageBaseType(base_handle))?; |
| 5494 |
|
| 5495 |
let inner = crate::TypeInner::Image { |
| 5496 |
class: if is_depth == 1 { |
| 5497 |
crate::ImageClass::Depth { multi: is_msaa } |
| 5498 |
} else if format != 0 { |
| 5499 |
crate::ImageClass::Storage { |
| 5500 |
format: map_image_format(format)?, |
| 5501 |
access: crate::StorageAccess::default(), |
| 5502 |
} |
| 5503 |
} else { |
| 5504 |
crate::ImageClass::Sampled { |
| 5505 |
kind, |
| 5506 |
multi: is_msaa, |
| 5507 |
} |
| 5508 |
}, |
| 5509 |
dim, |
| 5510 |
arrayed: is_array, |
| 5511 |
}; |
| 5512 |
|
| 5513 |
let handle = module.types.insert( |
| 5514 |
crate::Type { |
| 5515 |
name: decor.name, |
| 5516 |
inner, |
| 5517 |
}, |
| 5518 |
self.span_from_with_op(start), |
| 5519 |
); |
| 5520 |
|
| 5521 |
self.lookup_type.insert( |
| 5522 |
id, |
| 5523 |
LookupType { |
| 5524 |
handle, |
| 5525 |
base_id: Some(sample_type_id), |
| 5526 |
}, |
| 5527 |
); |
| 5528 |
Ok(()) |
| 5529 |
} |
| 5530 |
|
| 5531 |
fn parse_type_sampled_image(&mut self, inst: Instruction) -> Result<(), Error> { |
| 5532 |
self.switch(ModuleState::Type, inst.op)?; |
| 5533 |
inst.expect(3)?; |
| 5534 |
let id = self.next()?; |
| 5535 |
let image_id = self.next()?; |
| 5536 |
self.lookup_type.insert( |
| 5537 |
id, |
| 5538 |
LookupType { |
| 5539 |
handle: self.lookup_type.lookup(image_id)?.handle, |
| 5540 |
base_id: Some(image_id), |
| 5541 |
}, |
| 5542 |
); |
| 5543 |
Ok(()) |
| 5544 |
} |
| 5545 |
|
| 5546 |
fn parse_type_sampler( |
| 5547 |
&mut self, |
| 5548 |
inst: Instruction, |
| 5549 |
module: &mut crate::Module, |
| 5550 |
) -> Result<(), Error> { |
| 5551 |
let start = self.data_offset; |
| 5552 |
self.switch(ModuleState::Type, inst.op)?; |
| 5553 |
inst.expect(2)?; |
| 5554 |
let id = self.next()?; |
| 5555 |
let decor = self.future_decor.remove(&id).unwrap_or_default(); |
| 5556 |
let handle = module.types.insert( |
| 5557 |
crate::Type { |
| 5558 |
name: decor.name, |
| 5559 |
inner: crate::TypeInner::Sampler { comparison: false }, |
| 5560 |
}, |
| 5561 |
self.span_from_with_op(start), |
| 5562 |
); |
| 5563 |
self.lookup_type.insert( |
| 5564 |
id, |
| 5565 |
LookupType { |
| 5566 |
handle, |
| 5567 |
base_id: None, |
| 5568 |
}, |
| 5569 |
); |
| 5570 |
Ok(()) |
| 5571 |
} |
| 5572 |
|
| 5573 |
fn parse_constant( |
| 5574 |
&mut self, |
| 5575 |
inst: Instruction, |
| 5576 |
module: &mut crate::Module, |
| 5577 |
) -> Result<(), Error> { |
| 5578 |
let start = self.data_offset; |
| 5579 |
self.switch(ModuleState::Type, inst.op)?; |
| 5580 |
inst.expect_at_least(4)?; |
| 5581 |
let type_id = self.next()?; |
| 5582 |
let id = self.next()?; |
| 5583 |
let type_lookup = self.lookup_type.lookup(type_id)?; |
| 5584 |
let ty = type_lookup.handle; |
| 5585 |
|
| 5586 |
let literal = match module.types[ty].inner { |
| 5587 |
crate::TypeInner::Scalar(crate::Scalar { |
| 5588 |
kind: crate::ScalarKind::Uint, |
| 5589 |
width, |
| 5590 |
}) => { |
| 5591 |
let low = self.next()?; |
| 5592 |
match width { |
| 5593 |
4 => crate::Literal::U32(low), |
| 5594 |
8 => { |
| 5595 |
inst.expect(5)?; |
| 5596 |
let high = self.next()?; |
| 5597 |
crate::Literal::U64((u64::from(high) << 32) | u64::from(low)) |
| 5598 |
} |
| 5599 |
_ => return Err(Error::InvalidTypeWidth(width as u32)), |
| 5600 |
} |
| 5601 |
} |
| 5602 |
crate::TypeInner::Scalar(crate::Scalar { |
| 5603 |
kind: crate::ScalarKind::Sint, |
| 5604 |
width, |
| 5605 |
}) => { |
| 5606 |
let low = self.next()?; |
| 5607 |
match width { |
| 5608 |
4 => crate::Literal::I32(low as i32), |
| 5609 |
8 => { |
| 5610 |
inst.expect(5)?; |
| 5611 |
let high = self.next()?; |
| 5612 |
crate::Literal::I64(((u64::from(high) << 32) | u64::from(low)) as i64) |
| 5613 |
} |
| 5614 |
_ => return Err(Error::InvalidTypeWidth(width as u32)), |
| 5615 |
} |
| 5616 |
} |
| 5617 |
crate::TypeInner::Scalar(crate::Scalar { |
| 5618 |
kind: crate::ScalarKind::Float, |
| 5619 |
width, |
| 5620 |
}) => { |
| 5621 |
let low = self.next()?; |
| 5622 |
match width { |
| 5623 |
// https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#Literal |
| 5624 |
// If a numeric type’s bit width is less than 32-bits, the value appears in the low-order bits of the word. |
| 5625 |
2 => crate::Literal::F16(f16::from_bits(low as u16)), |
| 5626 |
4 => crate::Literal::F32(f32::from_bits(low)), |
| 5627 |
8 => { |
| 5628 |
inst.expect(5)?; |
| 5629 |
let high = self.next()?; |
| 5630 |
crate::Literal::F64(f64::from_bits( |
| 5631 |
(u64::from(high) << 32) | u64::from(low), |
| 5632 |
)) |
| 5633 |
} |
| 5634 |
_ => return Err(Error::InvalidTypeWidth(width as u32)), |
| 5635 |
} |
| 5636 |
} |
| 5637 |
_ => return Err(Error::UnsupportedType(type_lookup.handle)), |
| 5638 |
}; |
| 5639 |
|
| 5640 |
let span = self.span_from_with_op(start); |
| 5641 |
|
| 5642 |
let init = module |
| 5643 |
.global_expressions |
| 5644 |
.append(crate::Expression::Literal(literal), span); |
| 5645 |
|
| 5646 |
self.insert_parsed_constant(module, id, type_id, ty, init, span) |
| 5647 |
} |
| 5648 |
|
| 5649 |
fn parse_composite_constant( |
| 5650 |
&mut self, |
| 5651 |
inst: Instruction, |
| 5652 |
module: &mut crate::Module, |
| 5653 |
) -> Result<(), Error> { |
| 5654 |
let start = self.data_offset; |
| 5655 |
self.switch(ModuleState::Type, inst.op)?; |
| 5656 |
inst.expect_at_least(3)?; |
| 5657 |
let type_id = self.next()?; |
| 5658 |
let id = self.next()?; |
| 5659 |
|
| 5660 |
let type_lookup = self.lookup_type.lookup(type_id)?; |
| 5661 |
let ty = type_lookup.handle; |
| 5662 |
|
| 5663 |
let mut components = Vec::with_capacity(inst.wc as usize - 3); |
| 5664 |
for _ in 0..components.capacity() { |
| 5665 |
let start = self.data_offset; |
| 5666 |
let component_id = self.next()?; |
| 5667 |
let span = self.span_from_with_op(start); |
| 5668 |
let constant = self.lookup_constant.lookup(component_id)?; |
| 5669 |
let expr = module |
| 5670 |
.global_expressions |
| 5671 |
.append(constant.inner.to_expr(), span); |
| 5672 |
components.push(expr); |
| 5673 |
} |
| 5674 |
|
| 5675 |
let span = self.span_from_with_op(start); |
| 5676 |
|
| 5677 |
let init = module |
| 5678 |
.global_expressions |
| 5679 |
.append(crate::Expression::Compose { ty, components }, span); |
| 5680 |
|
| 5681 |
self.insert_parsed_constant(module, id, type_id, ty, init, span) |
| 5682 |
} |
| 5683 |
|
| 5684 |
fn parse_null_constant( |
| 5685 |
&mut self, |
| 5686 |
inst: Instruction, |
| 5687 |
module: &mut crate::Module, |
| 5688 |
) -> Result<(), Error> { |
| 5689 |
let start = self.data_offset; |
| 5690 |
self.switch(ModuleState::Type, inst.op)?; |
| 5691 |
inst.expect(3)?; |
| 5692 |
let type_id = self.next()?; |
| 5693 |
let id = self.next()?; |
| 5694 |
let span = self.span_from_with_op(start); |
| 5695 |
|
| 5696 |
let type_lookup = self.lookup_type.lookup(type_id)?; |
| 5697 |
let ty = type_lookup.handle; |
| 5698 |
|
| 5699 |
let init = module |
| 5700 |
.global_expressions |
| 5701 |
.append(crate::Expression::ZeroValue(ty), span); |
| 5702 |
|
| 5703 |
self.insert_parsed_constant(module, id, type_id, ty, init, span) |
| 5704 |
} |
| 5705 |
|
| 5706 |
fn parse_bool_constant( |
| 5707 |
&mut self, |
| 5708 |
inst: Instruction, |
| 5709 |
value: bool, |
| 5710 |
module: &mut crate::Module, |
| 5711 |
) -> Result<(), Error> { |
| 5712 |
let start = self.data_offset; |
| 5713 |
self.switch(ModuleState::Type, inst.op)?; |
| 5714 |
inst.expect(3)?; |
| 5715 |
let type_id = self.next()?; |
| 5716 |
let id = self.next()?; |
| 5717 |
let span = self.span_from_with_op(start); |
| 5718 |
|
| 5719 |
let type_lookup = self.lookup_type.lookup(type_id)?; |
| 5720 |
let ty = type_lookup.handle; |
| 5721 |
|
| 5722 |
let init = module.global_expressions.append( |
| 5723 |
crate::Expression::Literal(crate::Literal::Bool(value)), |
| 5724 |
span, |
| 5725 |
); |
| 5726 |
|
| 5727 |
self.insert_parsed_constant(module, id, type_id, ty, init, span) |
| 5728 |
} |
| 5729 |
|
| 5730 |
fn insert_parsed_constant( |
| 5731 |
&mut self, |
| 5732 |
module: &mut crate::Module, |
| 5733 |
id: u32, |
| 5734 |
type_id: u32, |
| 5735 |
ty: Handle<crate::Type>, |
| 5736 |
init: Handle<crate::Expression>, |
| 5737 |
span: crate::Span, |
| 5738 |
) -> Result<(), Error> { |
| 5739 |
let decor = self.future_decor.remove(&id).unwrap_or_default(); |
| 5740 |
|
| 5741 |
let inner = if let Some(id) = decor.specialization_constant_id { |
| 5742 |
let o = crate::Override { |
| 5743 |
name: decor.name, |
| 5744 |
id: Some(id.try_into().map_err(|_| Error::SpecIdTooHigh(id))?), |
| 5745 |
ty, |
| 5746 |
init: Some(init), |
| 5747 |
}; |
| 5748 |
Constant::Override(module.overrides.append(o, span)) |
| 5749 |
} else { |
| 5750 |
let c = crate::Constant { |
| 5751 |
name: decor.name, |
| 5752 |
ty, |
| 5753 |
init, |
| 5754 |
}; |
| 5755 |
Constant::Constant(module.constants.append(c, span)) |
| 5756 |
}; |
| 5757 |
|
| 5758 |
self.lookup_constant |
| 5759 |
.insert(id, LookupConstant { inner, type_id }); |
| 5760 |
Ok(()) |
| 5761 |
} |
| 5762 |
|
| 5763 |
fn parse_global_variable( |
| 5764 |
&mut self, |
| 5765 |
inst: Instruction, |
| 5766 |
module: &mut crate::Module, |
| 5767 |
) -> Result<(), Error> { |
| 5768 |
let start = self.data_offset; |
| 5769 |
self.switch(ModuleState::Type, inst.op)?; |
| 5770 |
inst.expect_at_least(4)?; |
| 5771 |
let type_id = self.next()?; |
| 5772 |
let id = self.next()?; |
| 5773 |
let storage_class = self.next()?; |
| 5774 |
let init = if inst.wc > 4 { |
| 5775 |
inst.expect(5)?; |
| 5776 |
let start = self.data_offset; |
| 5777 |
let init_id = self.next()?; |
| 5778 |
let span = self.span_from_with_op(start); |
| 5779 |
let lconst = self.lookup_constant.lookup(init_id)?; |
| 5780 |
let expr = module |
| 5781 |
.global_expressions |
| 5782 |
.append(lconst.inner.to_expr(), span); |
| 5783 |
Some(expr) |
| 5784 |
} else { |
| 5785 |
None |
| 5786 |
}; |
| 5787 |
let span = self.span_from_with_op(start); |
| 5788 |
let dec = self.future_decor.remove(&id).unwrap_or_default(); |
| 5789 |
|
| 5790 |
let original_ty = self.lookup_type.lookup(type_id)?.handle; |
| 5791 |
let mut ty = original_ty; |
| 5792 |
|
| 5793 |
if let crate::TypeInner::Pointer { base, space: _ } = module.types[original_ty].inner { |
| 5794 |
ty = base; |
| 5795 |
} |
| 5796 |
|
| 5797 |
if let crate::TypeInner::BindingArray { .. } = module.types[original_ty].inner { |
| 5798 |
// Inside `parse_type_array()` we guess that an array of images or |
| 5799 |
// samplers must be a binding array, and here we validate that guess |
| 5800 |
if dec.desc_set.is_none() || dec.desc_index.is_none() { |
| 5801 |
return Err(Error::NonBindingArrayOfImageOrSamplers); |
| 5802 |
} |
| 5803 |
} |
| 5804 |
|
| 5805 |
if let crate::TypeInner::Image { |
| 5806 |
dim, |
| 5807 |
arrayed, |
| 5808 |
class: crate::ImageClass::Storage { format, access: _ }, |
| 5809 |
} = module.types[ty].inner |
| 5810 |
{ |
| 5811 |
// Storage image types in IR have to contain the access, but not in the SPIR-V. |
| 5812 |
// The same image type in SPIR-V can be used (and has to be used) for multiple images. |
| 5813 |
// So we copy the type out and apply the variable access decorations. |
| 5814 |
let access = dec.flags.to_storage_access(); |
| 5815 |
|
| 5816 |
ty = module.types.insert( |
| 5817 |
crate::Type { |
| 5818 |
name: None, |
| 5819 |
inner: crate::TypeInner::Image { |
| 5820 |
dim, |
| 5821 |
arrayed, |
| 5822 |
class: crate::ImageClass::Storage { format, access }, |
| 5823 |
}, |
| 5824 |
}, |
| 5825 |
Default::default(), |
| 5826 |
); |
| 5827 |
} |
| 5828 |
|
| 5829 |
let ext_class = match self.lookup_storage_buffer_types.get(&ty) { |
| 5830 |
Some(&access) => ExtendedClass::Global(crate::AddressSpace::Storage { access }), |
| 5831 |
None => map_storage_class(storage_class)?, |
| 5832 |
}; |
| 5833 |
|
| 5834 |
let (inner, var) = match ext_class { |
| 5835 |
ExtendedClass::Global(mut space) => { |
| 5836 |
if let crate::AddressSpace::Storage { ref mut access } = space { |
| 5837 |
*access &= dec.flags.to_storage_access(); |
| 5838 |
} |
| 5839 |
let var = crate::GlobalVariable { |
| 5840 |
binding: dec.resource_binding(), |
| 5841 |
name: dec.name, |
| 5842 |
space, |
| 5843 |
ty, |
| 5844 |
init, |
| 5845 |
}; |
| 5846 |
(Variable::Global, var) |
| 5847 |
} |
| 5848 |
ExtendedClass::Input => { |
| 5849 |
let binding = dec.io_binding()?; |
| 5850 |
let mut unsigned_ty = ty; |
| 5851 |
if let crate::Binding::BuiltIn(built_in) = binding { |
| 5852 |
let needs_inner_uint = match built_in { |
| 5853 |
crate::BuiltIn::BaseInstance |
| 5854 |
| crate::BuiltIn::BaseVertex |
| 5855 |
| crate::BuiltIn::InstanceIndex |
| 5856 |
| crate::BuiltIn::SampleIndex |
| 5857 |
| crate::BuiltIn::VertexIndex |
| 5858 |
| crate::BuiltIn::PrimitiveIndex |
| 5859 |
| crate::BuiltIn::LocalInvocationIndex => { |
| 5860 |
Some(crate::TypeInner::Scalar(crate::Scalar::U32)) |
| 5861 |
} |
| 5862 |
crate::BuiltIn::GlobalInvocationId |
| 5863 |
| crate::BuiltIn::LocalInvocationId |
| 5864 |
| crate::BuiltIn::WorkGroupId |
| 5865 |
| crate::BuiltIn::WorkGroupSize => Some(crate::TypeInner::Vector { |
| 5866 |
size: crate::VectorSize::Tri, |
| 5867 |
scalar: crate::Scalar::U32, |
| 5868 |
}), |
| 5869 |
_ => None, |
| 5870 |
}; |
| 5871 |
if let (Some(inner), Some(crate::ScalarKind::Sint)) = |
| 5872 |
(needs_inner_uint, module.types[ty].inner.scalar_kind()) |
| 5873 |
{ |
| 5874 |
unsigned_ty = module |
| 5875 |
.types |
| 5876 |
.insert(crate::Type { name: None, inner }, Default::default()); |
| 5877 |
} |
| 5878 |
} |
| 5879 |
|
| 5880 |
let var = crate::GlobalVariable { |
| 5881 |
name: dec.name.clone(), |
| 5882 |
space: crate::AddressSpace::Private, |
| 5883 |
binding: None, |
| 5884 |
ty, |
| 5885 |
init: None, |
| 5886 |
}; |
| 5887 |
|
| 5888 |
let inner = Variable::Input(crate::FunctionArgument { |
| 5889 |
name: dec.name, |
| 5890 |
ty: unsigned_ty, |
| 5891 |
binding: Some(binding), |
| 5892 |
}); |
| 5893 |
(inner, var) |
| 5894 |
} |
| 5895 |
ExtendedClass::Output => { |
| 5896 |
// For output interface blocks, this would be a structure. |
| 5897 |
let binding = dec.io_binding().ok(); |
| 5898 |
let init = match binding { |
| 5899 |
Some(crate::Binding::BuiltIn(built_in)) => { |
| 5900 |
match null::generate_default_built_in( |
| 5901 |
Some(built_in), |
| 5902 |
ty, |
| 5903 |
&mut module.global_expressions, |
| 5904 |
span, |
| 5905 |
) { |
| 5906 |
Ok(handle) => Some(handle), |
| 5907 |
Err(e) => { |
| 5908 |
log::warn!("Failed to initialize output built-in: {}", e); |
| 5909 |
None |
| 5910 |
} |
| 5911 |
} |
| 5912 |
} |
| 5913 |
Some(crate::Binding::Location { .. }) => None, |
| 5914 |
None => match module.types[ty].inner { |
| 5915 |
crate::TypeInner::Struct { ref members, .. } => { |
| 5916 |
let mut components = Vec::with_capacity(members.len()); |
| 5917 |
for member in members.iter() { |
| 5918 |
let built_in = match member.binding { |
| 5919 |
Some(crate::Binding::BuiltIn(built_in)) => Some(built_in), |
| 5920 |
_ => None, |
| 5921 |
}; |
| 5922 |
let handle = null::generate_default_built_in( |
| 5923 |
built_in, |
| 5924 |
member.ty, |
| 5925 |
&mut module.global_expressions, |
| 5926 |
span, |
| 5927 |
)?; |
| 5928 |
components.push(handle); |
| 5929 |
} |
| 5930 |
Some( |
| 5931 |
module |
| 5932 |
.global_expressions |
| 5933 |
.append(crate::Expression::Compose { ty, components }, span), |
| 5934 |
) |
| 5935 |
} |
| 5936 |
_ => None, |
| 5937 |
}, |
| 5938 |
}; |
| 5939 |
|
| 5940 |
let var = crate::GlobalVariable { |
| 5941 |
name: dec.name, |
| 5942 |
space: crate::AddressSpace::Private, |
| 5943 |
binding: None, |
| 5944 |
ty, |
| 5945 |
init, |
| 5946 |
}; |
| 5947 |
let inner = Variable::Output(crate::FunctionResult { ty, binding }); |
| 5948 |
(inner, var) |
| 5949 |
} |
| 5950 |
}; |
| 5951 |
|
| 5952 |
let handle = module.global_variables.append(var, span); |
| 5953 |
|
| 5954 |
if module.types[ty].inner.can_comparison_sample(module) { |
| 5955 |
log::debug!("\t\ttracking {:?} for sampling properties", handle); |
| 5956 |
|
| 5957 |
self.handle_sampling |
| 5958 |
.insert(handle, image::SamplingFlags::empty()); |
| 5959 |
} |
| 5960 |
|
| 5961 |
self.lookup_variable.insert( |
| 5962 |
id, |
| 5963 |
LookupVariable { |
| 5964 |
inner, |
| 5965 |
handle, |
| 5966 |
type_id, |
| 5967 |
}, |
| 5968 |
); |
| 5969 |
Ok(()) |
| 5970 |
} |
| 5971 |
|
| 5972 |
/// Record an atomic access to some component of a global variable. |
| 5973 |
/// |
| 5974 |
/// Given `handle`, an expression referring to a scalar that has had an |
| 5975 |
/// atomic operation applied to it, descend into the expression, noting |
| 5976 |
/// which global variable it ultimately refers to, and which struct fields |
| 5977 |
/// of that global's value it accesses. |
| 5978 |
/// |
| 5979 |
/// Return the handle of the type of the expression. |
| 5980 |
/// |
| 5981 |
/// If the expression doesn't actually refer to something in a global |
| 5982 |
/// variable, we can't upgrade its type in a way that Naga validation would |
| 5983 |
/// pass, so reject the input instead. |
| 5984 |
fn record_atomic_access( |
| 5985 |
&mut self, |
| 5986 |
ctx: &BlockContext, |
| 5987 |
handle: Handle<crate::Expression>, |
| 5988 |
) -> Result<Handle<crate::Type>, Error> { |
| 5989 |
log::debug!("\t\tlocating global variable in {handle:?}"); |
| 5990 |
match ctx.expressions[handle] { |
| 5991 |
crate::Expression::Access { base, index } => { |
| 5992 |
log::debug!("\t\t access {handle:?} {index:?}"); |
| 5993 |
let ty = self.record_atomic_access(ctx, base)?; |
| 5994 |
let crate::TypeInner::Array { base, .. } = ctx.module.types[ty].inner else { |
| 5995 |
unreachable!("Atomic operations on Access expressions only work for arrays"); |
| 5996 |
}; |
| 5997 |
Ok(base) |
| 5998 |
} |
| 5999 |
crate::Expression::AccessIndex { base, index } => { |
| 6000 |
log::debug!("\t\t access index {handle:?} {index:?}"); |
| 6001 |
let ty = self.record_atomic_access(ctx, base)?; |
| 6002 |
match ctx.module.types[ty].inner { |
| 6003 |
crate::TypeInner::Struct { ref members, .. } => { |
| 6004 |
let index = index as usize; |
| 6005 |
self.upgrade_atomics.insert_field(ty, index); |
| 6006 |
Ok(members[index].ty) |
| 6007 |
} |
| 6008 |
crate::TypeInner::Array { base, .. } => { |
| 6009 |
Ok(base) |
| 6010 |
} |
| 6011 |
_ => unreachable!("Atomic operations on AccessIndex expressions only work for structs and arrays"), |
| 6012 |
} |
| 6013 |
} |
| 6014 |
crate::Expression::GlobalVariable(h) => { |
| 6015 |
log::debug!("\t\t found {h:?}"); |
| 6016 |
self.upgrade_atomics.insert_global(h); |
| 6017 |
Ok(ctx.module.global_variables[h].ty) |
| 6018 |
} |
| 6019 |
_ => Err(Error::AtomicUpgradeError( |
| 6020 |
crate::front::atomic_upgrade::Error::GlobalVariableMissing, |
| 6021 |
)), |
| 6022 |
} |
| 6023 |
} |
| 6024 |
} |
| 6025 |
|
| 6026 |
fn make_index_literal( |
| 6027 |
ctx: &mut BlockContext, |
| 6028 |
index: u32, |
| 6029 |
block: &mut crate::Block, |
| 6030 |
emitter: &mut crate::proc::Emitter, |
| 6031 |
index_type: Handle<crate::Type>, |
| 6032 |
index_type_id: spirv::Word, |
| 6033 |
span: crate::Span, |
| 6034 |
) -> Result<Handle<crate::Expression>, Error> { |
| 6035 |
block.extend(emitter.finish(ctx.expressions)); |
| 6036 |
|
| 6037 |
let literal = match ctx.module.types[index_type].inner.scalar_kind() { |
| 6038 |
Some(crate::ScalarKind::Uint) => crate::Literal::U32(index), |
| 6039 |
Some(crate::ScalarKind::Sint) => crate::Literal::I32(index as i32), |
| 6040 |
_ => return Err(Error::InvalidIndexType(index_type_id)), |
| 6041 |
}; |
| 6042 |
let expr = ctx |
| 6043 |
.expressions |
| 6044 |
.append(crate::Expression::Literal(literal), span); |
| 6045 |
|
| 6046 |
emitter.start(ctx.expressions); |
| 6047 |
Ok(expr) |
| 6048 |
} |
| 6049 |
|
| 6050 |
fn resolve_constant(gctx: crate::proc::GlobalCtx, constant: &Constant) -> Option<u32> { |
| 6051 |
let constant = match *constant { |
| 6052 |
Constant::Constant(constant) => constant, |
| 6053 |
Constant::Override(_) => return None, |
| 6054 |
}; |
| 6055 |
match gctx.global_expressions[gctx.constants[constant].init] { |
| 6056 |
crate::Expression::Literal(crate::Literal::U32(id)) => Some(id), |
| 6057 |
crate::Expression::Literal(crate::Literal::I32(id)) => Some(id as u32), |
| 6058 |
_ => None, |
| 6059 |
} |
| 6060 |
} |
| 6061 |
|
| 6062 |
pub fn parse_u8_slice(data: &[u8], options: &Options) -> Result<crate::Module, Error> { |
| 6063 |
if data.len() % 4 != 0 { |
| 6064 |
return Err(Error::IncompleteData); |
| 6065 |
} |
| 6066 |
|
| 6067 |
let words = data |
| 6068 |
.chunks(4) |
| 6069 |
.map(|c| u32::from_le_bytes(c.try_into().unwrap())); |
| 6070 |
Frontend::new(words, options).parse() |
| 6071 |
} |
| 6072 |
|
| 6073 |
/// Helper function to check if `child` is in the scope of `parent` |
| 6074 |
fn is_parent(mut child: usize, parent: usize, block_ctx: &BlockContext) -> bool { |
| 6075 |
loop { |
| 6076 |
if child == parent { |
| 6077 |
// The child is in the scope parent |
| 6078 |
break true; |
| 6079 |
} else if child == 0 { |
| 6080 |
// Searched finished at the root the child isn't in the parent's body |
| 6081 |
break false; |
| 6082 |
} |
| 6083 |
|
| 6084 |
child = block_ctx.bodies[child].parent; |
| 6085 |
} |
| 6086 |
} |
| 6087 |
|
| 6088 |
#[cfg(test)] |
| 6089 |
mod test { |
| 6090 |
use alloc::vec; |
| 6091 |
|
| 6092 |
#[test] |
| 6093 |
fn parse() { |
| 6094 |
let bin = vec![ |
| 6095 |
// Magic number. Version number: 1.0. |
| 6096 |
0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, |
| 6097 |
// Generator number: 0. Bound: 0. |
| 6098 |
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Reserved word: 0. |
| 6099 |
0x00, 0x00, 0x00, 0x00, // OpMemoryModel. Logical. |
| 6100 |
0x0e, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, // GLSL450. |
| 6101 |
0x01, 0x00, 0x00, 0x00, |
| 6102 |
]; |
| 6103 |
let _ = super::parse_u8_slice(&bin, &Default::default()).unwrap(); |
| 6104 |
} |
| 6105 |
} |