| 1 |
use alloc::{ |
| 2 |
borrow::ToOwned, |
| 3 |
boxed::Box, |
| 4 |
string::{String, ToString}, |
| 5 |
vec::Vec, |
| 6 |
}; |
| 7 |
use core::num::NonZeroU32; |
| 8 |
|
| 9 |
use crate::common::wgsl::{TryToWgsl, TypeContext}; |
| 10 |
use crate::common::ForDebugWithTypes; |
| 11 |
use crate::front::wgsl::error::{Error, ExpectedToken, InvalidAssignmentType}; |
| 12 |
use crate::front::wgsl::index::Index; |
| 13 |
use crate::front::wgsl::parse::number::Number; |
| 14 |
use crate::front::wgsl::parse::{ast, conv}; |
| 15 |
use crate::front::wgsl::Result; |
| 16 |
use crate::front::Typifier; |
| 17 |
use crate::{ir, proc}; |
| 18 |
use crate::{Arena, FastHashMap, FastIndexMap, Handle, Span}; |
| 19 |
|
| 20 |
mod construction; |
| 21 |
mod conversion; |
| 22 |
|
| 23 |
/// Resolves the inner type of a given expression. |
| 24 |
/// |
| 25 |
/// Expects a &mut [`ExpressionContext`] and a [`Handle<Expression>`]. |
| 26 |
/// |
| 27 |
/// Returns a &[`ir::TypeInner`]. |
| 28 |
/// |
| 29 |
/// Ideally, we would simply have a function that takes a `&mut ExpressionContext` |
| 30 |
/// and returns a `&TypeResolution`. Unfortunately, this leads the borrow checker |
| 31 |
/// to conclude that the mutable borrow lasts for as long as we are using the |
| 32 |
/// `&TypeResolution`, so we can't use the `ExpressionContext` for anything else - |
| 33 |
/// like, say, resolving another operand's type. Using a macro that expands to |
| 34 |
/// two separate calls, only the first of which needs a `&mut`, |
| 35 |
/// lets the borrow checker see that the mutable borrow is over. |
| 36 |
macro_rules! resolve_inner { |
| 37 |
($ctx:ident, $expr:expr) => {{ |
| 38 |
$ctx.grow_types($expr)?; |
| 39 |
$ctx.typifier()[$expr].inner_with(&$ctx.module.types) |
| 40 |
}}; |
| 41 |
} |
| 42 |
pub(super) use resolve_inner; |
| 43 |
|
| 44 |
/// Resolves the inner types of two given expressions. |
| 45 |
/// |
| 46 |
/// Expects a &mut [`ExpressionContext`] and two [`Handle<Expression>`]s. |
| 47 |
/// |
| 48 |
/// Returns a tuple containing two &[`ir::TypeInner`]. |
| 49 |
/// |
| 50 |
/// See the documentation of [`resolve_inner!`] for why this macro is necessary. |
| 51 |
macro_rules! resolve_inner_binary { |
| 52 |
($ctx:ident, $left:expr, $right:expr) => {{ |
| 53 |
$ctx.grow_types($left)?; |
| 54 |
$ctx.grow_types($right)?; |
| 55 |
( |
| 56 |
$ctx.typifier()[$left].inner_with(&$ctx.module.types), |
| 57 |
$ctx.typifier()[$right].inner_with(&$ctx.module.types), |
| 58 |
) |
| 59 |
}}; |
| 60 |
} |
| 61 |
|
| 62 |
/// Resolves the type of a given expression. |
| 63 |
/// |
| 64 |
/// Expects a &mut [`ExpressionContext`] and a [`Handle<Expression>`]. |
| 65 |
/// |
| 66 |
/// Returns a &[`TypeResolution`]. |
| 67 |
/// |
| 68 |
/// See the documentation of [`resolve_inner!`] for why this macro is necessary. |
| 69 |
/// |
| 70 |
/// [`TypeResolution`]: proc::TypeResolution |
| 71 |
macro_rules! resolve { |
| 72 |
($ctx:ident, $expr:expr) => {{ |
| 73 |
$ctx.grow_types($expr)?; |
| 74 |
&$ctx.typifier()[$expr] |
| 75 |
}}; |
| 76 |
} |
| 77 |
pub(super) use resolve; |
| 78 |
|
| 79 |
/// State for constructing a `ir::Module`. |
| 80 |
pub struct GlobalContext<'source, 'temp, 'out> { |
| 81 |
/// The `TranslationUnit`'s expressions arena. |
| 82 |
ast_expressions: &'temp Arena<ast::Expression<'source>>, |
| 83 |
|
| 84 |
/// The `TranslationUnit`'s types arena. |
| 85 |
types: &'temp Arena<ast::Type<'source>>, |
| 86 |
|
| 87 |
// Naga IR values. |
| 88 |
/// The map from the names of module-scope declarations to the Naga IR |
| 89 |
/// `Handle`s we have built for them, owned by `Lowerer::lower`. |
| 90 |
globals: &'temp mut FastHashMap<&'source str, LoweredGlobalDecl>, |
| 91 |
|
| 92 |
/// The module we're constructing. |
| 93 |
module: &'out mut ir::Module, |
| 94 |
|
| 95 |
const_typifier: &'temp mut Typifier, |
| 96 |
|
| 97 |
layouter: &'temp mut proc::Layouter, |
| 98 |
|
| 99 |
global_expression_kind_tracker: &'temp mut proc::ExpressionKindTracker, |
| 100 |
} |
| 101 |
|
| 102 |
impl<'source> GlobalContext<'source, '_, '_> { |
| 103 |
fn as_const(&mut self) -> ExpressionContext<'source, '_, '_> { |
| 104 |
ExpressionContext { |
| 105 |
ast_expressions: self.ast_expressions, |
| 106 |
globals: self.globals, |
| 107 |
types: self.types, |
| 108 |
module: self.module, |
| 109 |
const_typifier: self.const_typifier, |
| 110 |
layouter: self.layouter, |
| 111 |
expr_type: ExpressionContextType::Constant(None), |
| 112 |
global_expression_kind_tracker: self.global_expression_kind_tracker, |
| 113 |
} |
| 114 |
} |
| 115 |
|
| 116 |
fn as_override(&mut self) -> ExpressionContext<'source, '_, '_> { |
| 117 |
ExpressionContext { |
| 118 |
ast_expressions: self.ast_expressions, |
| 119 |
globals: self.globals, |
| 120 |
types: self.types, |
| 121 |
module: self.module, |
| 122 |
const_typifier: self.const_typifier, |
| 123 |
layouter: self.layouter, |
| 124 |
expr_type: ExpressionContextType::Override, |
| 125 |
global_expression_kind_tracker: self.global_expression_kind_tracker, |
| 126 |
} |
| 127 |
} |
| 128 |
|
| 129 |
fn ensure_type_exists( |
| 130 |
&mut self, |
| 131 |
name: Option<String>, |
| 132 |
inner: ir::TypeInner, |
| 133 |
) -> Handle<ir::Type> { |
| 134 |
self.module |
| 135 |
.types |
| 136 |
.insert(ir::Type { inner, name }, Span::UNDEFINED) |
| 137 |
} |
| 138 |
} |
| 139 |
|
| 140 |
/// State for lowering a statement within a function. |
| 141 |
pub struct StatementContext<'source, 'temp, 'out> { |
| 142 |
// WGSL AST values. |
| 143 |
/// A reference to [`TranslationUnit::expressions`] for the translation unit |
| 144 |
/// we're lowering. |
| 145 |
/// |
| 146 |
/// [`TranslationUnit::expressions`]: ast::TranslationUnit::expressions |
| 147 |
ast_expressions: &'temp Arena<ast::Expression<'source>>, |
| 148 |
|
| 149 |
/// A reference to [`TranslationUnit::types`] for the translation unit |
| 150 |
/// we're lowering. |
| 151 |
/// |
| 152 |
/// [`TranslationUnit::types`]: ast::TranslationUnit::types |
| 153 |
types: &'temp Arena<ast::Type<'source>>, |
| 154 |
|
| 155 |
// Naga IR values. |
| 156 |
/// The map from the names of module-scope declarations to the Naga IR |
| 157 |
/// `Handle`s we have built for them, owned by `Lowerer::lower`. |
| 158 |
globals: &'temp mut FastHashMap<&'source str, LoweredGlobalDecl>, |
| 159 |
|
| 160 |
/// A map from each `ast::Local` handle to the Naga expression |
| 161 |
/// we've built for it: |
| 162 |
/// |
| 163 |
/// - WGSL function arguments become Naga [`FunctionArgument`] expressions. |
| 164 |
/// |
| 165 |
/// - WGSL `var` declarations become Naga [`LocalVariable`] expressions. |
| 166 |
/// |
| 167 |
/// - WGSL `let` declararations become arbitrary Naga expressions. |
| 168 |
/// |
| 169 |
/// This always borrows the `local_table` local variable in |
| 170 |
/// [`Lowerer::function`]. |
| 171 |
/// |
| 172 |
/// [`LocalVariable`]: ir::Expression::LocalVariable |
| 173 |
/// [`FunctionArgument`]: ir::Expression::FunctionArgument |
| 174 |
local_table: |
| 175 |
&'temp mut FastHashMap<Handle<ast::Local>, Declared<Typed<Handle<ir::Expression>>>>, |
| 176 |
|
| 177 |
const_typifier: &'temp mut Typifier, |
| 178 |
typifier: &'temp mut Typifier, |
| 179 |
layouter: &'temp mut proc::Layouter, |
| 180 |
function: &'out mut ir::Function, |
| 181 |
/// Stores the names of expressions that are assigned in `let` statement |
| 182 |
/// Also stores the spans of the names, for use in errors. |
| 183 |
named_expressions: &'out mut FastIndexMap<Handle<ir::Expression>, (String, Span)>, |
| 184 |
module: &'out mut ir::Module, |
| 185 |
|
| 186 |
/// Which `Expression`s in `self.naga_expressions` are const expressions, in |
| 187 |
/// the WGSL sense. |
| 188 |
/// |
| 189 |
/// According to the WGSL spec, a const expression must not refer to any |
| 190 |
/// `let` declarations, even if those declarations' initializers are |
| 191 |
/// themselves const expressions. So this tracker is not simply concerned |
| 192 |
/// with the form of the expressions; it is also tracking whether WGSL says |
| 193 |
/// we should consider them to be const. See the use of `force_non_const` in |
| 194 |
/// the code for lowering `let` bindings. |
| 195 |
local_expression_kind_tracker: &'temp mut proc::ExpressionKindTracker, |
| 196 |
global_expression_kind_tracker: &'temp mut proc::ExpressionKindTracker, |
| 197 |
} |
| 198 |
|
| 199 |
impl<'a, 'temp> StatementContext<'a, 'temp, '_> { |
| 200 |
fn as_const<'t>( |
| 201 |
&'t mut self, |
| 202 |
block: &'t mut ir::Block, |
| 203 |
emitter: &'t mut proc::Emitter, |
| 204 |
) -> ExpressionContext<'a, 't, 't> |
| 205 |
where |
| 206 |
'temp: 't, |
| 207 |
{ |
| 208 |
ExpressionContext { |
| 209 |
globals: self.globals, |
| 210 |
types: self.types, |
| 211 |
ast_expressions: self.ast_expressions, |
| 212 |
const_typifier: self.const_typifier, |
| 213 |
layouter: self.layouter, |
| 214 |
global_expression_kind_tracker: self.global_expression_kind_tracker, |
| 215 |
module: self.module, |
| 216 |
expr_type: ExpressionContextType::Constant(Some(LocalExpressionContext { |
| 217 |
local_table: self.local_table, |
| 218 |
function: self.function, |
| 219 |
block, |
| 220 |
emitter, |
| 221 |
typifier: self.typifier, |
| 222 |
local_expression_kind_tracker: self.local_expression_kind_tracker, |
| 223 |
})), |
| 224 |
} |
| 225 |
} |
| 226 |
|
| 227 |
fn as_expression<'t>( |
| 228 |
&'t mut self, |
| 229 |
block: &'t mut ir::Block, |
| 230 |
emitter: &'t mut proc::Emitter, |
| 231 |
) -> ExpressionContext<'a, 't, 't> |
| 232 |
where |
| 233 |
'temp: 't, |
| 234 |
{ |
| 235 |
ExpressionContext { |
| 236 |
globals: self.globals, |
| 237 |
types: self.types, |
| 238 |
ast_expressions: self.ast_expressions, |
| 239 |
const_typifier: self.const_typifier, |
| 240 |
layouter: self.layouter, |
| 241 |
global_expression_kind_tracker: self.global_expression_kind_tracker, |
| 242 |
module: self.module, |
| 243 |
expr_type: ExpressionContextType::Runtime(LocalExpressionContext { |
| 244 |
local_table: self.local_table, |
| 245 |
function: self.function, |
| 246 |
block, |
| 247 |
emitter, |
| 248 |
typifier: self.typifier, |
| 249 |
local_expression_kind_tracker: self.local_expression_kind_tracker, |
| 250 |
}), |
| 251 |
} |
| 252 |
} |
| 253 |
|
| 254 |
#[allow(dead_code)] |
| 255 |
fn as_global(&mut self) -> GlobalContext<'a, '_, '_> { |
| 256 |
GlobalContext { |
| 257 |
ast_expressions: self.ast_expressions, |
| 258 |
globals: self.globals, |
| 259 |
types: self.types, |
| 260 |
module: self.module, |
| 261 |
const_typifier: self.const_typifier, |
| 262 |
layouter: self.layouter, |
| 263 |
global_expression_kind_tracker: self.global_expression_kind_tracker, |
| 264 |
} |
| 265 |
} |
| 266 |
|
| 267 |
fn invalid_assignment_type(&self, expr: Handle<ir::Expression>) -> InvalidAssignmentType { |
| 268 |
if let Some(&(_, span)) = self.named_expressions.get(&expr) { |
| 269 |
InvalidAssignmentType::ImmutableBinding(span) |
| 270 |
} else { |
| 271 |
match self.function.expressions[expr] { |
| 272 |
ir::Expression::Swizzle { .. } => InvalidAssignmentType::Swizzle, |
| 273 |
ir::Expression::Access { base, .. } => self.invalid_assignment_type(base), |
| 274 |
ir::Expression::AccessIndex { base, .. } => self.invalid_assignment_type(base), |
| 275 |
_ => InvalidAssignmentType::Other, |
| 276 |
} |
| 277 |
} |
| 278 |
} |
| 279 |
} |
| 280 |
|
| 281 |
pub struct LocalExpressionContext<'temp, 'out> { |
| 282 |
/// A map from [`ast::Local`] handles to the Naga expressions we've built for them. |
| 283 |
/// |
| 284 |
/// This is always [`StatementContext::local_table`] for the |
| 285 |
/// enclosing statement; see that documentation for details. |
| 286 |
local_table: &'temp FastHashMap<Handle<ast::Local>, Declared<Typed<Handle<ir::Expression>>>>, |
| 287 |
|
| 288 |
function: &'out mut ir::Function, |
| 289 |
block: &'temp mut ir::Block, |
| 290 |
emitter: &'temp mut proc::Emitter, |
| 291 |
typifier: &'temp mut Typifier, |
| 292 |
|
| 293 |
/// Which `Expression`s in `self.naga_expressions` are const expressions, in |
| 294 |
/// the WGSL sense. |
| 295 |
/// |
| 296 |
/// See [`StatementContext::local_expression_kind_tracker`] for details. |
| 297 |
local_expression_kind_tracker: &'temp mut proc::ExpressionKindTracker, |
| 298 |
} |
| 299 |
|
| 300 |
/// The type of Naga IR expression we are lowering an [`ast::Expression`] to. |
| 301 |
pub enum ExpressionContextType<'temp, 'out> { |
| 302 |
/// We are lowering to an arbitrary runtime expression, to be |
| 303 |
/// included in a function's body. |
| 304 |
/// |
| 305 |
/// The given [`LocalExpressionContext`] holds information about local |
| 306 |
/// variables, arguments, and other definitions available only to runtime |
| 307 |
/// expressions, not constant or override expressions. |
| 308 |
Runtime(LocalExpressionContext<'temp, 'out>), |
| 309 |
|
| 310 |
/// We are lowering to a constant expression, to be included in the module's |
| 311 |
/// constant expression arena. |
| 312 |
/// |
| 313 |
/// Everything global constant expressions are allowed to refer to is |
| 314 |
/// available in the [`ExpressionContext`], but local constant expressions can |
| 315 |
/// also refer to other |
| 316 |
Constant(Option<LocalExpressionContext<'temp, 'out>>), |
| 317 |
|
| 318 |
/// We are lowering to an override expression, to be included in the module's |
| 319 |
/// constant expression arena. |
| 320 |
/// |
| 321 |
/// Everything override expressions are allowed to refer to is |
| 322 |
/// available in the [`ExpressionContext`], so this variant |
| 323 |
/// carries no further information. |
| 324 |
Override, |
| 325 |
} |
| 326 |
|
| 327 |
/// State for lowering an [`ast::Expression`] to Naga IR. |
| 328 |
/// |
| 329 |
/// [`ExpressionContext`]s come in two kinds, distinguished by |
| 330 |
/// the value of the [`expr_type`] field: |
| 331 |
/// |
| 332 |
/// - A [`Runtime`] context contributes [`naga::Expression`]s to a [`naga::Function`]'s |
| 333 |
/// runtime expression arena. |
| 334 |
/// |
| 335 |
/// - A [`Constant`] context contributes [`naga::Expression`]s to a [`naga::Module`]'s |
| 336 |
/// constant expression arena. |
| 337 |
/// |
| 338 |
/// [`ExpressionContext`]s are constructed in restricted ways: |
| 339 |
/// |
| 340 |
/// - To get a [`Runtime`] [`ExpressionContext`], call |
| 341 |
/// [`StatementContext::as_expression`]. |
| 342 |
/// |
| 343 |
/// - To get a [`Constant`] [`ExpressionContext`], call |
| 344 |
/// [`GlobalContext::as_const`]. |
| 345 |
/// |
| 346 |
/// - You can demote a [`Runtime`] context to a [`Constant`] context |
| 347 |
/// by calling [`as_const`], but there's no way to go in the other |
| 348 |
/// direction, producing a runtime context from a constant one. This |
| 349 |
/// is because runtime expressions can refer to constant |
| 350 |
/// expressions, via [`Expression::Constant`], but constant |
| 351 |
/// expressions can't refer to a function's expressions. |
| 352 |
/// |
| 353 |
/// Not to be confused with `wgsl::parse::ExpressionContext`, which is |
| 354 |
/// for parsing the `ast::Expression` in the first place. |
| 355 |
/// |
| 356 |
/// [`expr_type`]: ExpressionContext::expr_type |
| 357 |
/// [`Runtime`]: ExpressionContextType::Runtime |
| 358 |
/// [`naga::Expression`]: ir::Expression |
| 359 |
/// [`naga::Function`]: ir::Function |
| 360 |
/// [`Constant`]: ExpressionContextType::Constant |
| 361 |
/// [`naga::Module`]: ir::Module |
| 362 |
/// [`as_const`]: ExpressionContext::as_const |
| 363 |
/// [`Expression::Constant`]: ir::Expression::Constant |
| 364 |
pub struct ExpressionContext<'source, 'temp, 'out> { |
| 365 |
// WGSL AST values. |
| 366 |
ast_expressions: &'temp Arena<ast::Expression<'source>>, |
| 367 |
types: &'temp Arena<ast::Type<'source>>, |
| 368 |
|
| 369 |
// Naga IR values. |
| 370 |
/// The map from the names of module-scope declarations to the Naga IR |
| 371 |
/// `Handle`s we have built for them, owned by `Lowerer::lower`. |
| 372 |
globals: &'temp mut FastHashMap<&'source str, LoweredGlobalDecl>, |
| 373 |
|
| 374 |
/// The IR [`Module`] we're constructing. |
| 375 |
/// |
| 376 |
/// [`Module`]: ir::Module |
| 377 |
module: &'out mut ir::Module, |
| 378 |
|
| 379 |
/// Type judgments for [`module::global_expressions`]. |
| 380 |
/// |
| 381 |
/// [`module::global_expressions`]: ir::Module::global_expressions |
| 382 |
const_typifier: &'temp mut Typifier, |
| 383 |
layouter: &'temp mut proc::Layouter, |
| 384 |
global_expression_kind_tracker: &'temp mut proc::ExpressionKindTracker, |
| 385 |
|
| 386 |
/// Whether we are lowering a constant expression or a general |
| 387 |
/// runtime expression, and the data needed in each case. |
| 388 |
expr_type: ExpressionContextType<'temp, 'out>, |
| 389 |
} |
| 390 |
|
| 391 |
impl TypeContext for ExpressionContext<'_, '_, '_> { |
| 392 |
fn lookup_type(&self, handle: Handle<ir::Type>) -> &ir::Type { |
| 393 |
&self.module.types[handle] |
| 394 |
} |
| 395 |
|
| 396 |
fn type_name(&self, handle: Handle<ir::Type>) -> &str { |
| 397 |
self.module.types[handle] |
| 398 |
.name |
| 399 |
.as_deref() |
| 400 |
.unwrap_or("{anonymous type}") |
| 401 |
} |
| 402 |
|
| 403 |
fn write_override<W: core::fmt::Write>( |
| 404 |
&self, |
| 405 |
handle: Handle<ir::Override>, |
| 406 |
out: &mut W, |
| 407 |
) -> core::fmt::Result { |
| 408 |
match self.module.overrides[handle].name { |
| 409 |
Some(ref name) => out.write_str(name), |
| 410 |
None => write!(out, "{{anonymous override {handle:?}}}"), |
| 411 |
} |
| 412 |
} |
| 413 |
|
| 414 |
fn write_unnamed_struct<W: core::fmt::Write>( |
| 415 |
&self, |
| 416 |
_: &ir::TypeInner, |
| 417 |
_: &mut W, |
| 418 |
) -> core::fmt::Result { |
| 419 |
unreachable!("the WGSL front end should always know the type name"); |
| 420 |
} |
| 421 |
} |
| 422 |
|
| 423 |
impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { |
| 424 |
#[allow(dead_code)] |
| 425 |
fn as_const(&mut self) -> ExpressionContext<'source, '_, '_> { |
| 426 |
ExpressionContext { |
| 427 |
globals: self.globals, |
| 428 |
types: self.types, |
| 429 |
ast_expressions: self.ast_expressions, |
| 430 |
const_typifier: self.const_typifier, |
| 431 |
layouter: self.layouter, |
| 432 |
module: self.module, |
| 433 |
expr_type: ExpressionContextType::Constant(match self.expr_type { |
| 434 |
ExpressionContextType::Runtime(ref mut local_expression_context) |
| 435 |
| ExpressionContextType::Constant(Some(ref mut local_expression_context)) => { |
| 436 |
Some(LocalExpressionContext { |
| 437 |
local_table: local_expression_context.local_table, |
| 438 |
function: local_expression_context.function, |
| 439 |
block: local_expression_context.block, |
| 440 |
emitter: local_expression_context.emitter, |
| 441 |
typifier: local_expression_context.typifier, |
| 442 |
local_expression_kind_tracker: local_expression_context |
| 443 |
.local_expression_kind_tracker, |
| 444 |
}) |
| 445 |
} |
| 446 |
ExpressionContextType::Constant(None) | ExpressionContextType::Override => None, |
| 447 |
}), |
| 448 |
global_expression_kind_tracker: self.global_expression_kind_tracker, |
| 449 |
} |
| 450 |
} |
| 451 |
|
| 452 |
fn as_global(&mut self) -> GlobalContext<'source, '_, '_> { |
| 453 |
GlobalContext { |
| 454 |
ast_expressions: self.ast_expressions, |
| 455 |
globals: self.globals, |
| 456 |
types: self.types, |
| 457 |
module: self.module, |
| 458 |
const_typifier: self.const_typifier, |
| 459 |
layouter: self.layouter, |
| 460 |
global_expression_kind_tracker: self.global_expression_kind_tracker, |
| 461 |
} |
| 462 |
} |
| 463 |
|
| 464 |
fn as_const_evaluator(&mut self) -> proc::ConstantEvaluator { |
| 465 |
match self.expr_type { |
| 466 |
ExpressionContextType::Runtime(ref mut rctx) => { |
| 467 |
proc::ConstantEvaluator::for_wgsl_function( |
| 468 |
self.module, |
| 469 |
&mut rctx.function.expressions, |
| 470 |
rctx.local_expression_kind_tracker, |
| 471 |
self.layouter, |
| 472 |
rctx.emitter, |
| 473 |
rctx.block, |
| 474 |
false, |
| 475 |
) |
| 476 |
} |
| 477 |
ExpressionContextType::Constant(Some(ref mut rctx)) => { |
| 478 |
proc::ConstantEvaluator::for_wgsl_function( |
| 479 |
self.module, |
| 480 |
&mut rctx.function.expressions, |
| 481 |
rctx.local_expression_kind_tracker, |
| 482 |
self.layouter, |
| 483 |
rctx.emitter, |
| 484 |
rctx.block, |
| 485 |
true, |
| 486 |
) |
| 487 |
} |
| 488 |
ExpressionContextType::Constant(None) => proc::ConstantEvaluator::for_wgsl_module( |
| 489 |
self.module, |
| 490 |
self.global_expression_kind_tracker, |
| 491 |
self.layouter, |
| 492 |
false, |
| 493 |
), |
| 494 |
ExpressionContextType::Override => proc::ConstantEvaluator::for_wgsl_module( |
| 495 |
self.module, |
| 496 |
self.global_expression_kind_tracker, |
| 497 |
self.layouter, |
| 498 |
true, |
| 499 |
), |
| 500 |
} |
| 501 |
} |
| 502 |
|
| 503 |
/// Return a wrapper around `value` suitable for formatting. |
| 504 |
/// |
| 505 |
/// Return a wrapper around `value` that implements |
| 506 |
/// [`core::fmt::Display`] in a form suitable for use in |
| 507 |
/// diagnostic messages. |
| 508 |
fn as_diagnostic_display<T>( |
| 509 |
&self, |
| 510 |
value: T, |
| 511 |
) -> crate::common::DiagnosticDisplay<(T, proc::GlobalCtx)> { |
| 512 |
let ctx = self.module.to_ctx(); |
| 513 |
crate::common::DiagnosticDisplay((value, ctx)) |
| 514 |
} |
| 515 |
|
| 516 |
fn append_expression( |
| 517 |
&mut self, |
| 518 |
expr: ir::Expression, |
| 519 |
span: Span, |
| 520 |
) -> Result<'source, Handle<ir::Expression>> { |
| 521 |
let mut eval = self.as_const_evaluator(); |
| 522 |
eval.try_eval_and_append(expr, span) |
| 523 |
.map_err(|e| Box::new(Error::ConstantEvaluatorError(e.into(), span))) |
| 524 |
} |
| 525 |
|
| 526 |
fn const_eval_expr_to_u32( |
| 527 |
&self, |
| 528 |
handle: Handle<ir::Expression>, |
| 529 |
) -> core::result::Result<u32, proc::U32EvalError> { |
| 530 |
match self.expr_type { |
| 531 |
ExpressionContextType::Runtime(ref ctx) => { |
| 532 |
if !ctx.local_expression_kind_tracker.is_const(handle) { |
| 533 |
return Err(proc::U32EvalError::NonConst); |
| 534 |
} |
| 535 |
|
| 536 |
self.module |
| 537 |
.to_ctx() |
| 538 |
.eval_expr_to_u32_from(handle, &ctx.function.expressions) |
| 539 |
} |
| 540 |
ExpressionContextType::Constant(Some(ref ctx)) => { |
| 541 |
assert!(ctx.local_expression_kind_tracker.is_const(handle)); |
| 542 |
self.module |
| 543 |
.to_ctx() |
| 544 |
.eval_expr_to_u32_from(handle, &ctx.function.expressions) |
| 545 |
} |
| 546 |
ExpressionContextType::Constant(None) => self.module.to_ctx().eval_expr_to_u32(handle), |
| 547 |
ExpressionContextType::Override => Err(proc::U32EvalError::NonConst), |
| 548 |
} |
| 549 |
} |
| 550 |
|
| 551 |
/// Return `true` if `handle` is a constant expression. |
| 552 |
fn is_const(&self, handle: Handle<ir::Expression>) -> bool { |
| 553 |
use ExpressionContextType as Ect; |
| 554 |
match self.expr_type { |
| 555 |
Ect::Runtime(ref ctx) | Ect::Constant(Some(ref ctx)) => { |
| 556 |
ctx.local_expression_kind_tracker.is_const(handle) |
| 557 |
} |
| 558 |
Ect::Constant(None) | Ect::Override => { |
| 559 |
self.global_expression_kind_tracker.is_const(handle) |
| 560 |
} |
| 561 |
} |
| 562 |
} |
| 563 |
|
| 564 |
fn get_expression_span(&self, handle: Handle<ir::Expression>) -> Span { |
| 565 |
match self.expr_type { |
| 566 |
ExpressionContextType::Runtime(ref ctx) |
| 567 |
| ExpressionContextType::Constant(Some(ref ctx)) => { |
| 568 |
ctx.function.expressions.get_span(handle) |
| 569 |
} |
| 570 |
ExpressionContextType::Constant(None) | ExpressionContextType::Override => { |
| 571 |
self.module.global_expressions.get_span(handle) |
| 572 |
} |
| 573 |
} |
| 574 |
} |
| 575 |
|
| 576 |
fn typifier(&self) -> &Typifier { |
| 577 |
match self.expr_type { |
| 578 |
ExpressionContextType::Runtime(ref ctx) |
| 579 |
| ExpressionContextType::Constant(Some(ref ctx)) => ctx.typifier, |
| 580 |
ExpressionContextType::Constant(None) | ExpressionContextType::Override => { |
| 581 |
self.const_typifier |
| 582 |
} |
| 583 |
} |
| 584 |
} |
| 585 |
|
| 586 |
fn local( |
| 587 |
&mut self, |
| 588 |
local: &Handle<ast::Local>, |
| 589 |
span: Span, |
| 590 |
) -> Result<'source, Typed<Handle<ir::Expression>>> { |
| 591 |
match self.expr_type { |
| 592 |
ExpressionContextType::Runtime(ref ctx) => Ok(ctx.local_table[local].runtime()), |
| 593 |
ExpressionContextType::Constant(Some(ref ctx)) => ctx.local_table[local] |
| 594 |
.const_time() |
| 595 |
.ok_or(Box::new(Error::UnexpectedOperationInConstContext(span))), |
| 596 |
_ => Err(Box::new(Error::UnexpectedOperationInConstContext(span))), |
| 597 |
} |
| 598 |
} |
| 599 |
|
| 600 |
fn runtime_expression_ctx( |
| 601 |
&mut self, |
| 602 |
span: Span, |
| 603 |
) -> Result<'source, &mut LocalExpressionContext<'temp, 'out>> { |
| 604 |
match self.expr_type { |
| 605 |
ExpressionContextType::Runtime(ref mut ctx) => Ok(ctx), |
| 606 |
ExpressionContextType::Constant(_) | ExpressionContextType::Override => { |
| 607 |
Err(Box::new(Error::UnexpectedOperationInConstContext(span))) |
| 608 |
} |
| 609 |
} |
| 610 |
} |
| 611 |
|
| 612 |
fn gather_component( |
| 613 |
&mut self, |
| 614 |
expr: Handle<ir::Expression>, |
| 615 |
component_span: Span, |
| 616 |
gather_span: Span, |
| 617 |
) -> Result<'source, ir::SwizzleComponent> { |
| 618 |
match self.expr_type { |
| 619 |
ExpressionContextType::Runtime(ref rctx) => { |
| 620 |
if !rctx.local_expression_kind_tracker.is_const(expr) { |
| 621 |
return Err(Box::new(Error::ExpectedConstExprConcreteIntegerScalar( |
| 622 |
component_span, |
| 623 |
))); |
| 624 |
} |
| 625 |
|
| 626 |
let index = self |
| 627 |
.module |
| 628 |
.to_ctx() |
| 629 |
.eval_expr_to_u32_from(expr, &rctx.function.expressions) |
| 630 |
.map_err(|err| match err { |
| 631 |
proc::U32EvalError::NonConst => { |
| 632 |
Error::ExpectedConstExprConcreteIntegerScalar(component_span) |
| 633 |
} |
| 634 |
proc::U32EvalError::Negative => Error::ExpectedNonNegative(component_span), |
| 635 |
})?; |
| 636 |
ir::SwizzleComponent::XYZW |
| 637 |
.get(index as usize) |
| 638 |
.copied() |
| 639 |
.ok_or(Box::new(Error::InvalidGatherComponent(component_span))) |
| 640 |
} |
| 641 |
// This means a `gather` operation appeared in a constant expression. |
| 642 |
// This error refers to the `gather` itself, not its "component" argument. |
| 643 |
ExpressionContextType::Constant(_) | ExpressionContextType::Override => Err(Box::new( |
| 644 |
Error::UnexpectedOperationInConstContext(gather_span), |
| 645 |
)), |
| 646 |
} |
| 647 |
} |
| 648 |
|
| 649 |
/// Determine the type of `handle`, and add it to the module's arena. |
| 650 |
/// |
| 651 |
/// If you just need a `TypeInner` for `handle`'s type, use the |
| 652 |
/// [`resolve_inner!`] macro instead. This function |
| 653 |
/// should only be used when the type of `handle` needs to appear |
| 654 |
/// in the module's final `Arena<Type>`, for example, if you're |
| 655 |
/// creating a [`LocalVariable`] whose type is inferred from its |
| 656 |
/// initializer. |
| 657 |
/// |
| 658 |
/// [`LocalVariable`]: ir::LocalVariable |
| 659 |
fn register_type( |
| 660 |
&mut self, |
| 661 |
handle: Handle<ir::Expression>, |
| 662 |
) -> Result<'source, Handle<ir::Type>> { |
| 663 |
self.grow_types(handle)?; |
| 664 |
// This is equivalent to calling ExpressionContext::typifier(), |
| 665 |
// except that this lets the borrow checker see that it's okay |
| 666 |
// to also borrow self.module.types mutably below. |
| 667 |
let typifier = match self.expr_type { |
| 668 |
ExpressionContextType::Runtime(ref ctx) |
| 669 |
| ExpressionContextType::Constant(Some(ref ctx)) => ctx.typifier, |
| 670 |
ExpressionContextType::Constant(None) | ExpressionContextType::Override => { |
| 671 |
&*self.const_typifier |
| 672 |
} |
| 673 |
}; |
| 674 |
Ok(typifier.register_type(handle, &mut self.module.types)) |
| 675 |
} |
| 676 |
|
| 677 |
/// Resolve the types of all expressions up through `handle`. |
| 678 |
/// |
| 679 |
/// Ensure that [`self.typifier`] has a [`TypeResolution`] for |
| 680 |
/// every expression in [`self.function.expressions`]. |
| 681 |
/// |
| 682 |
/// This does not add types to any arena. The [`Typifier`] |
| 683 |
/// documentation explains the steps we take to avoid filling |
| 684 |
/// arenas with intermediate types. |
| 685 |
/// |
| 686 |
/// This function takes `&mut self`, so it can't conveniently |
| 687 |
/// return a shared reference to the resulting `TypeResolution`: |
| 688 |
/// the shared reference would extend the mutable borrow, and you |
| 689 |
/// wouldn't be able to use `self` for anything else. Instead, you |
| 690 |
/// should use [`register_type`] or one of [`resolve!`], |
| 691 |
/// [`resolve_inner!`] or [`resolve_inner_binary!`]. |
| 692 |
/// |
| 693 |
/// [`self.typifier`]: ExpressionContext::typifier |
| 694 |
/// [`TypeResolution`]: proc::TypeResolution |
| 695 |
/// [`register_type`]: Self::register_type |
| 696 |
/// [`Typifier`]: Typifier |
| 697 |
fn grow_types(&mut self, handle: Handle<ir::Expression>) -> Result<'source, &mut Self> { |
| 698 |
let empty_arena = Arena::new(); |
| 699 |
let resolve_ctx; |
| 700 |
let typifier; |
| 701 |
let expressions; |
| 702 |
match self.expr_type { |
| 703 |
ExpressionContextType::Runtime(ref mut ctx) |
| 704 |
| ExpressionContextType::Constant(Some(ref mut ctx)) => { |
| 705 |
resolve_ctx = proc::ResolveContext::with_locals( |
| 706 |
self.module, |
| 707 |
&ctx.function.local_variables, |
| 708 |
&ctx.function.arguments, |
| 709 |
); |
| 710 |
typifier = &mut *ctx.typifier; |
| 711 |
expressions = &ctx.function.expressions; |
| 712 |
} |
| 713 |
ExpressionContextType::Constant(None) | ExpressionContextType::Override => { |
| 714 |
resolve_ctx = proc::ResolveContext::with_locals(self.module, &empty_arena, &[]); |
| 715 |
typifier = self.const_typifier; |
| 716 |
expressions = &self.module.global_expressions; |
| 717 |
} |
| 718 |
}; |
| 719 |
typifier |
| 720 |
.grow(handle, expressions, &resolve_ctx) |
| 721 |
.map_err(Error::InvalidResolve)?; |
| 722 |
|
| 723 |
Ok(self) |
| 724 |
} |
| 725 |
|
| 726 |
fn image_data( |
| 727 |
&mut self, |
| 728 |
image: Handle<ir::Expression>, |
| 729 |
span: Span, |
| 730 |
) -> Result<'source, (ir::ImageClass, bool)> { |
| 731 |
match *resolve_inner!(self, image) { |
| 732 |
ir::TypeInner::Image { class, arrayed, .. } => Ok((class, arrayed)), |
| 733 |
_ => Err(Box::new(Error::BadTexture(span))), |
| 734 |
} |
| 735 |
} |
| 736 |
|
| 737 |
fn prepare_args<'b>( |
| 738 |
&mut self, |
| 739 |
args: &'b [Handle<ast::Expression<'source>>], |
| 740 |
min_args: u32, |
| 741 |
span: Span, |
| 742 |
) -> ArgumentContext<'b, 'source> { |
| 743 |
ArgumentContext { |
| 744 |
args: args.iter(), |
| 745 |
min_args, |
| 746 |
args_used: 0, |
| 747 |
total_args: args.len() as u32, |
| 748 |
span, |
| 749 |
} |
| 750 |
} |
| 751 |
|
| 752 |
/// Insert splats, if needed by the non-'*' operations. |
| 753 |
/// |
| 754 |
/// See the "Binary arithmetic expressions with mixed scalar and vector operands" |
| 755 |
/// table in the WebGPU Shading Language specification for relevant operators. |
| 756 |
/// |
| 757 |
/// Multiply is not handled here as backends are expected to handle vec*scalar |
| 758 |
/// operations, so inserting splats into the IR increases size needlessly. |
| 759 |
fn binary_op_splat( |
| 760 |
&mut self, |
| 761 |
op: ir::BinaryOperator, |
| 762 |
left: &mut Handle<ir::Expression>, |
| 763 |
right: &mut Handle<ir::Expression>, |
| 764 |
) -> Result<'source, ()> { |
| 765 |
if matches!( |
| 766 |
op, |
| 767 |
ir::BinaryOperator::Add |
| 768 |
| ir::BinaryOperator::Subtract |
| 769 |
| ir::BinaryOperator::Divide |
| 770 |
| ir::BinaryOperator::Modulo |
| 771 |
) { |
| 772 |
match resolve_inner_binary!(self, *left, *right) { |
| 773 |
(&ir::TypeInner::Vector { size, .. }, &ir::TypeInner::Scalar { .. }) => { |
| 774 |
*right = self.append_expression( |
| 775 |
ir::Expression::Splat { |
| 776 |
size, |
| 777 |
value: *right, |
| 778 |
}, |
| 779 |
self.get_expression_span(*right), |
| 780 |
)?; |
| 781 |
} |
| 782 |
(&ir::TypeInner::Scalar { .. }, &ir::TypeInner::Vector { size, .. }) => { |
| 783 |
*left = self.append_expression( |
| 784 |
ir::Expression::Splat { size, value: *left }, |
| 785 |
self.get_expression_span(*left), |
| 786 |
)?; |
| 787 |
} |
| 788 |
_ => {} |
| 789 |
} |
| 790 |
} |
| 791 |
|
| 792 |
Ok(()) |
| 793 |
} |
| 794 |
|
| 795 |
/// Add a single expression to the expression table that is not covered by `self.emitter`. |
| 796 |
/// |
| 797 |
/// This is useful for `CallResult` and `AtomicResult` expressions, which should not be covered by |
| 798 |
/// `Emit` statements. |
| 799 |
fn interrupt_emitter( |
| 800 |
&mut self, |
| 801 |
expression: ir::Expression, |
| 802 |
span: Span, |
| 803 |
) -> Result<'source, Handle<ir::Expression>> { |
| 804 |
match self.expr_type { |
| 805 |
ExpressionContextType::Runtime(ref mut rctx) |
| 806 |
| ExpressionContextType::Constant(Some(ref mut rctx)) => { |
| 807 |
rctx.block |
| 808 |
.extend(rctx.emitter.finish(&rctx.function.expressions)); |
| 809 |
} |
| 810 |
ExpressionContextType::Constant(None) | ExpressionContextType::Override => {} |
| 811 |
} |
| 812 |
let result = self.append_expression(expression, span); |
| 813 |
match self.expr_type { |
| 814 |
ExpressionContextType::Runtime(ref mut rctx) |
| 815 |
| ExpressionContextType::Constant(Some(ref mut rctx)) => { |
| 816 |
rctx.emitter.start(&rctx.function.expressions); |
| 817 |
} |
| 818 |
ExpressionContextType::Constant(None) | ExpressionContextType::Override => {} |
| 819 |
} |
| 820 |
result |
| 821 |
} |
| 822 |
|
| 823 |
/// Apply the WGSL Load Rule to `expr`. |
| 824 |
/// |
| 825 |
/// If `expr` is has type `ref<SC, T, A>`, perform a load to produce a value of type |
| 826 |
/// `T`. Otherwise, return `expr` unchanged. |
| 827 |
fn apply_load_rule( |
| 828 |
&mut self, |
| 829 |
expr: Typed<Handle<ir::Expression>>, |
| 830 |
) -> Result<'source, Handle<ir::Expression>> { |
| 831 |
match expr { |
| 832 |
Typed::Reference(pointer) => { |
| 833 |
let load = ir::Expression::Load { pointer }; |
| 834 |
let span = self.get_expression_span(pointer); |
| 835 |
self.append_expression(load, span) |
| 836 |
} |
| 837 |
Typed::Plain(handle) => Ok(handle), |
| 838 |
} |
| 839 |
} |
| 840 |
|
| 841 |
fn ensure_type_exists(&mut self, inner: ir::TypeInner) -> Handle<ir::Type> { |
| 842 |
self.as_global().ensure_type_exists(None, inner) |
| 843 |
} |
| 844 |
} |
| 845 |
|
| 846 |
struct ArgumentContext<'ctx, 'source> { |
| 847 |
args: core::slice::Iter<'ctx, Handle<ast::Expression<'source>>>, |
| 848 |
min_args: u32, |
| 849 |
args_used: u32, |
| 850 |
total_args: u32, |
| 851 |
span: Span, |
| 852 |
} |
| 853 |
|
| 854 |
impl<'source> ArgumentContext<'_, 'source> { |
| 855 |
pub fn finish(self) -> Result<'source, ()> { |
| 856 |
if self.args.len() == 0 { |
| 857 |
Ok(()) |
| 858 |
} else { |
| 859 |
Err(Box::new(Error::WrongArgumentCount { |
| 860 |
found: self.total_args, |
| 861 |
expected: self.min_args..self.args_used + 1, |
| 862 |
span: self.span, |
| 863 |
})) |
| 864 |
} |
| 865 |
} |
| 866 |
|
| 867 |
pub fn next(&mut self) -> Result<'source, Handle<ast::Expression<'source>>> { |
| 868 |
match self.args.next().copied() { |
| 869 |
Some(arg) => { |
| 870 |
self.args_used += 1; |
| 871 |
Ok(arg) |
| 872 |
} |
| 873 |
None => Err(Box::new(Error::WrongArgumentCount { |
| 874 |
found: self.total_args, |
| 875 |
expected: self.min_args..self.args_used + 1, |
| 876 |
span: self.span, |
| 877 |
})), |
| 878 |
} |
| 879 |
} |
| 880 |
} |
| 881 |
|
| 882 |
#[derive(Debug, Copy, Clone)] |
| 883 |
enum Declared<T> { |
| 884 |
/// Value declared as const |
| 885 |
Const(T), |
| 886 |
|
| 887 |
/// Value declared as non-const |
| 888 |
Runtime(T), |
| 889 |
} |
| 890 |
|
| 891 |
impl<T> Declared<T> { |
| 892 |
fn runtime(self) -> T { |
| 893 |
match self { |
| 894 |
Declared::Const(t) | Declared::Runtime(t) => t, |
| 895 |
} |
| 896 |
} |
| 897 |
|
| 898 |
fn const_time(self) -> Option<T> { |
| 899 |
match self { |
| 900 |
Declared::Const(t) => Some(t), |
| 901 |
Declared::Runtime(_) => None, |
| 902 |
} |
| 903 |
} |
| 904 |
} |
| 905 |
|
| 906 |
/// WGSL type annotations on expressions, types, values, etc. |
| 907 |
/// |
| 908 |
/// Naga and WGSL types are very close, but Naga lacks WGSL's `ref` types, which |
| 909 |
/// we need to know to apply the Load Rule. This enum carries some WGSL or Naga |
| 910 |
/// datum along with enough information to determine its corresponding WGSL |
| 911 |
/// type. |
| 912 |
/// |
| 913 |
/// The `T` type parameter can be any expression-like thing: |
| 914 |
/// |
| 915 |
/// - `Typed<Handle<ir::Type>>` can represent a full WGSL type. For example, |
| 916 |
/// given some Naga `Pointer` type `ptr`, a WGSL reference type is a |
| 917 |
/// `Typed::Reference(ptr)` whereas a WGSL pointer type is a |
| 918 |
/// `Typed::Plain(ptr)`. |
| 919 |
/// |
| 920 |
/// - `Typed<ir::Expression>` or `Typed<Handle<ir::Expression>>` can |
| 921 |
/// represent references similarly. |
| 922 |
/// |
| 923 |
/// Use the `map` and `try_map` methods to convert from one expression |
| 924 |
/// representation to another. |
| 925 |
/// |
| 926 |
/// [`Expression`]: ir::Expression |
| 927 |
#[derive(Debug, Copy, Clone)] |
| 928 |
enum Typed<T> { |
| 929 |
/// A WGSL reference. |
| 930 |
Reference(T), |
| 931 |
|
| 932 |
/// A WGSL plain type. |
| 933 |
Plain(T), |
| 934 |
} |
| 935 |
|
| 936 |
impl<T> Typed<T> { |
| 937 |
fn map<U>(self, mut f: impl FnMut(T) -> U) -> Typed<U> { |
| 938 |
match self { |
| 939 |
Self::Reference(v) => Typed::Reference(f(v)), |
| 940 |
Self::Plain(v) => Typed::Plain(f(v)), |
| 941 |
} |
| 942 |
} |
| 943 |
|
| 944 |
fn try_map<U, E>( |
| 945 |
self, |
| 946 |
mut f: impl FnMut(T) -> core::result::Result<U, E>, |
| 947 |
) -> core::result::Result<Typed<U>, E> { |
| 948 |
Ok(match self { |
| 949 |
Self::Reference(expr) => Typed::Reference(f(expr)?), |
| 950 |
Self::Plain(expr) => Typed::Plain(f(expr)?), |
| 951 |
}) |
| 952 |
} |
| 953 |
} |
| 954 |
|
| 955 |
/// A single vector component or swizzle. |
| 956 |
/// |
| 957 |
/// This represents the things that can appear after the `.` in a vector access |
| 958 |
/// expression: either a single component name, or a series of them, |
| 959 |
/// representing a swizzle. |
| 960 |
enum Components { |
| 961 |
Single(u32), |
| 962 |
Swizzle { |
| 963 |
size: ir::VectorSize, |
| 964 |
pattern: [ir::SwizzleComponent; 4], |
| 965 |
}, |
| 966 |
} |
| 967 |
|
| 968 |
impl Components { |
| 969 |
const fn letter_component(letter: char) -> Option<ir::SwizzleComponent> { |
| 970 |
use ir::SwizzleComponent as Sc; |
| 971 |
match letter { |
| 972 |
'x' | 'r' => Some(Sc::X), |
| 973 |
'y' | 'g' => Some(Sc::Y), |
| 974 |
'z' | 'b' => Some(Sc::Z), |
| 975 |
'w' | 'a' => Some(Sc::W), |
| 976 |
_ => None, |
| 977 |
} |
| 978 |
} |
| 979 |
|
| 980 |
fn single_component(name: &str, name_span: Span) -> Result<u32> { |
| 981 |
let ch = name.chars().next().ok_or(Error::BadAccessor(name_span))?; |
| 982 |
match Self::letter_component(ch) { |
| 983 |
Some(sc) => Ok(sc as u32), |
| 984 |
None => Err(Box::new(Error::BadAccessor(name_span))), |
| 985 |
} |
| 986 |
} |
| 987 |
|
| 988 |
/// Construct a `Components` value from a 'member' name, like `"wzy"` or `"x"`. |
| 989 |
/// |
| 990 |
/// Use `name_span` for reporting errors in parsing the component string. |
| 991 |
fn new(name: &str, name_span: Span) -> Result<Self> { |
| 992 |
let size = match name.len() { |
| 993 |
1 => return Ok(Components::Single(Self::single_component(name, name_span)?)), |
| 994 |
2 => ir::VectorSize::Bi, |
| 995 |
3 => ir::VectorSize::Tri, |
| 996 |
4 => ir::VectorSize::Quad, |
| 997 |
_ => return Err(Box::new(Error::BadAccessor(name_span))), |
| 998 |
}; |
| 999 |
|
| 1000 |
let mut pattern = [ir::SwizzleComponent::X; 4]; |
| 1001 |
for (comp, ch) in pattern.iter_mut().zip(name.chars()) { |
| 1002 |
*comp = Self::letter_component(ch).ok_or(Error::BadAccessor(name_span))?; |
| 1003 |
} |
| 1004 |
|
| 1005 |
if name.chars().all(|c| matches!(c, 'x' | 'y' | 'z' | 'w')) |
| 1006 |
|| name.chars().all(|c| matches!(c, 'r' | 'g' | 'b' | 'a')) |
| 1007 |
{ |
| 1008 |
Ok(Components::Swizzle { size, pattern }) |
| 1009 |
} else { |
| 1010 |
Err(Box::new(Error::BadAccessor(name_span))) |
| 1011 |
} |
| 1012 |
} |
| 1013 |
} |
| 1014 |
|
| 1015 |
/// An `ast::GlobalDecl` for which we have built the Naga IR equivalent. |
| 1016 |
enum LoweredGlobalDecl { |
| 1017 |
Function { |
| 1018 |
handle: Handle<ir::Function>, |
| 1019 |
must_use: bool, |
| 1020 |
}, |
| 1021 |
Var(Handle<ir::GlobalVariable>), |
| 1022 |
Const(Handle<ir::Constant>), |
| 1023 |
Override(Handle<ir::Override>), |
| 1024 |
Type(Handle<ir::Type>), |
| 1025 |
EntryPoint, |
| 1026 |
} |
| 1027 |
|
| 1028 |
enum Texture { |
| 1029 |
Gather, |
| 1030 |
GatherCompare, |
| 1031 |
|
| 1032 |
Sample, |
| 1033 |
SampleBias, |
| 1034 |
SampleCompare, |
| 1035 |
SampleCompareLevel, |
| 1036 |
SampleGrad, |
| 1037 |
SampleLevel, |
| 1038 |
// SampleBaseClampToEdge, |
| 1039 |
} |
| 1040 |
|
| 1041 |
impl Texture { |
| 1042 |
pub fn map(word: &str) -> Option<Self> { |
| 1043 |
Some(match word { |
| 1044 |
"textureGather" => Self::Gather, |
| 1045 |
"textureGatherCompare" => Self::GatherCompare, |
| 1046 |
|
| 1047 |
"textureSample" => Self::Sample, |
| 1048 |
"textureSampleBias" => Self::SampleBias, |
| 1049 |
"textureSampleCompare" => Self::SampleCompare, |
| 1050 |
"textureSampleCompareLevel" => Self::SampleCompareLevel, |
| 1051 |
"textureSampleGrad" => Self::SampleGrad, |
| 1052 |
"textureSampleLevel" => Self::SampleLevel, |
| 1053 |
// "textureSampleBaseClampToEdge" => Some(Self::SampleBaseClampToEdge), |
| 1054 |
_ => return None, |
| 1055 |
}) |
| 1056 |
} |
| 1057 |
|
| 1058 |
pub const fn min_argument_count(&self) -> u32 { |
| 1059 |
match *self { |
| 1060 |
Self::Gather => 3, |
| 1061 |
Self::GatherCompare => 4, |
| 1062 |
|
| 1063 |
Self::Sample => 3, |
| 1064 |
Self::SampleBias => 5, |
| 1065 |
Self::SampleCompare => 5, |
| 1066 |
Self::SampleCompareLevel => 5, |
| 1067 |
Self::SampleGrad => 6, |
| 1068 |
Self::SampleLevel => 5, |
| 1069 |
// Self::SampleBaseClampToEdge => 3, |
| 1070 |
} |
| 1071 |
} |
| 1072 |
} |
| 1073 |
|
| 1074 |
enum SubgroupGather { |
| 1075 |
BroadcastFirst, |
| 1076 |
Broadcast, |
| 1077 |
Shuffle, |
| 1078 |
ShuffleDown, |
| 1079 |
ShuffleUp, |
| 1080 |
ShuffleXor, |
| 1081 |
} |
| 1082 |
|
| 1083 |
impl SubgroupGather { |
| 1084 |
pub fn map(word: &str) -> Option<Self> { |
| 1085 |
Some(match word { |
| 1086 |
"subgroupBroadcastFirst" => Self::BroadcastFirst, |
| 1087 |
"subgroupBroadcast" => Self::Broadcast, |
| 1088 |
"subgroupShuffle" => Self::Shuffle, |
| 1089 |
"subgroupShuffleDown" => Self::ShuffleDown, |
| 1090 |
"subgroupShuffleUp" => Self::ShuffleUp, |
| 1091 |
"subgroupShuffleXor" => Self::ShuffleXor, |
| 1092 |
_ => return None, |
| 1093 |
}) |
| 1094 |
} |
| 1095 |
} |
| 1096 |
|
| 1097 |
/// Whether a declaration accepts abstract types, or concretizes. |
| 1098 |
enum AbstractRule { |
| 1099 |
/// This declaration concretizes its initialization expression. |
| 1100 |
Concretize, |
| 1101 |
|
| 1102 |
/// This declaration can accept initializers with abstract types. |
| 1103 |
Allow, |
| 1104 |
} |
| 1105 |
|
| 1106 |
pub struct Lowerer<'source, 'temp> { |
| 1107 |
index: &'temp Index<'source>, |
| 1108 |
} |
| 1109 |
|
| 1110 |
impl<'source, 'temp> Lowerer<'source, 'temp> { |
| 1111 |
pub const fn new(index: &'temp Index<'source>) -> Self { |
| 1112 |
Self { index } |
| 1113 |
} |
| 1114 |
|
| 1115 |
pub fn lower(&mut self, tu: ast::TranslationUnit<'source>) -> Result<'source, ir::Module> { |
| 1116 |
let mut module = ir::Module { |
| 1117 |
diagnostic_filters: tu.diagnostic_filters, |
| 1118 |
diagnostic_filter_leaf: tu.diagnostic_filter_leaf, |
| 1119 |
..Default::default() |
| 1120 |
}; |
| 1121 |
|
| 1122 |
let mut ctx = GlobalContext { |
| 1123 |
ast_expressions: &tu.expressions, |
| 1124 |
globals: &mut FastHashMap::default(), |
| 1125 |
types: &tu.types, |
| 1126 |
module: &mut module, |
| 1127 |
const_typifier: &mut Typifier::new(), |
| 1128 |
layouter: &mut proc::Layouter::default(), |
| 1129 |
global_expression_kind_tracker: &mut proc::ExpressionKindTracker::new(), |
| 1130 |
}; |
| 1131 |
|
| 1132 |
for decl_handle in self.index.visit_ordered() { |
| 1133 |
let span = tu.decls.get_span(decl_handle); |
| 1134 |
let decl = &tu.decls[decl_handle]; |
| 1135 |
|
| 1136 |
match decl.kind { |
| 1137 |
ast::GlobalDeclKind::Fn(ref f) => { |
| 1138 |
let lowered_decl = self.function(f, span, &mut ctx)?; |
| 1139 |
ctx.globals.insert(f.name.name, lowered_decl); |
| 1140 |
} |
| 1141 |
ast::GlobalDeclKind::Var(ref v) => { |
| 1142 |
let explicit_ty = |
| 1143 |
v.ty.map(|ast| self.resolve_ast_type(ast, &mut ctx.as_const())) |
| 1144 |
.transpose()?; |
| 1145 |
|
| 1146 |
let (ty, initializer) = self.type_and_init( |
| 1147 |
v.name, |
| 1148 |
v.init, |
| 1149 |
explicit_ty, |
| 1150 |
AbstractRule::Concretize, |
| 1151 |
&mut ctx.as_override(), |
| 1152 |
)?; |
| 1153 |
|
| 1154 |
let binding = if let Some(ref binding) = v.binding { |
| 1155 |
Some(ir::ResourceBinding { |
| 1156 |
group: self.const_u32(binding.group, &mut ctx.as_const())?.0, |
| 1157 |
binding: self.const_u32(binding.binding, &mut ctx.as_const())?.0, |
| 1158 |
}) |
| 1159 |
} else { |
| 1160 |
None |
| 1161 |
}; |
| 1162 |
|
| 1163 |
let handle = ctx.module.global_variables.append( |
| 1164 |
ir::GlobalVariable { |
| 1165 |
name: Some(v.name.name.to_string()), |
| 1166 |
space: v.space, |
| 1167 |
binding, |
| 1168 |
ty, |
| 1169 |
init: initializer, |
| 1170 |
}, |
| 1171 |
span, |
| 1172 |
); |
| 1173 |
|
| 1174 |
ctx.globals |
| 1175 |
.insert(v.name.name, LoweredGlobalDecl::Var(handle)); |
| 1176 |
} |
| 1177 |
ast::GlobalDeclKind::Const(ref c) => { |
| 1178 |
let mut ectx = ctx.as_const(); |
| 1179 |
|
| 1180 |
let explicit_ty = |
| 1181 |
c.ty.map(|ast| self.resolve_ast_type(ast, &mut ectx)) |
| 1182 |
.transpose()?; |
| 1183 |
|
| 1184 |
let (ty, init) = self.type_and_init( |
| 1185 |
c.name, |
| 1186 |
Some(c.init), |
| 1187 |
explicit_ty, |
| 1188 |
AbstractRule::Allow, |
| 1189 |
&mut ectx, |
| 1190 |
)?; |
| 1191 |
let init = init.expect("Global const must have init"); |
| 1192 |
|
| 1193 |
let handle = ctx.module.constants.append( |
| 1194 |
ir::Constant { |
| 1195 |
name: Some(c.name.name.to_string()), |
| 1196 |
ty, |
| 1197 |
init, |
| 1198 |
}, |
| 1199 |
span, |
| 1200 |
); |
| 1201 |
|
| 1202 |
ctx.globals |
| 1203 |
.insert(c.name.name, LoweredGlobalDecl::Const(handle)); |
| 1204 |
} |
| 1205 |
ast::GlobalDeclKind::Override(ref o) => { |
| 1206 |
let explicit_ty = |
| 1207 |
o.ty.map(|ast| self.resolve_ast_type(ast, &mut ctx.as_const())) |
| 1208 |
.transpose()?; |
| 1209 |
|
| 1210 |
let mut ectx = ctx.as_override(); |
| 1211 |
|
| 1212 |
let (ty, init) = self.type_and_init( |
| 1213 |
o.name, |
| 1214 |
o.init, |
| 1215 |
explicit_ty, |
| 1216 |
AbstractRule::Concretize, |
| 1217 |
&mut ectx, |
| 1218 |
)?; |
| 1219 |
|
| 1220 |
let id = |
| 1221 |
o.id.map(|id| self.const_u32(id, &mut ctx.as_const())) |
| 1222 |
.transpose()?; |
| 1223 |
|
| 1224 |
let id = if let Some((id, id_span)) = id { |
| 1225 |
Some( |
| 1226 |
u16::try_from(id) |
| 1227 |
.map_err(|_| Error::PipelineConstantIDValue(id_span))?, |
| 1228 |
) |
| 1229 |
} else { |
| 1230 |
None |
| 1231 |
}; |
| 1232 |
|
| 1233 |
let handle = ctx.module.overrides.append( |
| 1234 |
ir::Override { |
| 1235 |
name: Some(o.name.name.to_string()), |
| 1236 |
id, |
| 1237 |
ty, |
| 1238 |
init, |
| 1239 |
}, |
| 1240 |
span, |
| 1241 |
); |
| 1242 |
|
| 1243 |
ctx.globals |
| 1244 |
.insert(o.name.name, LoweredGlobalDecl::Override(handle)); |
| 1245 |
} |
| 1246 |
ast::GlobalDeclKind::Struct(ref s) => { |
| 1247 |
let handle = self.r#struct(s, span, &mut ctx)?; |
| 1248 |
ctx.globals |
| 1249 |
.insert(s.name.name, LoweredGlobalDecl::Type(handle)); |
| 1250 |
} |
| 1251 |
ast::GlobalDeclKind::Type(ref alias) => { |
| 1252 |
let ty = self.resolve_named_ast_type( |
| 1253 |
alias.ty, |
| 1254 |
Some(alias.name.name.to_string()), |
| 1255 |
&mut ctx.as_const(), |
| 1256 |
)?; |
| 1257 |
ctx.globals |
| 1258 |
.insert(alias.name.name, LoweredGlobalDecl::Type(ty)); |
| 1259 |
} |
| 1260 |
ast::GlobalDeclKind::ConstAssert(condition) => { |
| 1261 |
let condition = self.expression(condition, &mut ctx.as_const())?; |
| 1262 |
|
| 1263 |
let span = ctx.module.global_expressions.get_span(condition); |
| 1264 |
match ctx |
| 1265 |
.module |
| 1266 |
.to_ctx() |
| 1267 |
.eval_expr_to_bool_from(condition, &ctx.module.global_expressions) |
| 1268 |
{ |
| 1269 |
Some(true) => Ok(()), |
| 1270 |
Some(false) => Err(Error::ConstAssertFailed(span)), |
| 1271 |
_ => Err(Error::NotBool(span)), |
| 1272 |
}?; |
| 1273 |
} |
| 1274 |
} |
| 1275 |
} |
| 1276 |
|
| 1277 |
// Constant evaluation may leave abstract-typed literals and |
| 1278 |
// compositions in expression arenas, so we need to compact the module |
| 1279 |
// to remove unused expressions and types. |
| 1280 |
crate::compact::compact(&mut module); |
| 1281 |
|
| 1282 |
Ok(module) |
| 1283 |
} |
| 1284 |
|
| 1285 |
/// Obtain (inferred) type and initializer after automatic conversion |
| 1286 |
fn type_and_init( |
| 1287 |
&mut self, |
| 1288 |
name: ast::Ident<'source>, |
| 1289 |
init: Option<Handle<ast::Expression<'source>>>, |
| 1290 |
explicit_ty: Option<Handle<ir::Type>>, |
| 1291 |
abstract_rule: AbstractRule, |
| 1292 |
ectx: &mut ExpressionContext<'source, '_, '_>, |
| 1293 |
) -> Result<'source, (Handle<ir::Type>, Option<Handle<ir::Expression>>)> { |
| 1294 |
let ty; |
| 1295 |
let initializer; |
| 1296 |
match (init, explicit_ty) { |
| 1297 |
(Some(init), Some(explicit_ty)) => { |
| 1298 |
let init = self.expression_for_abstract(init, ectx)?; |
| 1299 |
let ty_res = proc::TypeResolution::Handle(explicit_ty); |
| 1300 |
let init = ectx |
| 1301 |
.try_automatic_conversions(init, &ty_res, name.span) |
| 1302 |
.map_err(|error| match *error { |
| 1303 |
Error::AutoConversion(e) => Box::new(Error::InitializationTypeMismatch { |
| 1304 |
name: name.span, |
| 1305 |
expected: e.dest_type, |
| 1306 |
got: e.source_type, |
| 1307 |
}), |
| 1308 |
_ => error, |
| 1309 |
})?; |
| 1310 |
|
| 1311 |
let init_ty = ectx.register_type(init)?; |
| 1312 |
if !ectx.module.compare_types( |
| 1313 |
&proc::TypeResolution::Handle(explicit_ty), |
| 1314 |
&proc::TypeResolution::Handle(init_ty), |
| 1315 |
) { |
| 1316 |
return Err(Box::new(Error::InitializationTypeMismatch { |
| 1317 |
name: name.span, |
| 1318 |
expected: ectx.type_to_string(explicit_ty), |
| 1319 |
got: ectx.type_to_string(init_ty), |
| 1320 |
})); |
| 1321 |
} |
| 1322 |
ty = explicit_ty; |
| 1323 |
initializer = Some(init); |
| 1324 |
} |
| 1325 |
(Some(init), None) => { |
| 1326 |
let mut init = self.expression_for_abstract(init, ectx)?; |
| 1327 |
if let AbstractRule::Concretize = abstract_rule { |
| 1328 |
init = ectx.concretize(init)?; |
| 1329 |
} |
| 1330 |
ty = ectx.register_type(init)?; |
| 1331 |
initializer = Some(init); |
| 1332 |
} |
| 1333 |
(None, Some(explicit_ty)) => { |
| 1334 |
ty = explicit_ty; |
| 1335 |
initializer = None; |
| 1336 |
} |
| 1337 |
(None, None) => return Err(Box::new(Error::DeclMissingTypeAndInit(name.span))), |
| 1338 |
} |
| 1339 |
Ok((ty, initializer)) |
| 1340 |
} |
| 1341 |
|
| 1342 |
fn function( |
| 1343 |
&mut self, |
| 1344 |
f: &ast::Function<'source>, |
| 1345 |
span: Span, |
| 1346 |
ctx: &mut GlobalContext<'source, '_, '_>, |
| 1347 |
) -> Result<'source, LoweredGlobalDecl> { |
| 1348 |
let mut local_table = FastHashMap::default(); |
| 1349 |
let mut expressions = Arena::new(); |
| 1350 |
let mut named_expressions = FastIndexMap::default(); |
| 1351 |
let mut local_expression_kind_tracker = proc::ExpressionKindTracker::new(); |
| 1352 |
|
| 1353 |
let arguments = f |
| 1354 |
.arguments |
| 1355 |
.iter() |
| 1356 |
.enumerate() |
| 1357 |
.map(|(i, arg)| -> Result<'_, _> { |
| 1358 |
let ty = self.resolve_ast_type(arg.ty, &mut ctx.as_const())?; |
| 1359 |
let expr = |
| 1360 |
expressions.append(ir::Expression::FunctionArgument(i as u32), arg.name.span); |
| 1361 |
local_table.insert(arg.handle, Declared::Runtime(Typed::Plain(expr))); |
| 1362 |
named_expressions.insert(expr, (arg.name.name.to_string(), arg.name.span)); |
| 1363 |
local_expression_kind_tracker.insert(expr, proc::ExpressionKind::Runtime); |
| 1364 |
|
| 1365 |
Ok(ir::FunctionArgument { |
| 1366 |
name: Some(arg.name.name.to_string()), |
| 1367 |
ty, |
| 1368 |
binding: self.binding(&arg.binding, ty, ctx)?, |
| 1369 |
}) |
| 1370 |
}) |
| 1371 |
.collect::<Result<Vec<_>>>()?; |
| 1372 |
|
| 1373 |
let result = f |
| 1374 |
.result |
| 1375 |
.as_ref() |
| 1376 |
.map(|res| -> Result<'_, _> { |
| 1377 |
let ty = self.resolve_ast_type(res.ty, &mut ctx.as_const())?; |
| 1378 |
Ok(ir::FunctionResult { |
| 1379 |
ty, |
| 1380 |
binding: self.binding(&res.binding, ty, ctx)?, |
| 1381 |
}) |
| 1382 |
}) |
| 1383 |
.transpose()?; |
| 1384 |
|
| 1385 |
let mut function = ir::Function { |
| 1386 |
name: Some(f.name.name.to_string()), |
| 1387 |
arguments, |
| 1388 |
result, |
| 1389 |
local_variables: Arena::new(), |
| 1390 |
expressions, |
| 1391 |
named_expressions: crate::NamedExpressions::default(), |
| 1392 |
body: ir::Block::default(), |
| 1393 |
diagnostic_filter_leaf: f.diagnostic_filter_leaf, |
| 1394 |
}; |
| 1395 |
|
| 1396 |
let mut typifier = Typifier::default(); |
| 1397 |
let mut stmt_ctx = StatementContext { |
| 1398 |
local_table: &mut local_table, |
| 1399 |
globals: ctx.globals, |
| 1400 |
ast_expressions: ctx.ast_expressions, |
| 1401 |
const_typifier: ctx.const_typifier, |
| 1402 |
typifier: &mut typifier, |
| 1403 |
layouter: ctx.layouter, |
| 1404 |
function: &mut function, |
| 1405 |
named_expressions: &mut named_expressions, |
| 1406 |
types: ctx.types, |
| 1407 |
module: ctx.module, |
| 1408 |
local_expression_kind_tracker: &mut local_expression_kind_tracker, |
| 1409 |
global_expression_kind_tracker: ctx.global_expression_kind_tracker, |
| 1410 |
}; |
| 1411 |
let mut body = self.block(&f.body, false, &mut stmt_ctx)?; |
| 1412 |
proc::ensure_block_returns(&mut body); |
| 1413 |
|
| 1414 |
function.body = body; |
| 1415 |
function.named_expressions = named_expressions |
| 1416 |
.into_iter() |
| 1417 |
.map(|(key, (name, _))| (key, name)) |
| 1418 |
.collect(); |
| 1419 |
|
| 1420 |
if let Some(ref entry) = f.entry_point { |
| 1421 |
let workgroup_size_info = if let Some(workgroup_size) = entry.workgroup_size { |
| 1422 |
// TODO: replace with try_map once stabilized |
| 1423 |
let mut workgroup_size_out = [1; 3]; |
| 1424 |
let mut workgroup_size_overrides_out = [None; 3]; |
| 1425 |
for (i, size) in workgroup_size.into_iter().enumerate() { |
| 1426 |
if let Some(size_expr) = size { |
| 1427 |
match self.const_u32(size_expr, &mut ctx.as_const()) { |
| 1428 |
Ok(value) => { |
| 1429 |
workgroup_size_out[i] = value.0; |
| 1430 |
} |
| 1431 |
Err(err) => { |
| 1432 |
if let Error::ConstantEvaluatorError(ref ty, _) = *err { |
| 1433 |
match **ty { |
| 1434 |
proc::ConstantEvaluatorError::OverrideExpr => { |
| 1435 |
workgroup_size_overrides_out[i] = |
| 1436 |
Some(self.workgroup_size_override( |
| 1437 |
size_expr, |
| 1438 |
&mut ctx.as_override(), |
| 1439 |
)?); |
| 1440 |
} |
| 1441 |
_ => { |
| 1442 |
return Err(err); |
| 1443 |
} |
| 1444 |
} |
| 1445 |
} else { |
| 1446 |
return Err(err); |
| 1447 |
} |
| 1448 |
} |
| 1449 |
} |
| 1450 |
} |
| 1451 |
} |
| 1452 |
if workgroup_size_overrides_out.iter().all(|x| x.is_none()) { |
| 1453 |
(workgroup_size_out, None) |
| 1454 |
} else { |
| 1455 |
(workgroup_size_out, Some(workgroup_size_overrides_out)) |
| 1456 |
} |
| 1457 |
} else { |
| 1458 |
([0; 3], None) |
| 1459 |
}; |
| 1460 |
|
| 1461 |
let (workgroup_size, workgroup_size_overrides) = workgroup_size_info; |
| 1462 |
ctx.module.entry_points.push(ir::EntryPoint { |
| 1463 |
name: f.name.name.to_string(), |
| 1464 |
stage: entry.stage, |
| 1465 |
early_depth_test: entry.early_depth_test, |
| 1466 |
workgroup_size, |
| 1467 |
workgroup_size_overrides, |
| 1468 |
function, |
| 1469 |
}); |
| 1470 |
Ok(LoweredGlobalDecl::EntryPoint) |
| 1471 |
} else { |
| 1472 |
let handle = ctx.module.functions.append(function, span); |
| 1473 |
Ok(LoweredGlobalDecl::Function { |
| 1474 |
handle, |
| 1475 |
must_use: f.result.as_ref().is_some_and(|res| res.must_use), |
| 1476 |
}) |
| 1477 |
} |
| 1478 |
} |
| 1479 |
|
| 1480 |
fn workgroup_size_override( |
| 1481 |
&mut self, |
| 1482 |
size_expr: Handle<ast::Expression<'source>>, |
| 1483 |
ctx: &mut ExpressionContext<'source, '_, '_>, |
| 1484 |
) -> Result<'source, Handle<ir::Expression>> { |
| 1485 |
let span = ctx.ast_expressions.get_span(size_expr); |
| 1486 |
let expr = self.expression(size_expr, ctx)?; |
| 1487 |
match resolve_inner!(ctx, expr).scalar_kind().ok_or(0) { |
| 1488 |
Ok(ir::ScalarKind::Sint) | Ok(ir::ScalarKind::Uint) => Ok(expr), |
| 1489 |
_ => Err(Box::new(Error::ExpectedConstExprConcreteIntegerScalar( |
| 1490 |
span, |
| 1491 |
))), |
| 1492 |
} |
| 1493 |
} |
| 1494 |
|
| 1495 |
fn block( |
| 1496 |
&mut self, |
| 1497 |
b: &ast::Block<'source>, |
| 1498 |
is_inside_loop: bool, |
| 1499 |
ctx: &mut StatementContext<'source, '_, '_>, |
| 1500 |
) -> Result<'source, ir::Block> { |
| 1501 |
let mut block = ir::Block::default(); |
| 1502 |
|
| 1503 |
for stmt in b.stmts.iter() { |
| 1504 |
self.statement(stmt, &mut block, is_inside_loop, ctx)?; |
| 1505 |
} |
| 1506 |
|
| 1507 |
Ok(block) |
| 1508 |
} |
| 1509 |
|
| 1510 |
fn statement( |
| 1511 |
&mut self, |
| 1512 |
stmt: &ast::Statement<'source>, |
| 1513 |
block: &mut ir::Block, |
| 1514 |
is_inside_loop: bool, |
| 1515 |
ctx: &mut StatementContext<'source, '_, '_>, |
| 1516 |
) -> Result<'source, ()> { |
| 1517 |
let out = match stmt.kind { |
| 1518 |
ast::StatementKind::Block(ref block) => { |
| 1519 |
let block = self.block(block, is_inside_loop, ctx)?; |
| 1520 |
ir::Statement::Block(block) |
| 1521 |
} |
| 1522 |
ast::StatementKind::LocalDecl(ref decl) => match *decl { |
| 1523 |
ast::LocalDecl::Let(ref l) => { |
| 1524 |
let mut emitter = proc::Emitter::default(); |
| 1525 |
emitter.start(&ctx.function.expressions); |
| 1526 |
|
| 1527 |
let explicit_ty = l |
| 1528 |
.ty |
| 1529 |
.map(|ty| self.resolve_ast_type(ty, &mut ctx.as_const(block, &mut emitter))) |
| 1530 |
.transpose()?; |
| 1531 |
|
| 1532 |
let mut ectx = ctx.as_expression(block, &mut emitter); |
| 1533 |
|
| 1534 |
let (_ty, initializer) = self.type_and_init( |
| 1535 |
l.name, |
| 1536 |
Some(l.init), |
| 1537 |
explicit_ty, |
| 1538 |
AbstractRule::Concretize, |
| 1539 |
&mut ectx, |
| 1540 |
)?; |
| 1541 |
|
| 1542 |
// We passed `Some()` to `type_and_init`, so we |
| 1543 |
// will get a lowered initializer expression back. |
| 1544 |
let initializer = |
| 1545 |
initializer.expect("type_and_init did not return an initializer"); |
| 1546 |
|
| 1547 |
// The WGSL spec says that any expression that refers to a |
| 1548 |
// `let`-bound variable is not a const expression. This |
| 1549 |
// affects when errors must be reported, so we can't even |
| 1550 |
// treat suitable `let` bindings as constant as an |
| 1551 |
// optimization. |
| 1552 |
ctx.local_expression_kind_tracker |
| 1553 |
.force_non_const(initializer); |
| 1554 |
|
| 1555 |
block.extend(emitter.finish(&ctx.function.expressions)); |
| 1556 |
ctx.local_table |
| 1557 |
.insert(l.handle, Declared::Runtime(Typed::Plain(initializer))); |
| 1558 |
ctx.named_expressions |
| 1559 |
.insert(initializer, (l.name.name.to_string(), l.name.span)); |
| 1560 |
|
| 1561 |
return Ok(()); |
| 1562 |
} |
| 1563 |
ast::LocalDecl::Var(ref v) => { |
| 1564 |
let mut emitter = proc::Emitter::default(); |
| 1565 |
emitter.start(&ctx.function.expressions); |
| 1566 |
|
| 1567 |
let explicit_ty = |
| 1568 |
v.ty.map(|ast| { |
| 1569 |
self.resolve_ast_type(ast, &mut ctx.as_const(block, &mut emitter)) |
| 1570 |
}) |
| 1571 |
.transpose()?; |
| 1572 |
|
| 1573 |
let mut ectx = ctx.as_expression(block, &mut emitter); |
| 1574 |
let (ty, initializer) = self.type_and_init( |
| 1575 |
v.name, |
| 1576 |
v.init, |
| 1577 |
explicit_ty, |
| 1578 |
AbstractRule::Concretize, |
| 1579 |
&mut ectx, |
| 1580 |
)?; |
| 1581 |
|
| 1582 |
let (const_initializer, initializer) = { |
| 1583 |
match initializer { |
| 1584 |
Some(init) => { |
| 1585 |
// It's not correct to hoist the initializer up |
| 1586 |
// to the top of the function if: |
| 1587 |
// - the initialization is inside a loop, and should |
| 1588 |
// take place on every iteration, or |
| 1589 |
// - the initialization is not a constant |
| 1590 |
// expression, so its value depends on the |
| 1591 |
// state at the point of initialization. |
| 1592 |
if is_inside_loop |
| 1593 |
|| !ctx.local_expression_kind_tracker.is_const_or_override(init) |
| 1594 |
{ |
| 1595 |
(None, Some(init)) |
| 1596 |
} else { |
| 1597 |
(Some(init), None) |
| 1598 |
} |
| 1599 |
} |
| 1600 |
None => (None, None), |
| 1601 |
} |
| 1602 |
}; |
| 1603 |
|
| 1604 |
let var = ctx.function.local_variables.append( |
| 1605 |
ir::LocalVariable { |
| 1606 |
name: Some(v.name.name.to_string()), |
| 1607 |
ty, |
| 1608 |
init: const_initializer, |
| 1609 |
}, |
| 1610 |
stmt.span, |
| 1611 |
); |
| 1612 |
|
| 1613 |
let handle = ctx |
| 1614 |
.as_expression(block, &mut emitter) |
| 1615 |
.interrupt_emitter(ir::Expression::LocalVariable(var), Span::UNDEFINED)?; |
| 1616 |
block.extend(emitter.finish(&ctx.function.expressions)); |
| 1617 |
ctx.local_table |
| 1618 |
.insert(v.handle, Declared::Runtime(Typed::Reference(handle))); |
| 1619 |
|
| 1620 |
match initializer { |
| 1621 |
Some(initializer) => ir::Statement::Store { |
| 1622 |
pointer: handle, |
| 1623 |
value: initializer, |
| 1624 |
}, |
| 1625 |
None => return Ok(()), |
| 1626 |
} |
| 1627 |
} |
| 1628 |
ast::LocalDecl::Const(ref c) => { |
| 1629 |
let mut emitter = proc::Emitter::default(); |
| 1630 |
emitter.start(&ctx.function.expressions); |
| 1631 |
|
| 1632 |
let ectx = &mut ctx.as_const(block, &mut emitter); |
| 1633 |
|
| 1634 |
let explicit_ty = |
| 1635 |
c.ty.map(|ast| self.resolve_ast_type(ast, &mut ectx.as_const())) |
| 1636 |
.transpose()?; |
| 1637 |
|
| 1638 |
let (_ty, init) = self.type_and_init( |
| 1639 |
c.name, |
| 1640 |
Some(c.init), |
| 1641 |
explicit_ty, |
| 1642 |
AbstractRule::Allow, |
| 1643 |
&mut ectx.as_const(), |
| 1644 |
)?; |
| 1645 |
let init = init.expect("Local const must have init"); |
| 1646 |
|
| 1647 |
block.extend(emitter.finish(&ctx.function.expressions)); |
| 1648 |
ctx.local_table |
| 1649 |
.insert(c.handle, Declared::Const(Typed::Plain(init))); |
| 1650 |
return Ok(()); |
| 1651 |
} |
| 1652 |
}, |
| 1653 |
ast::StatementKind::If { |
| 1654 |
condition, |
| 1655 |
ref accept, |
| 1656 |
ref reject, |
| 1657 |
} => { |
| 1658 |
let mut emitter = proc::Emitter::default(); |
| 1659 |
emitter.start(&ctx.function.expressions); |
| 1660 |
|
| 1661 |
let condition = |
| 1662 |
self.expression(condition, &mut ctx.as_expression(block, &mut emitter))?; |
| 1663 |
block.extend(emitter.finish(&ctx.function.expressions)); |
| 1664 |
|
| 1665 |
let accept = self.block(accept, is_inside_loop, ctx)?; |
| 1666 |
let reject = self.block(reject, is_inside_loop, ctx)?; |
| 1667 |
|
| 1668 |
ir::Statement::If { |
| 1669 |
condition, |
| 1670 |
accept, |
| 1671 |
reject, |
| 1672 |
} |
| 1673 |
} |
| 1674 |
ast::StatementKind::Switch { |
| 1675 |
selector, |
| 1676 |
ref cases, |
| 1677 |
} => { |
| 1678 |
let mut emitter = proc::Emitter::default(); |
| 1679 |
emitter.start(&ctx.function.expressions); |
| 1680 |
|
| 1681 |
let mut ectx = ctx.as_expression(block, &mut emitter); |
| 1682 |
|
| 1683 |
// Determine the scalar type of the selector and case expressions, find the |
| 1684 |
// consensus type for automatic conversion, then convert them. |
| 1685 |
let (mut exprs, spans) = core::iter::once(selector) |
| 1686 |
.chain(cases.iter().filter_map(|case| match case.value { |
| 1687 |
ast::SwitchValue::Expr(expr) => Some(expr), |
| 1688 |
ast::SwitchValue::Default => None, |
| 1689 |
})) |
| 1690 |
.enumerate() |
| 1691 |
.map(|(i, expr)| { |
| 1692 |
let span = ectx.ast_expressions.get_span(expr); |
| 1693 |
let expr = self.expression_for_abstract(expr, &mut ectx)?; |
| 1694 |
let ty = resolve_inner!(ectx, expr); |
| 1695 |
match *ty { |
| 1696 |
ir::TypeInner::Scalar( |
| 1697 |
ir::Scalar::I32 | ir::Scalar::U32 | ir::Scalar::ABSTRACT_INT, |
| 1698 |
) => Ok((expr, span)), |
| 1699 |
_ => match i { |
| 1700 |
0 => Err(Box::new(Error::InvalidSwitchSelector { span })), |
| 1701 |
_ => Err(Box::new(Error::InvalidSwitchCase { span })), |
| 1702 |
}, |
| 1703 |
} |
| 1704 |
}) |
| 1705 |
.collect::<Result<(Vec<_>, Vec<_>)>>()?; |
| 1706 |
|
| 1707 |
let mut consensus = |
| 1708 |
ectx.automatic_conversion_consensus(&exprs) |
| 1709 |
.map_err(|span_idx| Error::SwitchCaseTypeMismatch { |
| 1710 |
span: spans[span_idx], |
| 1711 |
})?; |
| 1712 |
// Concretize to I32 if the selector and all cases were abstract |
| 1713 |
if consensus == ir::Scalar::ABSTRACT_INT { |
| 1714 |
consensus = ir::Scalar::I32; |
| 1715 |
} |
| 1716 |
for expr in &mut exprs { |
| 1717 |
ectx.convert_to_leaf_scalar(expr, consensus)?; |
| 1718 |
} |
| 1719 |
|
| 1720 |
block.extend(emitter.finish(&ctx.function.expressions)); |
| 1721 |
|
| 1722 |
let mut exprs = exprs.into_iter(); |
| 1723 |
let selector = exprs |
| 1724 |
.next() |
| 1725 |
.expect("First element should be selector expression"); |
| 1726 |
|
| 1727 |
let cases = cases |
| 1728 |
.iter() |
| 1729 |
.map(|case| { |
| 1730 |
Ok(ir::SwitchCase { |
| 1731 |
value: match case.value { |
| 1732 |
ast::SwitchValue::Expr(expr) => { |
| 1733 |
let span = ctx.ast_expressions.get_span(expr); |
| 1734 |
let expr = exprs.next().expect( |
| 1735 |
"Should yield expression for each SwitchValue::Expr case", |
| 1736 |
); |
| 1737 |
match ctx |
| 1738 |
.module |
| 1739 |
.to_ctx() |
| 1740 |
.eval_expr_to_literal_from(expr, &ctx.function.expressions) |
| 1741 |
{ |
| 1742 |
Some(ir::Literal::I32(value)) => { |
| 1743 |
ir::SwitchValue::I32(value) |
| 1744 |
} |
| 1745 |
Some(ir::Literal::U32(value)) => { |
| 1746 |
ir::SwitchValue::U32(value) |
| 1747 |
} |
| 1748 |
_ => { |
| 1749 |
return Err(Box::new(Error::InvalidSwitchCase { |
| 1750 |
span, |
| 1751 |
})); |
| 1752 |
} |
| 1753 |
} |
| 1754 |
} |
| 1755 |
ast::SwitchValue::Default => ir::SwitchValue::Default, |
| 1756 |
}, |
| 1757 |
body: self.block(&case.body, is_inside_loop, ctx)?, |
| 1758 |
fall_through: case.fall_through, |
| 1759 |
}) |
| 1760 |
}) |
| 1761 |
.collect::<Result<_>>()?; |
| 1762 |
|
| 1763 |
ir::Statement::Switch { selector, cases } |
| 1764 |
} |
| 1765 |
ast::StatementKind::Loop { |
| 1766 |
ref body, |
| 1767 |
ref continuing, |
| 1768 |
break_if, |
| 1769 |
} => { |
| 1770 |
let body = self.block(body, true, ctx)?; |
| 1771 |
let mut continuing = self.block(continuing, true, ctx)?; |
| 1772 |
|
| 1773 |
let mut emitter = proc::Emitter::default(); |
| 1774 |
emitter.start(&ctx.function.expressions); |
| 1775 |
let break_if = break_if |
| 1776 |
.map(|expr| { |
| 1777 |
self.expression(expr, &mut ctx.as_expression(&mut continuing, &mut emitter)) |
| 1778 |
}) |
| 1779 |
.transpose()?; |
| 1780 |
continuing.extend(emitter.finish(&ctx.function.expressions)); |
| 1781 |
|
| 1782 |
ir::Statement::Loop { |
| 1783 |
body, |
| 1784 |
continuing, |
| 1785 |
break_if, |
| 1786 |
} |
| 1787 |
} |
| 1788 |
ast::StatementKind::Break => ir::Statement::Break, |
| 1789 |
ast::StatementKind::Continue => ir::Statement::Continue, |
| 1790 |
ast::StatementKind::Return { value: ast_value } => { |
| 1791 |
let mut emitter = proc::Emitter::default(); |
| 1792 |
emitter.start(&ctx.function.expressions); |
| 1793 |
|
| 1794 |
let value; |
| 1795 |
if let Some(ast_expr) = ast_value { |
| 1796 |
let result_ty = ctx.function.result.as_ref().map(|r| r.ty); |
| 1797 |
let mut ectx = ctx.as_expression(block, &mut emitter); |
| 1798 |
let expr = self.expression_for_abstract(ast_expr, &mut ectx)?; |
| 1799 |
|
| 1800 |
if let Some(result_ty) = result_ty { |
| 1801 |
let mut ectx = ctx.as_expression(block, &mut emitter); |
| 1802 |
let resolution = proc::TypeResolution::Handle(result_ty); |
| 1803 |
let converted = |
| 1804 |
ectx.try_automatic_conversions(expr, &resolution, Span::default())?; |
| 1805 |
value = Some(converted); |
| 1806 |
} else { |
| 1807 |
value = Some(expr); |
| 1808 |
} |
| 1809 |
} else { |
| 1810 |
value = None; |
| 1811 |
} |
| 1812 |
block.extend(emitter.finish(&ctx.function.expressions)); |
| 1813 |
|
| 1814 |
ir::Statement::Return { value } |
| 1815 |
} |
| 1816 |
ast::StatementKind::Kill => ir::Statement::Kill, |
| 1817 |
ast::StatementKind::Call { |
| 1818 |
ref function, |
| 1819 |
ref arguments, |
| 1820 |
} => { |
| 1821 |
let mut emitter = proc::Emitter::default(); |
| 1822 |
emitter.start(&ctx.function.expressions); |
| 1823 |
|
| 1824 |
let _ = self.call( |
| 1825 |
stmt.span, |
| 1826 |
function, |
| 1827 |
arguments, |
| 1828 |
&mut ctx.as_expression(block, &mut emitter), |
| 1829 |
true, |
| 1830 |
)?; |
| 1831 |
block.extend(emitter.finish(&ctx.function.expressions)); |
| 1832 |
return Ok(()); |
| 1833 |
} |
| 1834 |
ast::StatementKind::Assign { |
| 1835 |
target: ast_target, |
| 1836 |
op, |
| 1837 |
value, |
| 1838 |
} => { |
| 1839 |
let mut emitter = proc::Emitter::default(); |
| 1840 |
emitter.start(&ctx.function.expressions); |
| 1841 |
let target_span = ctx.ast_expressions.get_span(ast_target); |
| 1842 |
|
| 1843 |
let mut ectx = ctx.as_expression(block, &mut emitter); |
| 1844 |
let target = self.expression_for_reference(ast_target, &mut ectx)?; |
| 1845 |
let target_handle = match target { |
| 1846 |
Typed::Reference(handle) => handle, |
| 1847 |
Typed::Plain(handle) => { |
| 1848 |
let ty = ctx.invalid_assignment_type(handle); |
| 1849 |
return Err(Box::new(Error::InvalidAssignment { |
| 1850 |
span: target_span, |
| 1851 |
ty, |
| 1852 |
})); |
| 1853 |
} |
| 1854 |
}; |
| 1855 |
|
| 1856 |
// Usually the value needs to be converted to match the type of |
| 1857 |
// the memory view you're assigning it to. The bit shift |
| 1858 |
// operators are exceptions, in that the right operand is always |
| 1859 |
// a `u32` or `vecN<u32>`. |
| 1860 |
let target_scalar = match op { |
| 1861 |
Some(ir::BinaryOperator::ShiftLeft | ir::BinaryOperator::ShiftRight) => { |
| 1862 |
Some(ir::Scalar::U32) |
| 1863 |
} |
| 1864 |
_ => resolve_inner!(ectx, target_handle) |
| 1865 |
.pointer_automatically_convertible_scalar(&ectx.module.types), |
| 1866 |
}; |
| 1867 |
|
| 1868 |
let value = self.expression_for_abstract(value, &mut ectx)?; |
| 1869 |
let mut value = match target_scalar { |
| 1870 |
Some(target_scalar) => ectx.try_automatic_conversion_for_leaf_scalar( |
| 1871 |
value, |
| 1872 |
target_scalar, |
| 1873 |
target_span, |
| 1874 |
)?, |
| 1875 |
None => value, |
| 1876 |
}; |
| 1877 |
|
| 1878 |
let value = match op { |
| 1879 |
Some(op) => { |
| 1880 |
let mut left = ectx.apply_load_rule(target)?; |
| 1881 |
ectx.binary_op_splat(op, &mut left, &mut value)?; |
| 1882 |
ectx.append_expression( |
| 1883 |
ir::Expression::Binary { |
| 1884 |
op, |
| 1885 |
left, |
| 1886 |
right: value, |
| 1887 |
}, |
| 1888 |
stmt.span, |
| 1889 |
)? |
| 1890 |
} |
| 1891 |
None => value, |
| 1892 |
}; |
| 1893 |
block.extend(emitter.finish(&ctx.function.expressions)); |
| 1894 |
|
| 1895 |
ir::Statement::Store { |
| 1896 |
pointer: target_handle, |
| 1897 |
value, |
| 1898 |
} |
| 1899 |
} |
| 1900 |
ast::StatementKind::Increment(value) | ast::StatementKind::Decrement(value) => { |
| 1901 |
let mut emitter = proc::Emitter::default(); |
| 1902 |
emitter.start(&ctx.function.expressions); |
| 1903 |
|
| 1904 |
let op = match stmt.kind { |
| 1905 |
ast::StatementKind::Increment(_) => ir::BinaryOperator::Add, |
| 1906 |
ast::StatementKind::Decrement(_) => ir::BinaryOperator::Subtract, |
| 1907 |
_ => unreachable!(), |
| 1908 |
}; |
| 1909 |
|
| 1910 |
let value_span = ctx.ast_expressions.get_span(value); |
| 1911 |
let target = self |
| 1912 |
.expression_for_reference(value, &mut ctx.as_expression(block, &mut emitter))?; |
| 1913 |
let target_handle = match target { |
| 1914 |
Typed::Reference(handle) => handle, |
| 1915 |
Typed::Plain(_) => { |
| 1916 |
return Err(Box::new(Error::BadIncrDecrReferenceType(value_span))) |
| 1917 |
} |
| 1918 |
}; |
| 1919 |
|
| 1920 |
let mut ectx = ctx.as_expression(block, &mut emitter); |
| 1921 |
let scalar = match *resolve_inner!(ectx, target_handle) { |
| 1922 |
ir::TypeInner::ValuePointer { |
| 1923 |
size: None, scalar, .. |
| 1924 |
} => scalar, |
| 1925 |
ir::TypeInner::Pointer { base, .. } => match ectx.module.types[base].inner { |
| 1926 |
ir::TypeInner::Scalar(scalar) => scalar, |
| 1927 |
_ => return Err(Box::new(Error::BadIncrDecrReferenceType(value_span))), |
| 1928 |
}, |
| 1929 |
_ => return Err(Box::new(Error::BadIncrDecrReferenceType(value_span))), |
| 1930 |
}; |
| 1931 |
let literal = match scalar.kind { |
| 1932 |
ir::ScalarKind::Sint | ir::ScalarKind::Uint => ir::Literal::one(scalar) |
| 1933 |
.ok_or(Error::BadIncrDecrReferenceType(value_span))?, |
| 1934 |
_ => return Err(Box::new(Error::BadIncrDecrReferenceType(value_span))), |
| 1935 |
}; |
| 1936 |
|
| 1937 |
let right = |
| 1938 |
ectx.interrupt_emitter(ir::Expression::Literal(literal), Span::UNDEFINED)?; |
| 1939 |
let rctx = ectx.runtime_expression_ctx(stmt.span)?; |
| 1940 |
let left = rctx.function.expressions.append( |
| 1941 |
ir::Expression::Load { |
| 1942 |
pointer: target_handle, |
| 1943 |
}, |
| 1944 |
value_span, |
| 1945 |
); |
| 1946 |
let value = rctx |
| 1947 |
.function |
| 1948 |
.expressions |
| 1949 |
.append(ir::Expression::Binary { op, left, right }, stmt.span); |
| 1950 |
rctx.local_expression_kind_tracker |
| 1951 |
.insert(left, proc::ExpressionKind::Runtime); |
| 1952 |
rctx.local_expression_kind_tracker |
| 1953 |
.insert(value, proc::ExpressionKind::Runtime); |
| 1954 |
|
| 1955 |
block.extend(emitter.finish(&ctx.function.expressions)); |
| 1956 |
ir::Statement::Store { |
| 1957 |
pointer: target_handle, |
| 1958 |
value, |
| 1959 |
} |
| 1960 |
} |
| 1961 |
ast::StatementKind::ConstAssert(condition) => { |
| 1962 |
let mut emitter = proc::Emitter::default(); |
| 1963 |
emitter.start(&ctx.function.expressions); |
| 1964 |
|
| 1965 |
let condition = |
| 1966 |
self.expression(condition, &mut ctx.as_const(block, &mut emitter))?; |
| 1967 |
|
| 1968 |
let span = ctx.function.expressions.get_span(condition); |
| 1969 |
match ctx |
| 1970 |
.module |
| 1971 |
.to_ctx() |
| 1972 |
.eval_expr_to_bool_from(condition, &ctx.function.expressions) |
| 1973 |
{ |
| 1974 |
Some(true) => Ok(()), |
| 1975 |
Some(false) => Err(Error::ConstAssertFailed(span)), |
| 1976 |
_ => Err(Error::NotBool(span)), |
| 1977 |
}?; |
| 1978 |
|
| 1979 |
block.extend(emitter.finish(&ctx.function.expressions)); |
| 1980 |
|
| 1981 |
return Ok(()); |
| 1982 |
} |
| 1983 |
ast::StatementKind::Phony(expr) => { |
| 1984 |
// Remembered the RHS of the phony assignment as a named expression. This |
| 1985 |
// is important (1) to preserve the RHS for validation, (2) to track any |
| 1986 |
// referenced globals. |
| 1987 |
let mut emitter = proc::Emitter::default(); |
| 1988 |
emitter.start(&ctx.function.expressions); |
| 1989 |
|
| 1990 |
let value = self.expression(expr, &mut ctx.as_expression(block, &mut emitter))?; |
| 1991 |
block.extend(emitter.finish(&ctx.function.expressions)); |
| 1992 |
ctx.named_expressions |
| 1993 |
.insert(value, ("phony".to_string(), stmt.span)); |
| 1994 |
return Ok(()); |
| 1995 |
} |
| 1996 |
}; |
| 1997 |
|
| 1998 |
block.push(out, stmt.span); |
| 1999 |
|
| 2000 |
Ok(()) |
| 2001 |
} |
| 2002 |
|
| 2003 |
/// Lower `expr` and apply the Load Rule if possible. |
| 2004 |
/// |
| 2005 |
/// For the time being, this concretizes abstract values, to support |
| 2006 |
/// consumers that haven't been adapted to consume them yet. Consumers |
| 2007 |
/// prepared for abstract values can call [`expression_for_abstract`]. |
| 2008 |
/// |
| 2009 |
/// [`expression_for_abstract`]: Lowerer::expression_for_abstract |
| 2010 |
fn expression( |
| 2011 |
&mut self, |
| 2012 |
expr: Handle<ast::Expression<'source>>, |
| 2013 |
ctx: &mut ExpressionContext<'source, '_, '_>, |
| 2014 |
) -> Result<'source, Handle<ir::Expression>> { |
| 2015 |
let expr = self.expression_for_abstract(expr, ctx)?; |
| 2016 |
ctx.concretize(expr) |
| 2017 |
} |
| 2018 |
|
| 2019 |
fn expression_for_abstract( |
| 2020 |
&mut self, |
| 2021 |
expr: Handle<ast::Expression<'source>>, |
| 2022 |
ctx: &mut ExpressionContext<'source, '_, '_>, |
| 2023 |
) -> Result<'source, Handle<ir::Expression>> { |
| 2024 |
let expr = self.expression_for_reference(expr, ctx)?; |
| 2025 |
ctx.apply_load_rule(expr) |
| 2026 |
} |
| 2027 |
|
| 2028 |
fn expression_with_leaf_scalar( |
| 2029 |
&mut self, |
| 2030 |
expr: Handle<ast::Expression<'source>>, |
| 2031 |
scalar: ir::Scalar, |
| 2032 |
ctx: &mut ExpressionContext<'source, '_, '_>, |
| 2033 |
) -> Result<'source, Handle<ir::Expression>> { |
| 2034 |
let unconverted = self.expression_for_abstract(expr, ctx)?; |
| 2035 |
ctx.try_automatic_conversion_for_leaf_scalar(unconverted, scalar, Span::default()) |
| 2036 |
} |
| 2037 |
|
| 2038 |
fn expression_for_reference( |
| 2039 |
&mut self, |
| 2040 |
expr: Handle<ast::Expression<'source>>, |
| 2041 |
ctx: &mut ExpressionContext<'source, '_, '_>, |
| 2042 |
) -> Result<'source, Typed<Handle<ir::Expression>>> { |
| 2043 |
let span = ctx.ast_expressions.get_span(expr); |
| 2044 |
let expr = &ctx.ast_expressions[expr]; |
| 2045 |
|
| 2046 |
let expr: Typed<ir::Expression> = match *expr { |
| 2047 |
ast::Expression::Literal(literal) => { |
| 2048 |
let literal = match literal { |
| 2049 |
ast::Literal::Number(Number::F16(f)) => ir::Literal::F16(f), |
| 2050 |
ast::Literal::Number(Number::F32(f)) => ir::Literal::F32(f), |
| 2051 |
ast::Literal::Number(Number::I32(i)) => ir::Literal::I32(i), |
| 2052 |
ast::Literal::Number(Number::U32(u)) => ir::Literal::U32(u), |
| 2053 |
ast::Literal::Number(Number::I64(i)) => ir::Literal::I64(i), |
| 2054 |
ast::Literal::Number(Number::U64(u)) => ir::Literal::U64(u), |
| 2055 |
ast::Literal::Number(Number::F64(f)) => ir::Literal::F64(f), |
| 2056 |
ast::Literal::Number(Number::AbstractInt(i)) => ir::Literal::AbstractInt(i), |
| 2057 |
ast::Literal::Number(Number::AbstractFloat(f)) => ir::Literal::AbstractFloat(f), |
| 2058 |
ast::Literal::Bool(b) => ir::Literal::Bool(b), |
| 2059 |
}; |
| 2060 |
let handle = ctx.interrupt_emitter(ir::Expression::Literal(literal), span)?; |
| 2061 |
return Ok(Typed::Plain(handle)); |
| 2062 |
} |
| 2063 |
ast::Expression::Ident(ast::IdentExpr::Local(local)) => { |
| 2064 |
return ctx.local(&local, span); |
| 2065 |
} |
| 2066 |
ast::Expression::Ident(ast::IdentExpr::Unresolved(name)) => { |
| 2067 |
let global = ctx |
| 2068 |
.globals |
| 2069 |
.get(name) |
| 2070 |
.ok_or(Error::UnknownIdent(span, name))?; |
| 2071 |
let expr = match *global { |
| 2072 |
LoweredGlobalDecl::Var(handle) => { |
| 2073 |
let expr = ir::Expression::GlobalVariable(handle); |
| 2074 |
match ctx.module.global_variables[handle].space { |
| 2075 |
ir::AddressSpace::Handle => Typed::Plain(expr), |
| 2076 |
_ => Typed::Reference(expr), |
| 2077 |
} |
| 2078 |
} |
| 2079 |
LoweredGlobalDecl::Const(handle) => { |
| 2080 |
Typed::Plain(ir::Expression::Constant(handle)) |
| 2081 |
} |
| 2082 |
LoweredGlobalDecl::Override(handle) => { |
| 2083 |
Typed::Plain(ir::Expression::Override(handle)) |
| 2084 |
} |
| 2085 |
LoweredGlobalDecl::Function { .. } |
| 2086 |
| LoweredGlobalDecl::Type(_) |
| 2087 |
| LoweredGlobalDecl::EntryPoint => { |
| 2088 |
return Err(Box::new(Error::Unexpected(span, ExpectedToken::Variable))); |
| 2089 |
} |
| 2090 |
}; |
| 2091 |
|
| 2092 |
return expr.try_map(|handle| ctx.interrupt_emitter(handle, span)); |
| 2093 |
} |
| 2094 |
ast::Expression::Construct { |
| 2095 |
ref ty, |
| 2096 |
ty_span, |
| 2097 |
ref components, |
| 2098 |
} => { |
| 2099 |
let handle = self.construct(span, ty, ty_span, components, ctx)?; |
| 2100 |
return Ok(Typed::Plain(handle)); |
| 2101 |
} |
| 2102 |
ast::Expression::Unary { op, expr } => { |
| 2103 |
let expr = self.expression_for_abstract(expr, ctx)?; |
| 2104 |
Typed::Plain(ir::Expression::Unary { op, expr }) |
| 2105 |
} |
| 2106 |
ast::Expression::AddrOf(expr) => { |
| 2107 |
// The `&` operator simply converts a reference to a pointer. And since a |
| 2108 |
// reference is required, the Load Rule is not applied. |
| 2109 |
match self.expression_for_reference(expr, ctx)? { |
| 2110 |
Typed::Reference(handle) => { |
| 2111 |
let expr = &ctx.runtime_expression_ctx(span)?.function.expressions[handle]; |
| 2112 |
if let &ir::Expression::Access { base, .. } |
| 2113 |
| &ir::Expression::AccessIndex { base, .. } = expr |
| 2114 |
{ |
| 2115 |
if let Some(ty) = resolve_inner!(ctx, base).pointer_base_type() { |
| 2116 |
if matches!( |
| 2117 |
*ty.inner_with(&ctx.module.types), |
| 2118 |
ir::TypeInner::Vector { .. }, |
| 2119 |
) { |
| 2120 |
return Err(Box::new(Error::InvalidAddrOfOperand( |
| 2121 |
ctx.get_expression_span(handle), |
| 2122 |
))); |
| 2123 |
} |
| 2124 |
} |
| 2125 |
} |
| 2126 |
// No code is generated. We just declare the reference a pointer now. |
| 2127 |
return Ok(Typed::Plain(handle)); |
| 2128 |
} |
| 2129 |
Typed::Plain(_) => { |
| 2130 |
return Err(Box::new(Error::NotReference( |
| 2131 |
"the operand of the `&` operator", |
| 2132 |
span, |
| 2133 |
))); |
| 2134 |
} |
| 2135 |
} |
| 2136 |
} |
| 2137 |
ast::Expression::Deref(expr) => { |
| 2138 |
// The pointer we dereference must be loaded. |
| 2139 |
let pointer = self.expression(expr, ctx)?; |
| 2140 |
|
| 2141 |
if resolve_inner!(ctx, pointer).pointer_space().is_none() { |
| 2142 |
return Err(Box::new(Error::NotPointer(span))); |
| 2143 |
} |
| 2144 |
|
| 2145 |
// No code is generated. We just declare the pointer a reference now. |
| 2146 |
return Ok(Typed::Reference(pointer)); |
| 2147 |
} |
| 2148 |
ast::Expression::Binary { op, left, right } => { |
| 2149 |
self.binary(op, left, right, span, ctx)? |
| 2150 |
} |
| 2151 |
ast::Expression::Call { |
| 2152 |
ref function, |
| 2153 |
ref arguments, |
| 2154 |
} => { |
| 2155 |
let handle = self |
| 2156 |
.call(span, function, arguments, ctx, false)? |
| 2157 |
.ok_or(Error::FunctionReturnsVoid(function.span))?; |
| 2158 |
return Ok(Typed::Plain(handle)); |
| 2159 |
} |
| 2160 |
ast::Expression::Index { base, index } => { |
| 2161 |
let mut lowered_base = self.expression_for_reference(base, ctx)?; |
| 2162 |
let index = self.expression(index, ctx)?; |
| 2163 |
|
| 2164 |
// <https://www.w3.org/TR/WGSL/#language_extension-pointer_composite_access> |
| 2165 |
// Declare pointer as reference |
| 2166 |
if let Typed::Plain(handle) = lowered_base { |
| 2167 |
if resolve_inner!(ctx, handle).pointer_space().is_some() { |
| 2168 |
lowered_base = Typed::Reference(handle); |
| 2169 |
} |
| 2170 |
} |
| 2171 |
|
| 2172 |
lowered_base.try_map(|base| match ctx.const_eval_expr_to_u32(index).ok() { |
| 2173 |
Some(index) => Ok::<_, Box<Error>>(ir::Expression::AccessIndex { base, index }), |
| 2174 |
None => { |
| 2175 |
// When an abstract array value e is indexed by an expression |
| 2176 |
// that is not a const-expression, then the array is concretized |
| 2177 |
// before the index is applied. |
| 2178 |
// https://www.w3.org/TR/WGSL/#array-access-expr |
| 2179 |
// Also applies to vectors and matrices. |
| 2180 |
let base = ctx.concretize(base)?; |
| 2181 |
Ok(ir::Expression::Access { base, index }) |
| 2182 |
} |
| 2183 |
})? |
| 2184 |
} |
| 2185 |
ast::Expression::Member { base, ref field } => { |
| 2186 |
let mut lowered_base = self.expression_for_reference(base, ctx)?; |
| 2187 |
|
| 2188 |
// <https://www.w3.org/TR/WGSL/#language_extension-pointer_composite_access> |
| 2189 |
// Declare pointer as reference |
| 2190 |
if let Typed::Plain(handle) = lowered_base { |
| 2191 |
if resolve_inner!(ctx, handle).pointer_space().is_some() { |
| 2192 |
lowered_base = Typed::Reference(handle); |
| 2193 |
} |
| 2194 |
} |
| 2195 |
|
| 2196 |
let temp_ty; |
| 2197 |
let composite_type: &ir::TypeInner = match lowered_base { |
| 2198 |
Typed::Reference(handle) => { |
| 2199 |
temp_ty = resolve_inner!(ctx, handle) |
| 2200 |
.pointer_base_type() |
| 2201 |
.expect("In Typed::Reference(handle), handle must be a Naga pointer"); |
| 2202 |
temp_ty.inner_with(&ctx.module.types) |
| 2203 |
} |
| 2204 |
|
| 2205 |
Typed::Plain(handle) => { |
| 2206 |
resolve_inner!(ctx, handle) |
| 2207 |
} |
| 2208 |
}; |
| 2209 |
|
| 2210 |
let access = match *composite_type { |
| 2211 |
ir::TypeInner::Struct { ref members, .. } => { |
| 2212 |
let index = members |
| 2213 |
.iter() |
| 2214 |
.position(|m| m.name.as_deref() == Some(field.name)) |
| 2215 |
.ok_or(Error::BadAccessor(field.span))? |
| 2216 |
as u32; |
| 2217 |
|
| 2218 |
lowered_base.map(|base| ir::Expression::AccessIndex { base, index }) |
| 2219 |
} |
| 2220 |
ir::TypeInner::Vector { .. } => { |
| 2221 |
match Components::new(field.name, field.span)? { |
| 2222 |
Components::Swizzle { size, pattern } => { |
| 2223 |
Typed::Plain(ir::Expression::Swizzle { |
| 2224 |
size, |
| 2225 |
vector: ctx.apply_load_rule(lowered_base)?, |
| 2226 |
pattern, |
| 2227 |
}) |
| 2228 |
} |
| 2229 |
Components::Single(index) => { |
| 2230 |
lowered_base.map(|base| ir::Expression::AccessIndex { base, index }) |
| 2231 |
} |
| 2232 |
} |
| 2233 |
} |
| 2234 |
_ => return Err(Box::new(Error::BadAccessor(field.span))), |
| 2235 |
}; |
| 2236 |
|
| 2237 |
access |
| 2238 |
} |
| 2239 |
ast::Expression::Bitcast { expr, to, ty_span } => { |
| 2240 |
let expr = self.expression(expr, ctx)?; |
| 2241 |
let to_resolved = self.resolve_ast_type(to, &mut ctx.as_const())?; |
| 2242 |
|
| 2243 |
let element_scalar = match ctx.module.types[to_resolved].inner { |
| 2244 |
ir::TypeInner::Scalar(scalar) => scalar, |
| 2245 |
ir::TypeInner::Vector { scalar, .. } => scalar, |
| 2246 |
_ => { |
| 2247 |
let ty = resolve!(ctx, expr); |
| 2248 |
return Err(Box::new(Error::BadTypeCast { |
| 2249 |
from_type: ctx.type_resolution_to_string(ty), |
| 2250 |
span: ty_span, |
| 2251 |
to_type: ctx.type_to_string(to_resolved), |
| 2252 |
})); |
| 2253 |
} |
| 2254 |
}; |
| 2255 |
|
| 2256 |
Typed::Plain(ir::Expression::As { |
| 2257 |
expr, |
| 2258 |
kind: element_scalar.kind, |
| 2259 |
convert: None, |
| 2260 |
}) |
| 2261 |
} |
| 2262 |
}; |
| 2263 |
|
| 2264 |
expr.try_map(|handle| ctx.append_expression(handle, span)) |
| 2265 |
} |
| 2266 |
|
| 2267 |
fn binary( |
| 2268 |
&mut self, |
| 2269 |
op: ir::BinaryOperator, |
| 2270 |
left: Handle<ast::Expression<'source>>, |
| 2271 |
right: Handle<ast::Expression<'source>>, |
| 2272 |
span: Span, |
| 2273 |
ctx: &mut ExpressionContext<'source, '_, '_>, |
| 2274 |
) -> Result<'source, Typed<ir::Expression>> { |
| 2275 |
// Load both operands. |
| 2276 |
let mut left = self.expression_for_abstract(left, ctx)?; |
| 2277 |
let mut right = self.expression_for_abstract(right, ctx)?; |
| 2278 |
|
| 2279 |
// Convert `scalar op vector` to `vector op vector` by introducing |
| 2280 |
// `Splat` expressions. |
| 2281 |
ctx.binary_op_splat(op, &mut left, &mut right)?; |
| 2282 |
|
| 2283 |
// Apply automatic conversions. |
| 2284 |
match op { |
| 2285 |
ir::BinaryOperator::ShiftLeft | ir::BinaryOperator::ShiftRight => { |
| 2286 |
// Shift operators require the right operand to be `u32` or |
| 2287 |
// `vecN<u32>`. We can let the validator sort out vector length |
| 2288 |
// issues, but the right operand must be, or convert to, a u32 leaf |
| 2289 |
// scalar. |
| 2290 |
right = |
| 2291 |
ctx.try_automatic_conversion_for_leaf_scalar(right, ir::Scalar::U32, span)?; |
| 2292 |
|
| 2293 |
// Additionally, we must concretize the left operand if the right operand |
| 2294 |
// is not a const-expression. |
| 2295 |
// See https://www.w3.org/TR/WGSL/#overload-resolution-section. |
| 2296 |
// |
| 2297 |
// 2. Eliminate any candidate where one of its subexpressions resolves to |
| 2298 |
// an abstract type after feasible automatic conversions, but another of |
| 2299 |
// the candidate’s subexpressions is not a const-expression. |
| 2300 |
// |
| 2301 |
// We only have to explicitly do so for shifts as their operands may be |
| 2302 |
// of different types - for other binary ops this is achieved by finding |
| 2303 |
// the conversion consensus for both operands. |
| 2304 |
if !ctx.is_const(right) { |
| 2305 |
left = ctx.concretize(left)?; |
| 2306 |
} |
| 2307 |
} |
| 2308 |
|
| 2309 |
// All other operators follow the same pattern: reconcile the |
| 2310 |
// scalar leaf types. If there's no reconciliation possible, |
| 2311 |
// leave the expressions as they are: validation will report the |
| 2312 |
// problem. |
| 2313 |
_ => { |
| 2314 |
ctx.grow_types(left)?; |
| 2315 |
ctx.grow_types(right)?; |
| 2316 |
if let Ok(consensus_scalar) = |
| 2317 |
ctx.automatic_conversion_consensus([left, right].iter()) |
| 2318 |
{ |
| 2319 |
ctx.convert_to_leaf_scalar(&mut left, consensus_scalar)?; |
| 2320 |
ctx.convert_to_leaf_scalar(&mut right, consensus_scalar)?; |
| 2321 |
} |
| 2322 |
} |
| 2323 |
} |
| 2324 |
|
| 2325 |
Ok(Typed::Plain(ir::Expression::Binary { op, left, right })) |
| 2326 |
} |
| 2327 |
|
| 2328 |
/// Generate Naga IR for call expressions and statements, and type |
| 2329 |
/// constructor expressions. |
| 2330 |
/// |
| 2331 |
/// The "function" being called is simply an `Ident` that we know refers to |
| 2332 |
/// some module-scope definition. |
| 2333 |
/// |
| 2334 |
/// - If it is the name of a type, then the expression is a type constructor |
| 2335 |
/// expression: either constructing a value from components, a conversion |
| 2336 |
/// expression, or a zero value expression. |
| 2337 |
/// |
| 2338 |
/// - If it is the name of a function, then we're generating a [`Call`] |
| 2339 |
/// statement. We may be in the midst of generating code for an |
| 2340 |
/// expression, in which case we must generate an `Emit` statement to |
| 2341 |
/// force evaluation of the IR expressions we've generated so far, add the |
| 2342 |
/// `Call` statement to the current block, and then resume generating |
| 2343 |
/// expressions. |
| 2344 |
/// |
| 2345 |
/// [`Call`]: ir::Statement::Call |
| 2346 |
fn call( |
| 2347 |
&mut self, |
| 2348 |
span: Span, |
| 2349 |
function: &ast::Ident<'source>, |
| 2350 |
arguments: &[Handle<ast::Expression<'source>>], |
| 2351 |
ctx: &mut ExpressionContext<'source, '_, '_>, |
| 2352 |
is_statement: bool, |
| 2353 |
) -> Result<'source, Option<Handle<ir::Expression>>> { |
| 2354 |
let function_span = function.span; |
| 2355 |
match ctx.globals.get(function.name) { |
| 2356 |
Some(&LoweredGlobalDecl::Type(ty)) => { |
| 2357 |
let handle = self.construct( |
| 2358 |
span, |
| 2359 |
&ast::ConstructorType::Type(ty), |
| 2360 |
function_span, |
| 2361 |
arguments, |
| 2362 |
ctx, |
| 2363 |
)?; |
| 2364 |
Ok(Some(handle)) |
| 2365 |
} |
| 2366 |
Some( |
| 2367 |
&LoweredGlobalDecl::Const(_) |
| 2368 |
| &LoweredGlobalDecl::Override(_) |
| 2369 |
| &LoweredGlobalDecl::Var(_), |
| 2370 |
) => Err(Box::new(Error::Unexpected( |
| 2371 |
function_span, |
| 2372 |
ExpectedToken::Function, |
| 2373 |
))), |
| 2374 |
Some(&LoweredGlobalDecl::EntryPoint) => { |
| 2375 |
Err(Box::new(Error::CalledEntryPoint(function_span))) |
| 2376 |
} |
| 2377 |
Some(&LoweredGlobalDecl::Function { |
| 2378 |
handle: function, |
| 2379 |
must_use, |
| 2380 |
}) => { |
| 2381 |
let arguments = arguments |
| 2382 |
.iter() |
| 2383 |
.enumerate() |
| 2384 |
.map(|(i, &arg)| { |
| 2385 |
// Try to convert abstract values to the known argument types |
| 2386 |
let Some(&ir::FunctionArgument { |
| 2387 |
ty: parameter_ty, .. |
| 2388 |
}) = ctx.module.functions[function].arguments.get(i) |
| 2389 |
else { |
| 2390 |
// Wrong number of arguments... just concretize the type here |
| 2391 |
// and let the validator report the error. |
| 2392 |
return self.expression(arg, ctx); |
| 2393 |
}; |
| 2394 |
|
| 2395 |
let expr = self.expression_for_abstract(arg, ctx)?; |
| 2396 |
ctx.try_automatic_conversions( |
| 2397 |
expr, |
| 2398 |
&proc::TypeResolution::Handle(parameter_ty), |
| 2399 |
ctx.ast_expressions.get_span(arg), |
| 2400 |
) |
| 2401 |
}) |
| 2402 |
.collect::<Result<Vec<_>>>()?; |
| 2403 |
|
| 2404 |
let has_result = ctx.module.functions[function].result.is_some(); |
| 2405 |
|
| 2406 |
if must_use && is_statement { |
| 2407 |
return Err(Box::new(Error::FunctionMustUseUnused(function_span))); |
| 2408 |
} |
| 2409 |
|
| 2410 |
let rctx = ctx.runtime_expression_ctx(span)?; |
| 2411 |
// we need to always do this before a fn call since all arguments need to be emitted before the fn call |
| 2412 |
rctx.block |
| 2413 |
.extend(rctx.emitter.finish(&rctx.function.expressions)); |
| 2414 |
let result = has_result.then(|| { |
| 2415 |
let result = rctx |
| 2416 |
.function |
| 2417 |
.expressions |
| 2418 |
.append(ir::Expression::CallResult(function), span); |
| 2419 |
rctx.local_expression_kind_tracker |
| 2420 |
.insert(result, proc::ExpressionKind::Runtime); |
| 2421 |
result |
| 2422 |
}); |
| 2423 |
rctx.emitter.start(&rctx.function.expressions); |
| 2424 |
rctx.block.push( |
| 2425 |
ir::Statement::Call { |
| 2426 |
function, |
| 2427 |
arguments, |
| 2428 |
result, |
| 2429 |
}, |
| 2430 |
span, |
| 2431 |
); |
| 2432 |
|
| 2433 |
Ok(result) |
| 2434 |
} |
| 2435 |
None => { |
| 2436 |
let span = function_span; |
| 2437 |
let expr = if let Some(fun) = conv::map_relational_fun(function.name) { |
| 2438 |
let mut args = ctx.prepare_args(arguments, 1, span); |
| 2439 |
let argument = self.expression(args.next()?, ctx)?; |
| 2440 |
args.finish()?; |
| 2441 |
|
| 2442 |
// Check for no-op all(bool) and any(bool): |
| 2443 |
let argument_unmodified = matches!( |
| 2444 |
fun, |
| 2445 |
ir::RelationalFunction::All | ir::RelationalFunction::Any |
| 2446 |
) && { |
| 2447 |
matches!( |
| 2448 |
resolve_inner!(ctx, argument), |
| 2449 |
&ir::TypeInner::Scalar(ir::Scalar { |
| 2450 |
kind: ir::ScalarKind::Bool, |
| 2451 |
.. |
| 2452 |
}) |
| 2453 |
) |
| 2454 |
}; |
| 2455 |
|
| 2456 |
if argument_unmodified { |
| 2457 |
return Ok(Some(argument)); |
| 2458 |
} else { |
| 2459 |
ir::Expression::Relational { fun, argument } |
| 2460 |
} |
| 2461 |
} else if let Some((axis, ctrl)) = conv::map_derivative(function.name) { |
| 2462 |
let mut args = ctx.prepare_args(arguments, 1, span); |
| 2463 |
let expr = self.expression(args.next()?, ctx)?; |
| 2464 |
args.finish()?; |
| 2465 |
|
| 2466 |
ir::Expression::Derivative { axis, ctrl, expr } |
| 2467 |
} else if let Some(fun) = conv::map_standard_fun(function.name) { |
| 2468 |
self.math_function_helper(span, fun, arguments, ctx)? |
| 2469 |
} else if let Some(fun) = Texture::map(function.name) { |
| 2470 |
self.texture_sample_helper(fun, arguments, span, ctx)? |
| 2471 |
} else if let Some((op, cop)) = conv::map_subgroup_operation(function.name) { |
| 2472 |
return Ok(Some( |
| 2473 |
self.subgroup_operation_helper(span, op, cop, arguments, ctx)?, |
| 2474 |
)); |
| 2475 |
} else if let Some(mode) = SubgroupGather::map(function.name) { |
| 2476 |
return Ok(Some( |
| 2477 |
self.subgroup_gather_helper(span, mode, arguments, ctx)?, |
| 2478 |
)); |
| 2479 |
} else if let Some(fun) = ir::AtomicFunction::map(function.name) { |
| 2480 |
return self.atomic_helper(span, fun, arguments, is_statement, ctx); |
| 2481 |
} else { |
| 2482 |
match function.name { |
| 2483 |
"select" => { |
| 2484 |
let mut args = ctx.prepare_args(arguments, 3, span); |
| 2485 |
|
| 2486 |
let reject = self.expression(args.next()?, ctx)?; |
| 2487 |
let accept = self.expression(args.next()?, ctx)?; |
| 2488 |
let condition = self.expression(args.next()?, ctx)?; |
| 2489 |
|
| 2490 |
args.finish()?; |
| 2491 |
|
| 2492 |
ir::Expression::Select { |
| 2493 |
reject, |
| 2494 |
accept, |
| 2495 |
condition, |
| 2496 |
} |
| 2497 |
} |
| 2498 |
"arrayLength" => { |
| 2499 |
let mut args = ctx.prepare_args(arguments, 1, span); |
| 2500 |
let expr = self.expression(args.next()?, ctx)?; |
| 2501 |
args.finish()?; |
| 2502 |
|
| 2503 |
ir::Expression::ArrayLength(expr) |
| 2504 |
} |
| 2505 |
"atomicLoad" => { |
| 2506 |
let mut args = ctx.prepare_args(arguments, 1, span); |
| 2507 |
let (pointer, _scalar) = self.atomic_pointer(args.next()?, ctx)?; |
| 2508 |
args.finish()?; |
| 2509 |
|
| 2510 |
ir::Expression::Load { pointer } |
| 2511 |
} |
| 2512 |
"atomicStore" => { |
| 2513 |
let mut args = ctx.prepare_args(arguments, 2, span); |
| 2514 |
let (pointer, scalar) = self.atomic_pointer(args.next()?, ctx)?; |
| 2515 |
let value = |
| 2516 |
self.expression_with_leaf_scalar(args.next()?, scalar, ctx)?; |
| 2517 |
args.finish()?; |
| 2518 |
|
| 2519 |
let rctx = ctx.runtime_expression_ctx(span)?; |
| 2520 |
rctx.block |
| 2521 |
.extend(rctx.emitter.finish(&rctx.function.expressions)); |
| 2522 |
rctx.emitter.start(&rctx.function.expressions); |
| 2523 |
rctx.block |
| 2524 |
.push(ir::Statement::Store { pointer, value }, span); |
| 2525 |
return Ok(None); |
| 2526 |
} |
| 2527 |
"atomicCompareExchangeWeak" => { |
| 2528 |
let mut args = ctx.prepare_args(arguments, 3, span); |
| 2529 |
|
| 2530 |
let (pointer, scalar) = self.atomic_pointer(args.next()?, ctx)?; |
| 2531 |
|
| 2532 |
let compare = |
| 2533 |
self.expression_with_leaf_scalar(args.next()?, scalar, ctx)?; |
| 2534 |
|
| 2535 |
let value = args.next()?; |
| 2536 |
let value_span = ctx.ast_expressions.get_span(value); |
| 2537 |
let value = self.expression_with_leaf_scalar(value, scalar, ctx)?; |
| 2538 |
|
| 2539 |
args.finish()?; |
| 2540 |
|
| 2541 |
let expression = match *resolve_inner!(ctx, value) { |
| 2542 |
ir::TypeInner::Scalar(scalar) => ir::Expression::AtomicResult { |
| 2543 |
ty: ctx.module.generate_predeclared_type( |
| 2544 |
ir::PredeclaredType::AtomicCompareExchangeWeakResult( |
| 2545 |
scalar, |
| 2546 |
), |
| 2547 |
), |
| 2548 |
comparison: true, |
| 2549 |
}, |
| 2550 |
_ => { |
| 2551 |
return Err(Box::new(Error::InvalidAtomicOperandType( |
| 2552 |
value_span, |
| 2553 |
))) |
| 2554 |
} |
| 2555 |
}; |
| 2556 |
|
| 2557 |
let result = ctx.interrupt_emitter(expression, span)?; |
| 2558 |
let rctx = ctx.runtime_expression_ctx(span)?; |
| 2559 |
rctx.block.push( |
| 2560 |
ir::Statement::Atomic { |
| 2561 |
pointer, |
| 2562 |
fun: ir::AtomicFunction::Exchange { |
| 2563 |
compare: Some(compare), |
| 2564 |
}, |
| 2565 |
value, |
| 2566 |
result: Some(result), |
| 2567 |
}, |
| 2568 |
span, |
| 2569 |
); |
| 2570 |
return Ok(Some(result)); |
| 2571 |
} |
| 2572 |
"textureAtomicMin" | "textureAtomicMax" | "textureAtomicAdd" |
| 2573 |
| "textureAtomicAnd" | "textureAtomicOr" | "textureAtomicXor" => { |
| 2574 |
let mut args = ctx.prepare_args(arguments, 3, span); |
| 2575 |
|
| 2576 |
let image = args.next()?; |
| 2577 |
let image_span = ctx.ast_expressions.get_span(image); |
| 2578 |
let image = self.expression(image, ctx)?; |
| 2579 |
|
| 2580 |
let coordinate = self.expression(args.next()?, ctx)?; |
| 2581 |
|
| 2582 |
let (_, arrayed) = ctx.image_data(image, image_span)?; |
| 2583 |
let array_index = arrayed |
| 2584 |
.then(|| { |
| 2585 |
args.min_args += 1; |
| 2586 |
self.expression(args.next()?, ctx) |
| 2587 |
}) |
| 2588 |
.transpose()?; |
| 2589 |
|
| 2590 |
let value = self.expression(args.next()?, ctx)?; |
| 2591 |
|
| 2592 |
args.finish()?; |
| 2593 |
|
| 2594 |
let rctx = ctx.runtime_expression_ctx(span)?; |
| 2595 |
rctx.block |
| 2596 |
.extend(rctx.emitter.finish(&rctx.function.expressions)); |
| 2597 |
rctx.emitter.start(&rctx.function.expressions); |
| 2598 |
let stmt = ir::Statement::ImageAtomic { |
| 2599 |
image, |
| 2600 |
coordinate, |
| 2601 |
array_index, |
| 2602 |
fun: match function.name { |
| 2603 |
"textureAtomicMin" => ir::AtomicFunction::Min, |
| 2604 |
"textureAtomicMax" => ir::AtomicFunction::Max, |
| 2605 |
"textureAtomicAdd" => ir::AtomicFunction::Add, |
| 2606 |
"textureAtomicAnd" => ir::AtomicFunction::And, |
| 2607 |
"textureAtomicOr" => ir::AtomicFunction::InclusiveOr, |
| 2608 |
"textureAtomicXor" => ir::AtomicFunction::ExclusiveOr, |
| 2609 |
_ => unreachable!(), |
| 2610 |
}, |
| 2611 |
value, |
| 2612 |
}; |
| 2613 |
rctx.block.push(stmt, span); |
| 2614 |
return Ok(None); |
| 2615 |
} |
| 2616 |
"storageBarrier" => { |
| 2617 |
ctx.prepare_args(arguments, 0, span).finish()?; |
| 2618 |
|
| 2619 |
let rctx = ctx.runtime_expression_ctx(span)?; |
| 2620 |
rctx.block |
| 2621 |
.push(ir::Statement::Barrier(ir::Barrier::STORAGE), span); |
| 2622 |
return Ok(None); |
| 2623 |
} |
| 2624 |
"workgroupBarrier" => { |
| 2625 |
ctx.prepare_args(arguments, 0, span).finish()?; |
| 2626 |
|
| 2627 |
let rctx = ctx.runtime_expression_ctx(span)?; |
| 2628 |
rctx.block |
| 2629 |
.push(ir::Statement::Barrier(ir::Barrier::WORK_GROUP), span); |
| 2630 |
return Ok(None); |
| 2631 |
} |
| 2632 |
"subgroupBarrier" => { |
| 2633 |
ctx.prepare_args(arguments, 0, span).finish()?; |
| 2634 |
|
| 2635 |
let rctx = ctx.runtime_expression_ctx(span)?; |
| 2636 |
rctx.block |
| 2637 |
.push(ir::Statement::Barrier(ir::Barrier::SUB_GROUP), span); |
| 2638 |
return Ok(None); |
| 2639 |
} |
| 2640 |
"textureBarrier" => { |
| 2641 |
ctx.prepare_args(arguments, 0, span).finish()?; |
| 2642 |
|
| 2643 |
let rctx = ctx.runtime_expression_ctx(span)?; |
| 2644 |
rctx.block |
| 2645 |
.push(ir::Statement::Barrier(ir::Barrier::TEXTURE), span); |
| 2646 |
return Ok(None); |
| 2647 |
} |
| 2648 |
"workgroupUniformLoad" => { |
| 2649 |
let mut args = ctx.prepare_args(arguments, 1, span); |
| 2650 |
let expr = args.next()?; |
| 2651 |
args.finish()?; |
| 2652 |
|
| 2653 |
let pointer = self.expression(expr, ctx)?; |
| 2654 |
let result_ty = match *resolve_inner!(ctx, pointer) { |
| 2655 |
ir::TypeInner::Pointer { |
| 2656 |
base, |
| 2657 |
space: ir::AddressSpace::WorkGroup, |
| 2658 |
} => base, |
| 2659 |
ref other => { |
| 2660 |
log::error!("Type {other:?} passed to workgroupUniformLoad"); |
| 2661 |
let span = ctx.ast_expressions.get_span(expr); |
| 2662 |
return Err(Box::new(Error::InvalidWorkGroupUniformLoad(span))); |
| 2663 |
} |
| 2664 |
}; |
| 2665 |
let result = ctx.interrupt_emitter( |
| 2666 |
ir::Expression::WorkGroupUniformLoadResult { ty: result_ty }, |
| 2667 |
span, |
| 2668 |
)?; |
| 2669 |
let rctx = ctx.runtime_expression_ctx(span)?; |
| 2670 |
rctx.block.push( |
| 2671 |
ir::Statement::WorkGroupUniformLoad { pointer, result }, |
| 2672 |
span, |
| 2673 |
); |
| 2674 |
|
| 2675 |
return Ok(Some(result)); |
| 2676 |
} |
| 2677 |
"textureStore" => { |
| 2678 |
let mut args = ctx.prepare_args(arguments, 3, span); |
| 2679 |
|
| 2680 |
let image = args.next()?; |
| 2681 |
let image_span = ctx.ast_expressions.get_span(image); |
| 2682 |
let image = self.expression(image, ctx)?; |
| 2683 |
|
| 2684 |
let coordinate = self.expression(args.next()?, ctx)?; |
| 2685 |
|
| 2686 |
let (class, arrayed) = ctx.image_data(image, image_span)?; |
| 2687 |
let array_index = arrayed |
| 2688 |
.then(|| { |
| 2689 |
args.min_args += 1; |
| 2690 |
self.expression(args.next()?, ctx) |
| 2691 |
}) |
| 2692 |
.transpose()?; |
| 2693 |
let scalar = if let ir::ImageClass::Storage { format, .. } = class { |
| 2694 |
format.into() |
| 2695 |
} else { |
| 2696 |
return Err(Box::new(Error::NotStorageTexture(image_span))); |
| 2697 |
}; |
| 2698 |
|
| 2699 |
let value = |
| 2700 |
self.expression_with_leaf_scalar(args.next()?, scalar, ctx)?; |
| 2701 |
|
| 2702 |
args.finish()?; |
| 2703 |
|
| 2704 |
let rctx = ctx.runtime_expression_ctx(span)?; |
| 2705 |
rctx.block |
| 2706 |
.extend(rctx.emitter.finish(&rctx.function.expressions)); |
| 2707 |
rctx.emitter.start(&rctx.function.expressions); |
| 2708 |
let stmt = ir::Statement::ImageStore { |
| 2709 |
image, |
| 2710 |
coordinate, |
| 2711 |
array_index, |
| 2712 |
value, |
| 2713 |
}; |
| 2714 |
rctx.block.push(stmt, span); |
| 2715 |
return Ok(None); |
| 2716 |
} |
| 2717 |
"textureLoad" => { |
| 2718 |
let mut args = ctx.prepare_args(arguments, 2, span); |
| 2719 |
|
| 2720 |
let image = args.next()?; |
| 2721 |
let image_span = ctx.ast_expressions.get_span(image); |
| 2722 |
let image = self.expression(image, ctx)?; |
| 2723 |
|
| 2724 |
let coordinate = self.expression(args.next()?, ctx)?; |
| 2725 |
|
| 2726 |
let (class, arrayed) = ctx.image_data(image, image_span)?; |
| 2727 |
let array_index = arrayed |
| 2728 |
.then(|| { |
| 2729 |
args.min_args += 1; |
| 2730 |
self.expression(args.next()?, ctx) |
| 2731 |
}) |
| 2732 |
.transpose()?; |
| 2733 |
|
| 2734 |
let level = class |
| 2735 |
.is_mipmapped() |
| 2736 |
.then(|| { |
| 2737 |
args.min_args += 1; |
| 2738 |
self.expression(args.next()?, ctx) |
| 2739 |
}) |
| 2740 |
.transpose()?; |
| 2741 |
|
| 2742 |
let sample = class |
| 2743 |
.is_multisampled() |
| 2744 |
.then(|| self.expression(args.next()?, ctx)) |
| 2745 |
.transpose()?; |
| 2746 |
|
| 2747 |
args.finish()?; |
| 2748 |
|
| 2749 |
ir::Expression::ImageLoad { |
| 2750 |
image, |
| 2751 |
coordinate, |
| 2752 |
array_index, |
| 2753 |
level, |
| 2754 |
sample, |
| 2755 |
} |
| 2756 |
} |
| 2757 |
"textureDimensions" => { |
| 2758 |
let mut args = ctx.prepare_args(arguments, 1, span); |
| 2759 |
let image = self.expression(args.next()?, ctx)?; |
| 2760 |
let level = args |
| 2761 |
.next() |
| 2762 |
.map(|arg| self.expression(arg, ctx)) |
| 2763 |
.ok() |
| 2764 |
.transpose()?; |
| 2765 |
args.finish()?; |
| 2766 |
|
| 2767 |
ir::Expression::ImageQuery { |
| 2768 |
image, |
| 2769 |
query: ir::ImageQuery::Size { level }, |
| 2770 |
} |
| 2771 |
} |
| 2772 |
"textureNumLevels" => { |
| 2773 |
let mut args = ctx.prepare_args(arguments, 1, span); |
| 2774 |
let image = self.expression(args.next()?, ctx)?; |
| 2775 |
args.finish()?; |
| 2776 |
|
| 2777 |
ir::Expression::ImageQuery { |
| 2778 |
image, |
| 2779 |
query: ir::ImageQuery::NumLevels, |
| 2780 |
} |
| 2781 |
} |
| 2782 |
"textureNumLayers" => { |
| 2783 |
let mut args = ctx.prepare_args(arguments, 1, span); |
| 2784 |
let image = self.expression(args.next()?, ctx)?; |
| 2785 |
args.finish()?; |
| 2786 |
|
| 2787 |
ir::Expression::ImageQuery { |
| 2788 |
image, |
| 2789 |
query: ir::ImageQuery::NumLayers, |
| 2790 |
} |
| 2791 |
} |
| 2792 |
"textureNumSamples" => { |
| 2793 |
let mut args = ctx.prepare_args(arguments, 1, span); |
| 2794 |
let image = self.expression(args.next()?, ctx)?; |
| 2795 |
args.finish()?; |
| 2796 |
|
| 2797 |
ir::Expression::ImageQuery { |
| 2798 |
image, |
| 2799 |
query: ir::ImageQuery::NumSamples, |
| 2800 |
} |
| 2801 |
} |
| 2802 |
"rayQueryInitialize" => { |
| 2803 |
let mut args = ctx.prepare_args(arguments, 3, span); |
| 2804 |
let query = self.ray_query_pointer(args.next()?, ctx)?; |
| 2805 |
let acceleration_structure = self.expression(args.next()?, ctx)?; |
| 2806 |
let descriptor = self.expression(args.next()?, ctx)?; |
| 2807 |
args.finish()?; |
| 2808 |
|
| 2809 |
let _ = ctx.module.generate_ray_desc_type(); |
| 2810 |
let fun = ir::RayQueryFunction::Initialize { |
| 2811 |
acceleration_structure, |
| 2812 |
descriptor, |
| 2813 |
}; |
| 2814 |
|
| 2815 |
let rctx = ctx.runtime_expression_ctx(span)?; |
| 2816 |
rctx.block |
| 2817 |
.extend(rctx.emitter.finish(&rctx.function.expressions)); |
| 2818 |
rctx.emitter.start(&rctx.function.expressions); |
| 2819 |
rctx.block |
| 2820 |
.push(ir::Statement::RayQuery { query, fun }, span); |
| 2821 |
return Ok(None); |
| 2822 |
} |
| 2823 |
"getCommittedHitVertexPositions" => { |
| 2824 |
let mut args = ctx.prepare_args(arguments, 1, span); |
| 2825 |
let query = self.ray_query_pointer(args.next()?, ctx)?; |
| 2826 |
args.finish()?; |
| 2827 |
|
| 2828 |
let _ = ctx.module.generate_vertex_return_type(); |
| 2829 |
|
| 2830 |
ir::Expression::RayQueryVertexPositions { |
| 2831 |
query, |
| 2832 |
committed: true, |
| 2833 |
} |
| 2834 |
} |
| 2835 |
"getCandidateHitVertexPositions" => { |
| 2836 |
let mut args = ctx.prepare_args(arguments, 1, span); |
| 2837 |
let query = self.ray_query_pointer(args.next()?, ctx)?; |
| 2838 |
args.finish()?; |
| 2839 |
|
| 2840 |
let _ = ctx.module.generate_vertex_return_type(); |
| 2841 |
|
| 2842 |
ir::Expression::RayQueryVertexPositions { |
| 2843 |
query, |
| 2844 |
committed: false, |
| 2845 |
} |
| 2846 |
} |
| 2847 |
"rayQueryProceed" => { |
| 2848 |
let mut args = ctx.prepare_args(arguments, 1, span); |
| 2849 |
let query = self.ray_query_pointer(args.next()?, ctx)?; |
| 2850 |
args.finish()?; |
| 2851 |
|
| 2852 |
let result = |
| 2853 |
ctx.interrupt_emitter(ir::Expression::RayQueryProceedResult, span)?; |
| 2854 |
let fun = ir::RayQueryFunction::Proceed { result }; |
| 2855 |
let rctx = ctx.runtime_expression_ctx(span)?; |
| 2856 |
rctx.block |
| 2857 |
.push(ir::Statement::RayQuery { query, fun }, span); |
| 2858 |
return Ok(Some(result)); |
| 2859 |
} |
| 2860 |
"rayQueryGenerateIntersection" => { |
| 2861 |
let mut args = ctx.prepare_args(arguments, 2, span); |
| 2862 |
let query = self.ray_query_pointer(args.next()?, ctx)?; |
| 2863 |
let hit_t = self.expression(args.next()?, ctx)?; |
| 2864 |
args.finish()?; |
| 2865 |
|
| 2866 |
let fun = ir::RayQueryFunction::GenerateIntersection { hit_t }; |
| 2867 |
let rctx = ctx.runtime_expression_ctx(span)?; |
| 2868 |
rctx.block |
| 2869 |
.push(ir::Statement::RayQuery { query, fun }, span); |
| 2870 |
return Ok(None); |
| 2871 |
} |
| 2872 |
"rayQueryConfirmIntersection" => { |
| 2873 |
let mut args = ctx.prepare_args(arguments, 1, span); |
| 2874 |
let query = self.ray_query_pointer(args.next()?, ctx)?; |
| 2875 |
args.finish()?; |
| 2876 |
|
| 2877 |
let fun = ir::RayQueryFunction::ConfirmIntersection; |
| 2878 |
let rctx = ctx.runtime_expression_ctx(span)?; |
| 2879 |
rctx.block |
| 2880 |
.push(ir::Statement::RayQuery { query, fun }, span); |
| 2881 |
return Ok(None); |
| 2882 |
} |
| 2883 |
"rayQueryTerminate" => { |
| 2884 |
let mut args = ctx.prepare_args(arguments, 1, span); |
| 2885 |
let query = self.ray_query_pointer(args.next()?, ctx)?; |
| 2886 |
args.finish()?; |
| 2887 |
|
| 2888 |
let fun = ir::RayQueryFunction::Terminate; |
| 2889 |
let rctx = ctx.runtime_expression_ctx(span)?; |
| 2890 |
rctx.block |
| 2891 |
.push(ir::Statement::RayQuery { query, fun }, span); |
| 2892 |
return Ok(None); |
| 2893 |
} |
| 2894 |
"rayQueryGetCommittedIntersection" => { |
| 2895 |
let mut args = ctx.prepare_args(arguments, 1, span); |
| 2896 |
let query = self.ray_query_pointer(args.next()?, ctx)?; |
| 2897 |
args.finish()?; |
| 2898 |
|
| 2899 |
let _ = ctx.module.generate_ray_intersection_type(); |
| 2900 |
ir::Expression::RayQueryGetIntersection { |
| 2901 |
query, |
| 2902 |
committed: true, |
| 2903 |
} |
| 2904 |
} |
| 2905 |
"rayQueryGetCandidateIntersection" => { |
| 2906 |
let mut args = ctx.prepare_args(arguments, 1, span); |
| 2907 |
let query = self.ray_query_pointer(args.next()?, ctx)?; |
| 2908 |
args.finish()?; |
| 2909 |
|
| 2910 |
let _ = ctx.module.generate_ray_intersection_type(); |
| 2911 |
ir::Expression::RayQueryGetIntersection { |
| 2912 |
query, |
| 2913 |
committed: false, |
| 2914 |
} |
| 2915 |
} |
| 2916 |
"RayDesc" => { |
| 2917 |
let ty = ctx.module.generate_ray_desc_type(); |
| 2918 |
let handle = self.construct( |
| 2919 |
span, |
| 2920 |
&ast::ConstructorType::Type(ty), |
| 2921 |
function.span, |
| 2922 |
arguments, |
| 2923 |
ctx, |
| 2924 |
)?; |
| 2925 |
return Ok(Some(handle)); |
| 2926 |
} |
| 2927 |
"subgroupBallot" => { |
| 2928 |
let mut args = ctx.prepare_args(arguments, 0, span); |
| 2929 |
let predicate = if arguments.len() == 1 { |
| 2930 |
Some(self.expression(args.next()?, ctx)?) |
| 2931 |
} else { |
| 2932 |
None |
| 2933 |
}; |
| 2934 |
args.finish()?; |
| 2935 |
|
| 2936 |
let result = |
| 2937 |
ctx.interrupt_emitter(ir::Expression::SubgroupBallotResult, span)?; |
| 2938 |
let rctx = ctx.runtime_expression_ctx(span)?; |
| 2939 |
rctx.block |
| 2940 |
.push(ir::Statement::SubgroupBallot { result, predicate }, span); |
| 2941 |
return Ok(Some(result)); |
| 2942 |
} |
| 2943 |
_ => { |
| 2944 |
return Err(Box::new(Error::UnknownIdent(function.span, function.name))) |
| 2945 |
} |
| 2946 |
} |
| 2947 |
}; |
| 2948 |
|
| 2949 |
let expr = ctx.append_expression(expr, span)?; |
| 2950 |
Ok(Some(expr)) |
| 2951 |
} |
| 2952 |
} |
| 2953 |
} |
| 2954 |
|
| 2955 |
/// Generate a Naga IR [`Math`] expression. |
| 2956 |
/// |
| 2957 |
/// Generate Naga IR for a call to the [`MathFunction`] `fun`, whose |
| 2958 |
/// unlowered arguments are `ast_arguments`. |
| 2959 |
/// |
| 2960 |
/// The `span` argument should give the span of the function name in the |
| 2961 |
/// call expression. |
| 2962 |
/// |
| 2963 |
/// [`Math`]: ir::Expression::Math |
| 2964 |
/// [`MathFunction`]: ir::MathFunction |
| 2965 |
fn math_function_helper( |
| 2966 |
&mut self, |
| 2967 |
span: Span, |
| 2968 |
fun: ir::MathFunction, |
| 2969 |
ast_arguments: &[Handle<ast::Expression<'source>>], |
| 2970 |
ctx: &mut ExpressionContext<'source, '_, '_>, |
| 2971 |
) -> Result<'source, ir::Expression> { |
| 2972 |
let mut lowered_arguments = Vec::with_capacity(ast_arguments.len()); |
| 2973 |
for &arg in ast_arguments { |
| 2974 |
let lowered = self.expression_for_abstract(arg, ctx)?; |
| 2975 |
ctx.grow_types(lowered)?; |
| 2976 |
lowered_arguments.push(lowered); |
| 2977 |
} |
| 2978 |
|
| 2979 |
let fun_overloads = fun.overloads(); |
| 2980 |
let rule = self.resolve_overloads(span, fun, fun_overloads, &lowered_arguments, ctx)?; |
| 2981 |
self.apply_automatic_conversions_for_call(&rule, &mut lowered_arguments, ctx)?; |
| 2982 |
|
| 2983 |
// If this function returns a predeclared type, register it |
| 2984 |
// in `Module::special_types`. The typifier will expect to |
| 2985 |
// be able to find it there. |
| 2986 |
if let proc::Conclusion::Predeclared(predeclared) = rule.conclusion { |
| 2987 |
ctx.module.generate_predeclared_type(predeclared); |
| 2988 |
} |
| 2989 |
|
| 2990 |
Ok(ir::Expression::Math { |
| 2991 |
fun, |
| 2992 |
arg: lowered_arguments[0], |
| 2993 |
arg1: lowered_arguments.get(1).cloned(), |
| 2994 |
arg2: lowered_arguments.get(2).cloned(), |
| 2995 |
arg3: lowered_arguments.get(3).cloned(), |
| 2996 |
}) |
| 2997 |
} |
| 2998 |
|
| 2999 |
/// Choose the right overload for a function call. |
| 3000 |
/// |
| 3001 |
/// Return a [`Rule`] representing the most preferred overload in |
| 3002 |
/// `overloads` to apply to `arguments`, or return an error explaining why |
| 3003 |
/// the call is not valid. |
| 3004 |
/// |
| 3005 |
/// Use `fun` to identify the function being called in error messages; |
| 3006 |
/// `span` should be the span of the function name in the call expression. |
| 3007 |
/// |
| 3008 |
/// [`Rule`]: proc::Rule |
| 3009 |
fn resolve_overloads<O, F>( |
| 3010 |
&self, |
| 3011 |
span: Span, |
| 3012 |
fun: F, |
| 3013 |
overloads: O, |
| 3014 |
arguments: &[Handle<ir::Expression>], |
| 3015 |
ctx: &ExpressionContext<'source, '_, '_>, |
| 3016 |
) -> Result<'source, proc::Rule> |
| 3017 |
where |
| 3018 |
O: proc::OverloadSet, |
| 3019 |
F: TryToWgsl + core::fmt::Debug + Copy, |
| 3020 |
{ |
| 3021 |
let mut remaining_overloads = overloads.clone(); |
| 3022 |
let min_arguments = remaining_overloads.min_arguments(); |
| 3023 |
let max_arguments = remaining_overloads.max_arguments(); |
| 3024 |
if arguments.len() < min_arguments { |
| 3025 |
return Err(Box::new(Error::WrongArgumentCount { |
| 3026 |
span, |
| 3027 |
expected: min_arguments as u32..max_arguments as u32, |
| 3028 |
found: arguments.len() as u32, |
| 3029 |
})); |
| 3030 |
} |
| 3031 |
if arguments.len() > max_arguments { |
| 3032 |
return Err(Box::new(Error::TooManyArguments { |
| 3033 |
function: fun.to_wgsl_for_diagnostics(), |
| 3034 |
call_span: span, |
| 3035 |
arg_span: ctx.get_expression_span(arguments[max_arguments]), |
| 3036 |
max_arguments: max_arguments as _, |
| 3037 |
})); |
| 3038 |
} |
| 3039 |
|
| 3040 |
log::debug!( |
| 3041 |
"Initial overloads: {:#?}", |
| 3042 |
remaining_overloads.for_debug(&ctx.module.types) |
| 3043 |
); |
| 3044 |
|
| 3045 |
for (arg_index, &arg) in arguments.iter().enumerate() { |
| 3046 |
let arg_type_resolution = &ctx.typifier()[arg]; |
| 3047 |
let arg_inner = arg_type_resolution.inner_with(&ctx.module.types); |
| 3048 |
log::debug!( |
| 3049 |
"Supplying argument {arg_index} of type {:?}", |
| 3050 |
arg_type_resolution.for_debug(&ctx.module.types) |
| 3051 |
); |
| 3052 |
let next_remaining_overloads = |
| 3053 |
remaining_overloads.arg(arg_index, arg_inner, &ctx.module.types); |
| 3054 |
|
| 3055 |
// If any argument is not a constant expression, then no overloads |
| 3056 |
// that accept abstract values should be considered. |
| 3057 |
// (`OverloadSet::concrete_only` is supposed to help impose this |
| 3058 |
// restriction.) However, no `MathFunction` accepts a mix of |
| 3059 |
// abstract and concrete arguments, so we don't need to worry |
| 3060 |
// about that here. |
| 3061 |
|
| 3062 |
log::debug!( |
| 3063 |
"Remaining overloads: {:#?}", |
| 3064 |
next_remaining_overloads.for_debug(&ctx.module.types) |
| 3065 |
); |
| 3066 |
|
| 3067 |
// If the set of remaining overloads is empty, then this argument's type |
| 3068 |
// was unacceptable. Diagnose the problem and produce an error message. |
| 3069 |
if next_remaining_overloads.is_empty() { |
| 3070 |
let function = fun.to_wgsl_for_diagnostics(); |
| 3071 |
let call_span = span; |
| 3072 |
let arg_span = ctx.get_expression_span(arg); |
| 3073 |
let arg_ty = ctx.as_diagnostic_display(arg_type_resolution).to_string(); |
| 3074 |
|
| 3075 |
// Is this type *ever* permitted for the arg_index'th argument? |
| 3076 |
// For example, `bool` is never permitted for `max`. |
| 3077 |
let only_this_argument = overloads.arg(arg_index, arg_inner, &ctx.module.types); |
| 3078 |
if only_this_argument.is_empty() { |
| 3079 |
// No overload of `fun` accepts this type as the |
| 3080 |
// arg_index'th argument. Determine the set of types that |
| 3081 |
// would ever be allowed there. |
| 3082 |
let allowed: Vec<String> = overloads |
| 3083 |
.allowed_args(arg_index, &ctx.module.to_ctx()) |
| 3084 |
.iter() |
| 3085 |
.map(|ty| ctx.type_resolution_to_string(ty)) |
| 3086 |
.collect(); |
| 3087 |
|
| 3088 |
if allowed.is_empty() { |
| 3089 |
// No overload of `fun` accepts any argument at this |
| 3090 |
// index, so it's a simple case of excess arguments. |
| 3091 |
// However, since each `MathFunction`'s overloads all |
| 3092 |
// have the same arity, we should have detected this |
| 3093 |
// earlier. |
| 3094 |
unreachable!("expected all overloads to have the same arity"); |
| 3095 |
} |
| 3096 |
|
| 3097 |
// Some overloads of `fun` do accept this many arguments, |
| 3098 |
// but none accept one of this type. |
| 3099 |
return Err(Box::new(Error::WrongArgumentType { |
| 3100 |
function, |
| 3101 |
call_span, |
| 3102 |
arg_span, |
| 3103 |
arg_index: arg_index as u32, |
| 3104 |
arg_ty, |
| 3105 |
allowed, |
| 3106 |
})); |
| 3107 |
} |
| 3108 |
|
| 3109 |
// This argument's type is accepted by some overloads---just |
| 3110 |
// not those overloads that remain, given the prior arguments. |
| 3111 |
// For example, `max` accepts `f32` as its second argument - |
| 3112 |
// but not if the first was `i32`. |
| 3113 |
|
| 3114 |
// Build a list of the types that would have been accepted here, |
| 3115 |
// given the prior arguments. |
| 3116 |
let allowed: Vec<String> = remaining_overloads |
| 3117 |
.allowed_args(arg_index, &ctx.module.to_ctx()) |
| 3118 |
.iter() |
| 3119 |
.map(|ty| ctx.type_resolution_to_string(ty)) |
| 3120 |
.collect(); |
| 3121 |
|
| 3122 |
// Re-run the argument list to determine which prior argument |
| 3123 |
// made this one unacceptable. |
| 3124 |
let mut remaining_overloads = overloads; |
| 3125 |
for (prior_index, &prior_expr) in arguments.iter().enumerate() { |
| 3126 |
let prior_type_resolution = &ctx.typifier()[prior_expr]; |
| 3127 |
let prior_ty = prior_type_resolution.inner_with(&ctx.module.types); |
| 3128 |
remaining_overloads = |
| 3129 |
remaining_overloads.arg(prior_index, prior_ty, &ctx.module.types); |
| 3130 |
if remaining_overloads |
| 3131 |
.arg(arg_index, arg_inner, &ctx.module.types) |
| 3132 |
.is_empty() |
| 3133 |
{ |
| 3134 |
// This is the argument that killed our dreams. |
| 3135 |
let inconsistent_span = ctx.get_expression_span(arguments[prior_index]); |
| 3136 |
let inconsistent_ty = |
| 3137 |
ctx.as_diagnostic_display(prior_type_resolution).to_string(); |
| 3138 |
|
| 3139 |
if allowed.is_empty() { |
| 3140 |
// Some overloads did accept `ty` at `arg_index`, but |
| 3141 |
// given the arguments up through `prior_expr`, we see |
| 3142 |
// no types acceptable at `arg_index`. This means that some |
| 3143 |
// overloads expect fewer arguments than others. However, |
| 3144 |
// each `MathFunction`'s overloads have the same arity, so this |
| 3145 |
// should be impossible. |
| 3146 |
unreachable!("expected all overloads to have the same arity"); |
| 3147 |
} |
| 3148 |
|
| 3149 |
// Report `arg`'s type as inconsistent with `prior_expr`'s |
| 3150 |
return Err(Box::new(Error::InconsistentArgumentType { |
| 3151 |
function, |
| 3152 |
call_span, |
| 3153 |
arg_span, |
| 3154 |
arg_index: arg_index as u32, |
| 3155 |
arg_ty, |
| 3156 |
inconsistent_span, |
| 3157 |
inconsistent_index: prior_index as u32, |
| 3158 |
inconsistent_ty, |
| 3159 |
allowed, |
| 3160 |
})); |
| 3161 |
} |
| 3162 |
} |
| 3163 |
unreachable!("Failed to eliminate argument type when re-tried"); |
| 3164 |
} |
| 3165 |
remaining_overloads = next_remaining_overloads; |
| 3166 |
} |
| 3167 |
|
| 3168 |
// Select the most preferred type rule for this call, |
| 3169 |
// given the argument types supplied above. |
| 3170 |
Ok(remaining_overloads.most_preferred()) |
| 3171 |
} |
| 3172 |
|
| 3173 |
/// Apply automatic type conversions for a function call. |
| 3174 |
/// |
| 3175 |
/// Apply whatever automatic conversions are needed to pass `arguments` to |
| 3176 |
/// the function overload described by `rule`. Update `arguments` to refer |
| 3177 |
/// to the converted arguments. |
| 3178 |
fn apply_automatic_conversions_for_call( |
| 3179 |
&self, |
| 3180 |
rule: &proc::Rule, |
| 3181 |
arguments: &mut [Handle<ir::Expression>], |
| 3182 |
ctx: &mut ExpressionContext<'source, '_, '_>, |
| 3183 |
) -> Result<'source, ()> { |
| 3184 |
for (i, argument) in arguments.iter_mut().enumerate() { |
| 3185 |
let goal_inner = rule.arguments[i].inner_with(&ctx.module.types); |
| 3186 |
let converted = match goal_inner.scalar_for_conversions(&ctx.module.types) { |
| 3187 |
Some(goal_scalar) => { |
| 3188 |
let arg_span = ctx.get_expression_span(*argument); |
| 3189 |
ctx.try_automatic_conversion_for_leaf_scalar(*argument, goal_scalar, arg_span)? |
| 3190 |
} |
| 3191 |
// No conversion is necessary. |
| 3192 |
None => *argument, |
| 3193 |
}; |
| 3194 |
|
| 3195 |
*argument = converted; |
| 3196 |
} |
| 3197 |
|
| 3198 |
Ok(()) |
| 3199 |
} |
| 3200 |
|
| 3201 |
fn atomic_pointer( |
| 3202 |
&mut self, |
| 3203 |
expr: Handle<ast::Expression<'source>>, |
| 3204 |
ctx: &mut ExpressionContext<'source, '_, '_>, |
| 3205 |
) -> Result<'source, (Handle<ir::Expression>, ir::Scalar)> { |
| 3206 |
let span = ctx.ast_expressions.get_span(expr); |
| 3207 |
let pointer = self.expression(expr, ctx)?; |
| 3208 |
|
| 3209 |
match *resolve_inner!(ctx, pointer) { |
| 3210 |
ir::TypeInner::Pointer { base, .. } => match ctx.module.types[base].inner { |
| 3211 |
ir::TypeInner::Atomic(scalar) => Ok((pointer, scalar)), |
| 3212 |
ref other => { |
| 3213 |
log::error!("Pointer type to {:?} passed to atomic op", other); |
| 3214 |
Err(Box::new(Error::InvalidAtomicPointer(span))) |
| 3215 |
} |
| 3216 |
}, |
| 3217 |
ref other => { |
| 3218 |
log::error!("Type {:?} passed to atomic op", other); |
| 3219 |
Err(Box::new(Error::InvalidAtomicPointer(span))) |
| 3220 |
} |
| 3221 |
} |
| 3222 |
} |
| 3223 |
|
| 3224 |
fn atomic_helper( |
| 3225 |
&mut self, |
| 3226 |
span: Span, |
| 3227 |
fun: ir::AtomicFunction, |
| 3228 |
args: &[Handle<ast::Expression<'source>>], |
| 3229 |
is_statement: bool, |
| 3230 |
ctx: &mut ExpressionContext<'source, '_, '_>, |
| 3231 |
) -> Result<'source, Option<Handle<ir::Expression>>> { |
| 3232 |
let mut args = ctx.prepare_args(args, 2, span); |
| 3233 |
|
| 3234 |
let (pointer, scalar) = self.atomic_pointer(args.next()?, ctx)?; |
| 3235 |
let value = self.expression_with_leaf_scalar(args.next()?, scalar, ctx)?; |
| 3236 |
let value_inner = resolve_inner!(ctx, value); |
| 3237 |
args.finish()?; |
| 3238 |
|
| 3239 |
// If we don't use the return value of a 64-bit `min` or `max` |
| 3240 |
// operation, generate a no-result form of the `Atomic` statement, so |
| 3241 |
// that we can pass validation with only `SHADER_INT64_ATOMIC_MIN_MAX` |
| 3242 |
// whenever possible. |
| 3243 |
let is_64_bit_min_max = matches!(fun, ir::AtomicFunction::Min | ir::AtomicFunction::Max) |
| 3244 |
&& matches!( |
| 3245 |
*value_inner, |
| 3246 |
ir::TypeInner::Scalar(ir::Scalar { width: 8, .. }) |
| 3247 |
); |
| 3248 |
let result = if is_64_bit_min_max && is_statement { |
| 3249 |
let rctx = ctx.runtime_expression_ctx(span)?; |
| 3250 |
rctx.block |
| 3251 |
.extend(rctx.emitter.finish(&rctx.function.expressions)); |
| 3252 |
rctx.emitter.start(&rctx.function.expressions); |
| 3253 |
None |
| 3254 |
} else { |
| 3255 |
let ty = ctx.register_type(value)?; |
| 3256 |
Some(ctx.interrupt_emitter( |
| 3257 |
ir::Expression::AtomicResult { |
| 3258 |
ty, |
| 3259 |
comparison: false, |
| 3260 |
}, |
| 3261 |
span, |
| 3262 |
)?) |
| 3263 |
}; |
| 3264 |
let rctx = ctx.runtime_expression_ctx(span)?; |
| 3265 |
rctx.block.push( |
| 3266 |
ir::Statement::Atomic { |
| 3267 |
pointer, |
| 3268 |
fun, |
| 3269 |
value, |
| 3270 |
result, |
| 3271 |
}, |
| 3272 |
span, |
| 3273 |
); |
| 3274 |
Ok(result) |
| 3275 |
} |
| 3276 |
|
| 3277 |
fn texture_sample_helper( |
| 3278 |
&mut self, |
| 3279 |
fun: Texture, |
| 3280 |
args: &[Handle<ast::Expression<'source>>], |
| 3281 |
span: Span, |
| 3282 |
ctx: &mut ExpressionContext<'source, '_, '_>, |
| 3283 |
) -> Result<'source, ir::Expression> { |
| 3284 |
let mut args = ctx.prepare_args(args, fun.min_argument_count(), span); |
| 3285 |
|
| 3286 |
fn get_image_and_span<'source>( |
| 3287 |
lowerer: &mut Lowerer<'source, '_>, |
| 3288 |
args: &mut ArgumentContext<'_, 'source>, |
| 3289 |
ctx: &mut ExpressionContext<'source, '_, '_>, |
| 3290 |
) -> Result<'source, (Handle<ir::Expression>, Span)> { |
| 3291 |
let image = args.next()?; |
| 3292 |
let image_span = ctx.ast_expressions.get_span(image); |
| 3293 |
let image = lowerer.expression_for_abstract(image, ctx)?; |
| 3294 |
Ok((image, image_span)) |
| 3295 |
} |
| 3296 |
|
| 3297 |
let image; |
| 3298 |
let image_span; |
| 3299 |
let gather; |
| 3300 |
match fun { |
| 3301 |
Texture::Gather => { |
| 3302 |
let image_or_component = args.next()?; |
| 3303 |
let image_or_component_span = ctx.ast_expressions.get_span(image_or_component); |
| 3304 |
// Gathers from depth textures don't take an initial `component` argument. |
| 3305 |
let lowered_image_or_component = self.expression(image_or_component, ctx)?; |
| 3306 |
|
| 3307 |
match *resolve_inner!(ctx, lowered_image_or_component) { |
| 3308 |
ir::TypeInner::Image { |
| 3309 |
class: ir::ImageClass::Depth { .. }, |
| 3310 |
.. |
| 3311 |
} => { |
| 3312 |
image = lowered_image_or_component; |
| 3313 |
image_span = image_or_component_span; |
| 3314 |
gather = Some(ir::SwizzleComponent::X); |
| 3315 |
} |
| 3316 |
_ => { |
| 3317 |
(image, image_span) = get_image_and_span(self, &mut args, ctx)?; |
| 3318 |
gather = Some(ctx.gather_component( |
| 3319 |
lowered_image_or_component, |
| 3320 |
image_or_component_span, |
| 3321 |
span, |
| 3322 |
)?); |
| 3323 |
} |
| 3324 |
} |
| 3325 |
} |
| 3326 |
Texture::GatherCompare => { |
| 3327 |
(image, image_span) = get_image_and_span(self, &mut args, ctx)?; |
| 3328 |
gather = Some(ir::SwizzleComponent::X); |
| 3329 |
} |
| 3330 |
|
| 3331 |
_ => { |
| 3332 |
(image, image_span) = get_image_and_span(self, &mut args, ctx)?; |
| 3333 |
gather = None; |
| 3334 |
} |
| 3335 |
}; |
| 3336 |
|
| 3337 |
let sampler = self.expression_for_abstract(args.next()?, ctx)?; |
| 3338 |
|
| 3339 |
let coordinate = self.expression_with_leaf_scalar(args.next()?, ir::Scalar::F32, ctx)?; |
| 3340 |
|
| 3341 |
let (class, arrayed) = ctx.image_data(image, image_span)?; |
| 3342 |
let array_index = arrayed |
| 3343 |
.then(|| self.expression(args.next()?, ctx)) |
| 3344 |
.transpose()?; |
| 3345 |
|
| 3346 |
let level; |
| 3347 |
let depth_ref; |
| 3348 |
match fun { |
| 3349 |
Texture::Gather => { |
| 3350 |
level = ir::SampleLevel::Zero; |
| 3351 |
depth_ref = None; |
| 3352 |
} |
| 3353 |
Texture::GatherCompare => { |
| 3354 |
let reference = |
| 3355 |
self.expression_with_leaf_scalar(args.next()?, ir::Scalar::F32, ctx)?; |
| 3356 |
level = ir::SampleLevel::Zero; |
| 3357 |
depth_ref = Some(reference); |
| 3358 |
} |
| 3359 |
|
| 3360 |
Texture::Sample => { |
| 3361 |
level = ir::SampleLevel::Auto; |
| 3362 |
depth_ref = None; |
| 3363 |
} |
| 3364 |
Texture::SampleBias => { |
| 3365 |
let bias = self.expression_with_leaf_scalar(args.next()?, ir::Scalar::F32, ctx)?; |
| 3366 |
level = ir::SampleLevel::Bias(bias); |
| 3367 |
depth_ref = None; |
| 3368 |
} |
| 3369 |
Texture::SampleCompare => { |
| 3370 |
let reference = |
| 3371 |
self.expression_with_leaf_scalar(args.next()?, ir::Scalar::F32, ctx)?; |
| 3372 |
level = ir::SampleLevel::Auto; |
| 3373 |
depth_ref = Some(reference); |
| 3374 |
} |
| 3375 |
Texture::SampleCompareLevel => { |
| 3376 |
let reference = |
| 3377 |
self.expression_with_leaf_scalar(args.next()?, ir::Scalar::F32, ctx)?; |
| 3378 |
level = ir::SampleLevel::Zero; |
| 3379 |
depth_ref = Some(reference); |
| 3380 |
} |
| 3381 |
Texture::SampleGrad => { |
| 3382 |
let x = self.expression_with_leaf_scalar(args.next()?, ir::Scalar::F32, ctx)?; |
| 3383 |
let y = self.expression_with_leaf_scalar(args.next()?, ir::Scalar::F32, ctx)?; |
| 3384 |
level = ir::SampleLevel::Gradient { x, y }; |
| 3385 |
depth_ref = None; |
| 3386 |
} |
| 3387 |
Texture::SampleLevel => { |
| 3388 |
let exact = match class { |
| 3389 |
// When applied to depth textures, `textureSampleLevel`'s |
| 3390 |
// `level` argument is an `i32` or `u32`. |
| 3391 |
ir::ImageClass::Depth { .. } => self.expression(args.next()?, ctx)?, |
| 3392 |
|
| 3393 |
// When applied to other sampled types, its `level` argument |
| 3394 |
// is an `f32`. |
| 3395 |
ir::ImageClass::Sampled { .. } => { |
| 3396 |
self.expression_with_leaf_scalar(args.next()?, ir::Scalar::F32, ctx)? |
| 3397 |
} |
| 3398 |
|
| 3399 |
// Sampling `Storage` textures isn't allowed at all. Let the |
| 3400 |
// validator report the error. |
| 3401 |
ir::ImageClass::Storage { .. } => self.expression(args.next()?, ctx)?, |
| 3402 |
}; |
| 3403 |
level = ir::SampleLevel::Exact(exact); |
| 3404 |
depth_ref = None; |
| 3405 |
} |
| 3406 |
}; |
| 3407 |
|
| 3408 |
let offset = args |
| 3409 |
.next() |
| 3410 |
.map(|arg| self.expression_with_leaf_scalar(arg, ir::Scalar::I32, &mut ctx.as_const())) |
| 3411 |
.ok() |
| 3412 |
.transpose()?; |
| 3413 |
|
| 3414 |
args.finish()?; |
| 3415 |
|
| 3416 |
Ok(ir::Expression::ImageSample { |
| 3417 |
image, |
| 3418 |
sampler, |
| 3419 |
gather, |
| 3420 |
coordinate, |
| 3421 |
array_index, |
| 3422 |
offset, |
| 3423 |
level, |
| 3424 |
depth_ref, |
| 3425 |
}) |
| 3426 |
} |
| 3427 |
|
| 3428 |
fn subgroup_operation_helper( |
| 3429 |
&mut self, |
| 3430 |
span: Span, |
| 3431 |
op: ir::SubgroupOperation, |
| 3432 |
collective_op: ir::CollectiveOperation, |
| 3433 |
arguments: &[Handle<ast::Expression<'source>>], |
| 3434 |
ctx: &mut ExpressionContext<'source, '_, '_>, |
| 3435 |
) -> Result<'source, Handle<ir::Expression>> { |
| 3436 |
let mut args = ctx.prepare_args(arguments, 1, span); |
| 3437 |
|
| 3438 |
let argument = self.expression(args.next()?, ctx)?; |
| 3439 |
args.finish()?; |
| 3440 |
|
| 3441 |
let ty = ctx.register_type(argument)?; |
| 3442 |
|
| 3443 |
let result = ctx.interrupt_emitter(ir::Expression::SubgroupOperationResult { ty }, span)?; |
| 3444 |
let rctx = ctx.runtime_expression_ctx(span)?; |
| 3445 |
rctx.block.push( |
| 3446 |
ir::Statement::SubgroupCollectiveOperation { |
| 3447 |
op, |
| 3448 |
collective_op, |
| 3449 |
argument, |
| 3450 |
result, |
| 3451 |
}, |
| 3452 |
span, |
| 3453 |
); |
| 3454 |
Ok(result) |
| 3455 |
} |
| 3456 |
|
| 3457 |
fn subgroup_gather_helper( |
| 3458 |
&mut self, |
| 3459 |
span: Span, |
| 3460 |
mode: SubgroupGather, |
| 3461 |
arguments: &[Handle<ast::Expression<'source>>], |
| 3462 |
ctx: &mut ExpressionContext<'source, '_, '_>, |
| 3463 |
) -> Result<'source, Handle<ir::Expression>> { |
| 3464 |
let mut args = ctx.prepare_args(arguments, 2, span); |
| 3465 |
|
| 3466 |
let argument = self.expression(args.next()?, ctx)?; |
| 3467 |
|
| 3468 |
use SubgroupGather as Sg; |
| 3469 |
let mode = if let Sg::BroadcastFirst = mode { |
| 3470 |
ir::GatherMode::BroadcastFirst |
| 3471 |
} else { |
| 3472 |
let index = self.expression(args.next()?, ctx)?; |
| 3473 |
match mode { |
| 3474 |
Sg::Broadcast => ir::GatherMode::Broadcast(index), |
| 3475 |
Sg::Shuffle => ir::GatherMode::Shuffle(index), |
| 3476 |
Sg::ShuffleDown => ir::GatherMode::ShuffleDown(index), |
| 3477 |
Sg::ShuffleUp => ir::GatherMode::ShuffleUp(index), |
| 3478 |
Sg::ShuffleXor => ir::GatherMode::ShuffleXor(index), |
| 3479 |
Sg::BroadcastFirst => unreachable!(), |
| 3480 |
} |
| 3481 |
}; |
| 3482 |
|
| 3483 |
args.finish()?; |
| 3484 |
|
| 3485 |
let ty = ctx.register_type(argument)?; |
| 3486 |
|
| 3487 |
let result = ctx.interrupt_emitter(ir::Expression::SubgroupOperationResult { ty }, span)?; |
| 3488 |
let rctx = ctx.runtime_expression_ctx(span)?; |
| 3489 |
rctx.block.push( |
| 3490 |
ir::Statement::SubgroupGather { |
| 3491 |
mode, |
| 3492 |
argument, |
| 3493 |
result, |
| 3494 |
}, |
| 3495 |
span, |
| 3496 |
); |
| 3497 |
Ok(result) |
| 3498 |
} |
| 3499 |
|
| 3500 |
fn r#struct( |
| 3501 |
&mut self, |
| 3502 |
s: &ast::Struct<'source>, |
| 3503 |
span: Span, |
| 3504 |
ctx: &mut GlobalContext<'source, '_, '_>, |
| 3505 |
) -> Result<'source, Handle<ir::Type>> { |
| 3506 |
let mut offset = 0; |
| 3507 |
let mut struct_alignment = proc::Alignment::ONE; |
| 3508 |
let mut members = Vec::with_capacity(s.members.len()); |
| 3509 |
|
| 3510 |
for member in s.members.iter() { |
| 3511 |
let ty = self.resolve_ast_type(member.ty, &mut ctx.as_const())?; |
| 3512 |
|
| 3513 |
ctx.layouter.update(ctx.module.to_ctx()).unwrap(); |
| 3514 |
|
| 3515 |
let member_min_size = ctx.layouter[ty].size; |
| 3516 |
let member_min_alignment = ctx.layouter[ty].alignment; |
| 3517 |
|
| 3518 |
let member_size = if let Some(size_expr) = member.size { |
| 3519 |
let (size, span) = self.const_u32(size_expr, &mut ctx.as_const())?; |
| 3520 |
if size < member_min_size { |
| 3521 |
return Err(Box::new(Error::SizeAttributeTooLow(span, member_min_size))); |
| 3522 |
} else { |
| 3523 |
size |
| 3524 |
} |
| 3525 |
} else { |
| 3526 |
member_min_size |
| 3527 |
}; |
| 3528 |
|
| 3529 |
let member_alignment = if let Some(align_expr) = member.align { |
| 3530 |
let (align, span) = self.const_u32(align_expr, &mut ctx.as_const())?; |
| 3531 |
if let Some(alignment) = proc::Alignment::new(align) { |
| 3532 |
if alignment < member_min_alignment { |
| 3533 |
return Err(Box::new(Error::AlignAttributeTooLow( |
| 3534 |
span, |
| 3535 |
member_min_alignment, |
| 3536 |
))); |
| 3537 |
} else { |
| 3538 |
alignment |
| 3539 |
} |
| 3540 |
} else { |
| 3541 |
return Err(Box::new(Error::NonPowerOfTwoAlignAttribute(span))); |
| 3542 |
} |
| 3543 |
} else { |
| 3544 |
member_min_alignment |
| 3545 |
}; |
| 3546 |
|
| 3547 |
let binding = self.binding(&member.binding, ty, ctx)?; |
| 3548 |
|
| 3549 |
offset = member_alignment.round_up(offset); |
| 3550 |
struct_alignment = struct_alignment.max(member_alignment); |
| 3551 |
|
| 3552 |
members.push(ir::StructMember { |
| 3553 |
name: Some(member.name.name.to_owned()), |
| 3554 |
ty, |
| 3555 |
binding, |
| 3556 |
offset, |
| 3557 |
}); |
| 3558 |
|
| 3559 |
offset += member_size; |
| 3560 |
} |
| 3561 |
|
| 3562 |
let size = struct_alignment.round_up(offset); |
| 3563 |
let inner = ir::TypeInner::Struct { |
| 3564 |
members, |
| 3565 |
span: size, |
| 3566 |
}; |
| 3567 |
|
| 3568 |
let handle = ctx.module.types.insert( |
| 3569 |
ir::Type { |
| 3570 |
name: Some(s.name.name.to_string()), |
| 3571 |
inner, |
| 3572 |
}, |
| 3573 |
span, |
| 3574 |
); |
| 3575 |
Ok(handle) |
| 3576 |
} |
| 3577 |
|
| 3578 |
fn const_u32( |
| 3579 |
&mut self, |
| 3580 |
expr: Handle<ast::Expression<'source>>, |
| 3581 |
ctx: &mut ExpressionContext<'source, '_, '_>, |
| 3582 |
) -> Result<'source, (u32, Span)> { |
| 3583 |
let span = ctx.ast_expressions.get_span(expr); |
| 3584 |
let expr = self.expression(expr, ctx)?; |
| 3585 |
let value = ctx |
| 3586 |
.module |
| 3587 |
.to_ctx() |
| 3588 |
.eval_expr_to_u32(expr) |
| 3589 |
.map_err(|err| match err { |
| 3590 |
proc::U32EvalError::NonConst => Error::ExpectedConstExprConcreteIntegerScalar(span), |
| 3591 |
proc::U32EvalError::Negative => Error::ExpectedNonNegative(span), |
| 3592 |
})?; |
| 3593 |
Ok((value, span)) |
| 3594 |
} |
| 3595 |
|
| 3596 |
fn array_size( |
| 3597 |
&mut self, |
| 3598 |
size: ast::ArraySize<'source>, |
| 3599 |
ctx: &mut ExpressionContext<'source, '_, '_>, |
| 3600 |
) -> Result<'source, ir::ArraySize> { |
| 3601 |
Ok(match size { |
| 3602 |
ast::ArraySize::Constant(expr) => { |
| 3603 |
let span = ctx.ast_expressions.get_span(expr); |
| 3604 |
let const_expr = self.expression(expr, &mut ctx.as_const()); |
| 3605 |
match const_expr { |
| 3606 |
Ok(value) => { |
| 3607 |
let len = ctx.const_eval_expr_to_u32(value).map_err(|err| { |
| 3608 |
Box::new(match err { |
| 3609 |
proc::U32EvalError::NonConst => { |
| 3610 |
Error::ExpectedConstExprConcreteIntegerScalar(span) |
| 3611 |
} |
| 3612 |
proc::U32EvalError::Negative => { |
| 3613 |
Error::ExpectedPositiveArrayLength(span) |
| 3614 |
} |
| 3615 |
}) |
| 3616 |
})?; |
| 3617 |
let size = |
| 3618 |
NonZeroU32::new(len).ok_or(Error::ExpectedPositiveArrayLength(span))?; |
| 3619 |
ir::ArraySize::Constant(size) |
| 3620 |
} |
| 3621 |
Err(err) => { |
| 3622 |
if let Error::ConstantEvaluatorError(ref ty, _) = *err { |
| 3623 |
match **ty { |
| 3624 |
proc::ConstantEvaluatorError::OverrideExpr => { |
| 3625 |
ir::ArraySize::Pending(self.array_size_override( |
| 3626 |
expr, |
| 3627 |
&mut ctx.as_global().as_override(), |
| 3628 |
span, |
| 3629 |
)?) |
| 3630 |
} |
| 3631 |
_ => { |
| 3632 |
return Err(err); |
| 3633 |
} |
| 3634 |
} |
| 3635 |
} else { |
| 3636 |
return Err(err); |
| 3637 |
} |
| 3638 |
} |
| 3639 |
} |
| 3640 |
} |
| 3641 |
ast::ArraySize::Dynamic => ir::ArraySize::Dynamic, |
| 3642 |
}) |
| 3643 |
} |
| 3644 |
|
| 3645 |
fn array_size_override( |
| 3646 |
&mut self, |
| 3647 |
size_expr: Handle<ast::Expression<'source>>, |
| 3648 |
ctx: &mut ExpressionContext<'source, '_, '_>, |
| 3649 |
span: Span, |
| 3650 |
) -> Result<'source, Handle<ir::Override>> { |
| 3651 |
let expr = self.expression(size_expr, ctx)?; |
| 3652 |
match resolve_inner!(ctx, expr).scalar_kind().ok_or(0) { |
| 3653 |
Ok(ir::ScalarKind::Sint) | Ok(ir::ScalarKind::Uint) => Ok({ |
| 3654 |
if let ir::Expression::Override(handle) = ctx.module.global_expressions[expr] { |
| 3655 |
handle |
| 3656 |
} else { |
| 3657 |
let ty = ctx.register_type(expr)?; |
| 3658 |
ctx.module.overrides.append( |
| 3659 |
ir::Override { |
| 3660 |
name: None, |
| 3661 |
id: None, |
| 3662 |
ty, |
| 3663 |
init: Some(expr), |
| 3664 |
}, |
| 3665 |
span, |
| 3666 |
) |
| 3667 |
} |
| 3668 |
}), |
| 3669 |
_ => Err(Box::new(Error::ExpectedConstExprConcreteIntegerScalar( |
| 3670 |
span, |
| 3671 |
))), |
| 3672 |
} |
| 3673 |
} |
| 3674 |
|
| 3675 |
/// Build the Naga equivalent of a named AST type. |
| 3676 |
/// |
| 3677 |
/// Return a Naga `Handle<Type>` representing the front-end type |
| 3678 |
/// `handle`, which should be named `name`, if given. |
| 3679 |
/// |
| 3680 |
/// If `handle` refers to a type cached in [`SpecialTypes`], |
| 3681 |
/// `name` may be ignored. |
| 3682 |
/// |
| 3683 |
/// [`SpecialTypes`]: ir::SpecialTypes |
| 3684 |
fn resolve_named_ast_type( |
| 3685 |
&mut self, |
| 3686 |
handle: Handle<ast::Type<'source>>, |
| 3687 |
name: Option<String>, |
| 3688 |
ctx: &mut ExpressionContext<'source, '_, '_>, |
| 3689 |
) -> Result<'source, Handle<ir::Type>> { |
| 3690 |
let inner = match ctx.types[handle] { |
| 3691 |
ast::Type::Scalar(scalar) => scalar.to_inner_scalar(), |
| 3692 |
ast::Type::Vector { size, ty, ty_span } => { |
| 3693 |
let ty = self.resolve_ast_type(ty, ctx)?; |
| 3694 |
let scalar = match ctx.module.types[ty].inner { |
| 3695 |
ir::TypeInner::Scalar(sc) => sc, |
| 3696 |
_ => return Err(Box::new(Error::UnknownScalarType(ty_span))), |
| 3697 |
}; |
| 3698 |
ir::TypeInner::Vector { size, scalar } |
| 3699 |
} |
| 3700 |
ast::Type::Matrix { |
| 3701 |
rows, |
| 3702 |
columns, |
| 3703 |
ty, |
| 3704 |
ty_span, |
| 3705 |
} => { |
| 3706 |
let ty = self.resolve_ast_type(ty, ctx)?; |
| 3707 |
let scalar = match ctx.module.types[ty].inner { |
| 3708 |
ir::TypeInner::Scalar(sc) => sc, |
| 3709 |
_ => return Err(Box::new(Error::UnknownScalarType(ty_span))), |
| 3710 |
}; |
| 3711 |
match scalar.kind { |
| 3712 |
ir::ScalarKind::Float => ir::TypeInner::Matrix { |
| 3713 |
columns, |
| 3714 |
rows, |
| 3715 |
scalar, |
| 3716 |
}, |
| 3717 |
_ => return Err(Box::new(Error::BadMatrixScalarKind(ty_span, scalar))), |
| 3718 |
} |
| 3719 |
} |
| 3720 |
ast::Type::Atomic(scalar) => scalar.to_inner_atomic(), |
| 3721 |
ast::Type::Pointer { base, space } => { |
| 3722 |
let base = self.resolve_ast_type(base, ctx)?; |
| 3723 |
ir::TypeInner::Pointer { base, space } |
| 3724 |
} |
| 3725 |
ast::Type::Array { base, size } => { |
| 3726 |
let base = self.resolve_ast_type(base, &mut ctx.as_const())?; |
| 3727 |
let size = self.array_size(size, ctx)?; |
| 3728 |
|
| 3729 |
ctx.layouter.update(ctx.module.to_ctx()).unwrap(); |
| 3730 |
let stride = ctx.layouter[base].to_stride(); |
| 3731 |
|
| 3732 |
ir::TypeInner::Array { base, size, stride } |
| 3733 |
} |
| 3734 |
ast::Type::Image { |
| 3735 |
dim, |
| 3736 |
arrayed, |
| 3737 |
class, |
| 3738 |
} => ir::TypeInner::Image { |
| 3739 |
dim, |
| 3740 |
arrayed, |
| 3741 |
class, |
| 3742 |
}, |
| 3743 |
ast::Type::Sampler { comparison } => ir::TypeInner::Sampler { comparison }, |
| 3744 |
ast::Type::AccelerationStructure { vertex_return } => { |
| 3745 |
ir::TypeInner::AccelerationStructure { vertex_return } |
| 3746 |
} |
| 3747 |
ast::Type::RayQuery { vertex_return } => ir::TypeInner::RayQuery { vertex_return }, |
| 3748 |
ast::Type::BindingArray { base, size } => { |
| 3749 |
let base = self.resolve_ast_type(base, ctx)?; |
| 3750 |
let size = self.array_size(size, ctx)?; |
| 3751 |
ir::TypeInner::BindingArray { base, size } |
| 3752 |
} |
| 3753 |
ast::Type::RayDesc => { |
| 3754 |
return Ok(ctx.module.generate_ray_desc_type()); |
| 3755 |
} |
| 3756 |
ast::Type::RayIntersection => { |
| 3757 |
return Ok(ctx.module.generate_ray_intersection_type()); |
| 3758 |
} |
| 3759 |
ast::Type::User(ref ident) => { |
| 3760 |
return match ctx.globals.get(ident.name) { |
| 3761 |
Some(&LoweredGlobalDecl::Type(handle)) => Ok(handle), |
| 3762 |
Some(_) => Err(Box::new(Error::Unexpected(ident.span, ExpectedToken::Type))), |
| 3763 |
None => Err(Box::new(Error::UnknownType(ident.span))), |
| 3764 |
} |
| 3765 |
} |
| 3766 |
}; |
| 3767 |
|
| 3768 |
Ok(ctx.as_global().ensure_type_exists(name, inner)) |
| 3769 |
} |
| 3770 |
|
| 3771 |
/// Return a Naga `Handle<Type>` representing the front-end type `handle`. |
| 3772 |
fn resolve_ast_type( |
| 3773 |
&mut self, |
| 3774 |
handle: Handle<ast::Type<'source>>, |
| 3775 |
ctx: &mut ExpressionContext<'source, '_, '_>, |
| 3776 |
) -> Result<'source, Handle<ir::Type>> { |
| 3777 |
self.resolve_named_ast_type(handle, None, ctx) |
| 3778 |
} |
| 3779 |
|
| 3780 |
fn binding( |
| 3781 |
&mut self, |
| 3782 |
binding: &Option<ast::Binding<'source>>, |
| 3783 |
ty: Handle<ir::Type>, |
| 3784 |
ctx: &mut GlobalContext<'source, '_, '_>, |
| 3785 |
) -> Result<'source, Option<ir::Binding>> { |
| 3786 |
Ok(match *binding { |
| 3787 |
Some(ast::Binding::BuiltIn(b)) => Some(ir::Binding::BuiltIn(b)), |
| 3788 |
Some(ast::Binding::Location { |
| 3789 |
location, |
| 3790 |
interpolation, |
| 3791 |
sampling, |
| 3792 |
blend_src, |
| 3793 |
}) => { |
| 3794 |
let blend_src = if let Some(blend_src) = blend_src { |
| 3795 |
Some(self.const_u32(blend_src, &mut ctx.as_const())?.0) |
| 3796 |
} else { |
| 3797 |
None |
| 3798 |
}; |
| 3799 |
|
| 3800 |
let mut binding = ir::Binding::Location { |
| 3801 |
location: self.const_u32(location, &mut ctx.as_const())?.0, |
| 3802 |
interpolation, |
| 3803 |
sampling, |
| 3804 |
blend_src, |
| 3805 |
}; |
| 3806 |
binding.apply_default_interpolation(&ctx.module.types[ty].inner); |
| 3807 |
Some(binding) |
| 3808 |
} |
| 3809 |
None => None, |
| 3810 |
}) |
| 3811 |
} |
| 3812 |
|
| 3813 |
fn ray_query_pointer( |
| 3814 |
&mut self, |
| 3815 |
expr: Handle<ast::Expression<'source>>, |
| 3816 |
ctx: &mut ExpressionContext<'source, '_, '_>, |
| 3817 |
) -> Result<'source, Handle<ir::Expression>> { |
| 3818 |
let span = ctx.ast_expressions.get_span(expr); |
| 3819 |
let pointer = self.expression(expr, ctx)?; |
| 3820 |
|
| 3821 |
match *resolve_inner!(ctx, pointer) { |
| 3822 |
ir::TypeInner::Pointer { base, .. } => match ctx.module.types[base].inner { |
| 3823 |
ir::TypeInner::RayQuery { .. } => Ok(pointer), |
| 3824 |
ref other => { |
| 3825 |
log::error!("Pointer type to {:?} passed to ray query op", other); |
| 3826 |
Err(Box::new(Error::InvalidRayQueryPointer(span))) |
| 3827 |
} |
| 3828 |
}, |
| 3829 |
ref other => { |
| 3830 |
log::error!("Type {:?} passed to ray query op", other); |
| 3831 |
Err(Box::new(Error::InvalidRayQueryPointer(span))) |
| 3832 |
} |
| 3833 |
} |
| 3834 |
} |
| 3835 |
} |
| 3836 |
|
| 3837 |
impl ir::AtomicFunction { |
| 3838 |
pub fn map(word: &str) -> Option<Self> { |
| 3839 |
Some(match word { |
| 3840 |
"atomicAdd" => ir::AtomicFunction::Add, |
| 3841 |
"atomicSub" => ir::AtomicFunction::Subtract, |
| 3842 |
"atomicAnd" => ir::AtomicFunction::And, |
| 3843 |
"atomicOr" => ir::AtomicFunction::InclusiveOr, |
| 3844 |
"atomicXor" => ir::AtomicFunction::ExclusiveOr, |
| 3845 |
"atomicMin" => ir::AtomicFunction::Min, |
| 3846 |
"atomicMax" => ir::AtomicFunction::Max, |
| 3847 |
"atomicExchange" => ir::AtomicFunction::Exchange { compare: None }, |
| 3848 |
_ => return None, |
| 3849 |
}) |
| 3850 |
} |
| 3851 |
} |