1use super::{
2 block::DebugInfoInner,
3 helpers::{contains_builtin, global_needs_wrapper, map_storage_class},
4 Block, BlockContext, CachedConstant, CachedExpressions, DebugInfo, EntryPointContext, Error,
5 Function, FunctionArgument, GlobalVariable, IdGenerator, Instruction, LocalType, LocalVariable,
6 LogicalLayout, LookupFunctionType, LookupType, NumericType, Options, PhysicalLayout,
7 PipelineOptions, ResultMember, Writer, WriterFlags, BITS_PER_BYTE,
8};
9use crate::{
10 arena::{Handle, HandleVec, UniqueArena},
11 back::spv::BindingInfo,
12 proc::{Alignment, TypeResolution},
13 valid::{FunctionInfo, ModuleInfo},
14};
15use spirv::Word;
16use std::collections::hash_map::Entry;
17
18struct FunctionInterface<'a> {
19 varying_ids: &'a mut Vec<Word>,
20 stage: crate::ShaderStage,
21}
22
23impl Function {
24 fn to_words(&self, sink: &mut impl Extend<Word>) {
25 self.signature.as_ref().unwrap().to_words(sink);
26 for argument in self.parameters.iter() {
27 argument.instruction.to_words(sink);
28 }
29 for (index, block) in self.blocks.iter().enumerate() {
30 Instruction::label(block.label_id).to_words(sink);
31 if index == 0 {
32 for local_var in self.variables.values() {
33 local_var.instruction.to_words(sink);
34 }
35 for internal_var in self.spilled_composites.values() {
36 internal_var.instruction.to_words(sink);
37 }
38 }
39 for instruction in block.body.iter() {
40 instruction.to_words(sink);
41 }
42 }
43 }
44}
45
46impl Writer {
47 pub fn new(options: &Options) -> Result<Self, Error> {
48 let (major, minor) = options.lang_version;
49 if major != 1 {
50 return Err(Error::UnsupportedVersion(major, minor));
51 }
52 let raw_version = ((major as u32) << 16) | ((minor as u32) << 8);
53
54 let mut capabilities_used = crate::FastIndexSet::default();
55 capabilities_used.insert(spirv::Capability::Shader);
56
57 let mut id_gen = IdGenerator::default();
58 let gl450_ext_inst_id = id_gen.next();
59 let void_type = id_gen.next();
60
61 Ok(Writer {
62 physical_layout: PhysicalLayout::new(raw_version),
63 logical_layout: LogicalLayout::default(),
64 id_gen,
65 capabilities_available: options.capabilities.clone(),
66 capabilities_used,
67 extensions_used: crate::FastIndexSet::default(),
68 debugs: vec![],
69 annotations: vec![],
70 flags: options.flags,
71 bounds_check_policies: options.bounds_check_policies,
72 zero_initialize_workgroup_memory: options.zero_initialize_workgroup_memory,
73 void_type,
74 lookup_type: crate::FastHashMap::default(),
75 lookup_function: crate::FastHashMap::default(),
76 lookup_function_type: crate::FastHashMap::default(),
77 constant_ids: HandleVec::new(),
78 cached_constants: crate::FastHashMap::default(),
79 global_variables: HandleVec::new(),
80 binding_map: options.binding_map.clone(),
81 saved_cached: CachedExpressions::default(),
82 gl450_ext_inst_id,
83 temp_list: Vec::new(),
84 })
85 }
86
87 fn reset(&mut self) {
97 use super::recyclable::Recyclable;
98 use std::mem::take;
99
100 let mut id_gen = IdGenerator::default();
101 let gl450_ext_inst_id = id_gen.next();
102 let void_type = id_gen.next();
103
104 let fresh = Writer {
107 flags: self.flags,
109 bounds_check_policies: self.bounds_check_policies,
110 zero_initialize_workgroup_memory: self.zero_initialize_workgroup_memory,
111 capabilities_available: take(&mut self.capabilities_available),
112 binding_map: take(&mut self.binding_map),
113
114 id_gen,
116 void_type,
117 gl450_ext_inst_id,
118
119 capabilities_used: take(&mut self.capabilities_used).recycle(),
121 extensions_used: take(&mut self.extensions_used).recycle(),
122 physical_layout: self.physical_layout.clone().recycle(),
123 logical_layout: take(&mut self.logical_layout).recycle(),
124 debugs: take(&mut self.debugs).recycle(),
125 annotations: take(&mut self.annotations).recycle(),
126 lookup_type: take(&mut self.lookup_type).recycle(),
127 lookup_function: take(&mut self.lookup_function).recycle(),
128 lookup_function_type: take(&mut self.lookup_function_type).recycle(),
129 constant_ids: take(&mut self.constant_ids).recycle(),
130 cached_constants: take(&mut self.cached_constants).recycle(),
131 global_variables: take(&mut self.global_variables).recycle(),
132 saved_cached: take(&mut self.saved_cached).recycle(),
133 temp_list: take(&mut self.temp_list).recycle(),
134 };
135
136 *self = fresh;
137
138 self.capabilities_used.insert(spirv::Capability::Shader);
139 }
140
141 pub(super) fn require_any(
156 &mut self,
157 what: &'static str,
158 capabilities: &[spirv::Capability],
159 ) -> Result<(), Error> {
160 match *capabilities {
161 [] => Ok(()),
162 [first, ..] => {
163 let selected = match self.capabilities_available {
166 None => first,
167 Some(ref available) => {
168 match capabilities.iter().find(|cap| available.contains(cap)) {
169 Some(&cap) => cap,
170 None => {
171 return Err(Error::MissingCapabilities(what, capabilities.to_vec()))
172 }
173 }
174 }
175 };
176 self.capabilities_used.insert(selected);
177 Ok(())
178 }
179 }
180 }
181
182 pub(super) fn use_extension(&mut self, extension: &'static str) {
184 self.extensions_used.insert(extension);
185 }
186
187 pub(super) fn get_type_id(&mut self, lookup_ty: LookupType) -> Word {
188 match self.lookup_type.entry(lookup_ty) {
189 Entry::Occupied(e) => *e.get(),
190 Entry::Vacant(e) => {
191 let local = match lookup_ty {
192 LookupType::Handle(_handle) => unreachable!("Handles are populated at start"),
193 LookupType::Local(local) => local,
194 };
195
196 let id = self.id_gen.next();
197 e.insert(id);
198 self.write_type_declaration_local(id, local);
199 id
200 }
201 }
202 }
203
204 pub(super) fn get_expression_lookup_type(&mut self, tr: &TypeResolution) -> LookupType {
205 match *tr {
206 TypeResolution::Handle(ty_handle) => LookupType::Handle(ty_handle),
207 TypeResolution::Value(ref inner) => {
208 LookupType::Local(LocalType::from_inner(inner).unwrap())
209 }
210 }
211 }
212
213 pub(super) fn get_expression_type_id(&mut self, tr: &TypeResolution) -> Word {
214 let lookup_ty = self.get_expression_lookup_type(tr);
215 self.get_type_id(lookup_ty)
216 }
217
218 pub(super) fn get_pointer_id(
219 &mut self,
220 handle: Handle<crate::Type>,
221 class: spirv::StorageClass,
222 ) -> Word {
223 self.get_type_id(LookupType::Local(LocalType::Pointer {
224 base: handle,
225 class,
226 }))
227 }
228
229 pub(super) fn get_resolution_pointer_id(
234 &mut self,
235 resolution: &TypeResolution,
236 class: spirv::StorageClass,
237 ) -> Word {
238 match *resolution {
239 TypeResolution::Handle(handle) => self.get_pointer_id(handle, class),
240 TypeResolution::Value(ref inner) => {
241 let base = NumericType::from_inner(inner).unwrap();
242 self.get_type_id(LookupType::Local(LocalType::LocalPointer { base, class }))
243 }
244 }
245 }
246
247 pub(super) fn get_uint_type_id(&mut self) -> Word {
248 let local_type = LocalType::Numeric(NumericType::Scalar(crate::Scalar::U32));
249 self.get_type_id(local_type.into())
250 }
251
252 pub(super) fn get_float_type_id(&mut self) -> Word {
253 let local_type = LocalType::Numeric(NumericType::Scalar(crate::Scalar::F32));
254 self.get_type_id(local_type.into())
255 }
256
257 pub(super) fn get_uint3_type_id(&mut self) -> Word {
258 let local_type = LocalType::Numeric(NumericType::Vector {
259 size: crate::VectorSize::Tri,
260 scalar: crate::Scalar::U32,
261 });
262 self.get_type_id(local_type.into())
263 }
264
265 pub(super) fn get_float_pointer_type_id(&mut self, class: spirv::StorageClass) -> Word {
266 let local_type = LocalType::LocalPointer {
267 base: NumericType::Scalar(crate::Scalar::F32),
268 class,
269 };
270 self.get_type_id(local_type.into())
271 }
272
273 pub(super) fn get_uint3_pointer_type_id(&mut self, class: spirv::StorageClass) -> Word {
274 let local_type = LocalType::LocalPointer {
275 base: NumericType::Vector {
276 size: crate::VectorSize::Tri,
277 scalar: crate::Scalar::U32,
278 },
279 class,
280 };
281 self.get_type_id(local_type.into())
282 }
283
284 pub(super) fn get_bool_type_id(&mut self) -> Word {
285 let local_type = LocalType::Numeric(NumericType::Scalar(crate::Scalar::BOOL));
286 self.get_type_id(local_type.into())
287 }
288
289 pub(super) fn get_bool3_type_id(&mut self) -> Word {
290 let local_type = LocalType::Numeric(NumericType::Vector {
291 size: crate::VectorSize::Tri,
292 scalar: crate::Scalar::BOOL,
293 });
294 self.get_type_id(local_type.into())
295 }
296
297 pub(super) fn decorate(&mut self, id: Word, decoration: spirv::Decoration, operands: &[Word]) {
298 self.annotations
299 .push(Instruction::decorate(id, decoration, operands));
300 }
301
302 fn write_function(
303 &mut self,
304 ir_function: &crate::Function,
305 info: &FunctionInfo,
306 ir_module: &crate::Module,
307 mut interface: Option<FunctionInterface>,
308 debug_info: &Option<DebugInfoInner>,
309 ) -> Result<Word, Error> {
310 log::trace!("Generating code for {:?}", ir_function.name);
311 let mut function = Function::default();
312
313 let prelude_id = self.id_gen.next();
314 let mut prelude = Block::new(prelude_id);
315 let mut ep_context = EntryPointContext {
316 argument_ids: Vec::new(),
317 results: Vec::new(),
318 };
319
320 let mut local_invocation_id = None;
321
322 let mut parameter_type_ids = Vec::with_capacity(ir_function.arguments.len());
323 for argument in ir_function.arguments.iter() {
324 let class = spirv::StorageClass::Input;
325 let handle_ty = ir_module.types[argument.ty].inner.is_handle();
326 let argument_type_id = match handle_ty {
327 true => self.get_pointer_id(argument.ty, spirv::StorageClass::UniformConstant),
328 false => self.get_type_id(LookupType::Handle(argument.ty)),
329 };
330
331 if let Some(ref mut iface) = interface {
332 let id = if let Some(ref binding) = argument.binding {
333 let name = argument.name.as_deref();
334
335 let varying_id = self.write_varying(
336 ir_module,
337 iface.stage,
338 class,
339 name,
340 argument.ty,
341 binding,
342 )?;
343 iface.varying_ids.push(varying_id);
344 let id = self.id_gen.next();
345 prelude
346 .body
347 .push(Instruction::load(argument_type_id, id, varying_id, None));
348
349 if binding == &crate::Binding::BuiltIn(crate::BuiltIn::LocalInvocationId) {
350 local_invocation_id = Some(id);
351 }
352
353 id
354 } else if let crate::TypeInner::Struct { ref members, .. } =
355 ir_module.types[argument.ty].inner
356 {
357 let struct_id = self.id_gen.next();
358 let mut constituent_ids = Vec::with_capacity(members.len());
359 for member in members {
360 let type_id = self.get_type_id(LookupType::Handle(member.ty));
361 let name = member.name.as_deref();
362 let binding = member.binding.as_ref().unwrap();
363 let varying_id = self.write_varying(
364 ir_module,
365 iface.stage,
366 class,
367 name,
368 member.ty,
369 binding,
370 )?;
371 iface.varying_ids.push(varying_id);
372 let id = self.id_gen.next();
373 prelude
374 .body
375 .push(Instruction::load(type_id, id, varying_id, None));
376 constituent_ids.push(id);
377
378 if binding == &crate::Binding::BuiltIn(crate::BuiltIn::GlobalInvocationId) {
379 local_invocation_id = Some(id);
380 }
381 }
382 prelude.body.push(Instruction::composite_construct(
383 argument_type_id,
384 struct_id,
385 &constituent_ids,
386 ));
387 struct_id
388 } else {
389 unreachable!("Missing argument binding on an entry point");
390 };
391 ep_context.argument_ids.push(id);
392 } else {
393 let argument_id = self.id_gen.next();
394 let instruction = Instruction::function_parameter(argument_type_id, argument_id);
395 if self.flags.contains(WriterFlags::DEBUG) {
396 if let Some(ref name) = argument.name {
397 self.debugs.push(Instruction::name(argument_id, name));
398 }
399 }
400 function.parameters.push(FunctionArgument {
401 instruction,
402 handle_id: if handle_ty {
403 let id = self.id_gen.next();
404 prelude.body.push(Instruction::load(
405 self.get_type_id(LookupType::Handle(argument.ty)),
406 id,
407 argument_id,
408 None,
409 ));
410 id
411 } else {
412 0
413 },
414 });
415 parameter_type_ids.push(argument_type_id);
416 };
417 }
418
419 let return_type_id = match ir_function.result {
420 Some(ref result) => {
421 if let Some(ref mut iface) = interface {
422 let mut has_point_size = false;
423 let class = spirv::StorageClass::Output;
424 if let Some(ref binding) = result.binding {
425 has_point_size |=
426 *binding == crate::Binding::BuiltIn(crate::BuiltIn::PointSize);
427 let type_id = self.get_type_id(LookupType::Handle(result.ty));
428 let varying_id = self.write_varying(
429 ir_module,
430 iface.stage,
431 class,
432 None,
433 result.ty,
434 binding,
435 )?;
436 iface.varying_ids.push(varying_id);
437 ep_context.results.push(ResultMember {
438 id: varying_id,
439 type_id,
440 built_in: binding.to_built_in(),
441 });
442 } else if let crate::TypeInner::Struct { ref members, .. } =
443 ir_module.types[result.ty].inner
444 {
445 for member in members {
446 let type_id = self.get_type_id(LookupType::Handle(member.ty));
447 let name = member.name.as_deref();
448 let binding = member.binding.as_ref().unwrap();
449 has_point_size |=
450 *binding == crate::Binding::BuiltIn(crate::BuiltIn::PointSize);
451 let varying_id = self.write_varying(
452 ir_module,
453 iface.stage,
454 class,
455 name,
456 member.ty,
457 binding,
458 )?;
459 iface.varying_ids.push(varying_id);
460 ep_context.results.push(ResultMember {
461 id: varying_id,
462 type_id,
463 built_in: binding.to_built_in(),
464 });
465 }
466 } else {
467 unreachable!("Missing result binding on an entry point");
468 }
469
470 if self.flags.contains(WriterFlags::FORCE_POINT_SIZE)
471 && iface.stage == crate::ShaderStage::Vertex
472 && !has_point_size
473 {
474 let varying_id = self.id_gen.next();
476 let pointer_type_id = self.get_float_pointer_type_id(class);
477 Instruction::variable(pointer_type_id, varying_id, class, None)
478 .to_words(&mut self.logical_layout.declarations);
479 self.decorate(
480 varying_id,
481 spirv::Decoration::BuiltIn,
482 &[spirv::BuiltIn::PointSize as u32],
483 );
484 iface.varying_ids.push(varying_id);
485
486 let default_value_id = self.get_constant_scalar(crate::Literal::F32(1.0));
487 prelude
488 .body
489 .push(Instruction::store(varying_id, default_value_id, None));
490 }
491 self.void_type
492 } else {
493 self.get_type_id(LookupType::Handle(result.ty))
494 }
495 }
496 None => self.void_type,
497 };
498
499 let lookup_function_type = LookupFunctionType {
500 parameter_type_ids,
501 return_type_id,
502 };
503
504 let function_id = self.id_gen.next();
505 if self.flags.contains(WriterFlags::DEBUG) {
506 if let Some(ref name) = ir_function.name {
507 self.debugs.push(Instruction::name(function_id, name));
508 }
509 }
510
511 let function_type = self.get_function_type(lookup_function_type);
512 function.signature = Some(Instruction::function(
513 return_type_id,
514 function_id,
515 spirv::FunctionControl::empty(),
516 function_type,
517 ));
518
519 if interface.is_some() {
520 function.entry_point_context = Some(ep_context);
521 }
522
523 for gv in self.global_variables.iter_mut() {
525 gv.reset_for_function();
526 }
527 for (handle, var) in ir_module.global_variables.iter() {
528 if info[handle].is_empty() {
529 continue;
530 }
531
532 let mut gv = self.global_variables[handle].clone();
533 if let Some(ref mut iface) = interface {
534 if self.physical_layout.version >= 0x10400 {
536 iface.varying_ids.push(gv.var_id);
537 }
538 }
539
540 match ir_module.types[var.ty].inner {
544 crate::TypeInner::BindingArray { .. } => {
545 gv.access_id = gv.var_id;
546 }
547 _ => {
548 if var.space == crate::AddressSpace::Handle {
549 let var_type_id = self.get_type_id(LookupType::Handle(var.ty));
550 let id = self.id_gen.next();
551 prelude
552 .body
553 .push(Instruction::load(var_type_id, id, gv.var_id, None));
554 gv.access_id = gv.var_id;
555 gv.handle_id = id;
556 } else if global_needs_wrapper(ir_module, var) {
557 let class = map_storage_class(var.space);
558 let pointer_type_id = self.get_pointer_id(var.ty, class);
559 let index_id = self.get_index_constant(0);
560 let id = self.id_gen.next();
561 prelude.body.push(Instruction::access_chain(
562 pointer_type_id,
563 id,
564 gv.var_id,
565 &[index_id],
566 ));
567 gv.access_id = id;
568 } else {
569 gv.access_id = gv.var_id;
571 };
572 }
573 }
574
575 self.global_variables[handle] = gv;
577 }
578
579 let mut context = BlockContext {
582 ir_module,
583 ir_function,
584 fun_info: info,
585 function: &mut function,
586 cached: std::mem::take(&mut self.saved_cached),
588
589 temp_list: std::mem::take(&mut self.temp_list),
591 writer: self,
592 expression_constness: super::ExpressionConstnessTracker::from_arena(
593 &ir_function.expressions,
594 ),
595 };
596
597 context.cached.reset(ir_function.expressions.len());
599 for (handle, expr) in ir_function.expressions.iter() {
600 if (expr.needs_pre_emit() && !matches!(*expr, crate::Expression::LocalVariable(_)))
601 || context.expression_constness.is_const(handle)
602 {
603 context.cache_expression_value(handle, &mut prelude)?;
604 }
605 }
606
607 for (handle, variable) in ir_function.local_variables.iter() {
608 let id = context.gen_id();
609
610 if context.writer.flags.contains(WriterFlags::DEBUG) {
611 if let Some(ref name) = variable.name {
612 context.writer.debugs.push(Instruction::name(id, name));
613 }
614 }
615
616 let init_word = variable.init.map(|constant| context.cached[constant]);
617 let pointer_type_id = context
618 .writer
619 .get_pointer_id(variable.ty, spirv::StorageClass::Function);
620 let instruction = Instruction::variable(
621 pointer_type_id,
622 id,
623 spirv::StorageClass::Function,
624 init_word.or_else(|| match ir_module.types[variable.ty].inner {
625 crate::TypeInner::RayQuery => None,
626 _ => {
627 let type_id = context.get_type_id(LookupType::Handle(variable.ty));
628 Some(context.writer.write_constant_null(type_id))
629 }
630 }),
631 );
632 context
633 .function
634 .variables
635 .insert(handle, LocalVariable { id, instruction });
636 }
637
638 for (handle, expr) in ir_function.expressions.iter() {
639 match *expr {
640 crate::Expression::LocalVariable(_) => {
641 context.cache_expression_value(handle, &mut prelude)?;
644 }
645 crate::Expression::Access { base, .. }
646 | crate::Expression::AccessIndex { base, .. } => {
647 *context.function.access_uses.entry(base).or_insert(0) += 1;
650 }
651 _ => {}
652 }
653 }
654
655 let next_id = context.gen_id();
656
657 context
658 .function
659 .consume(prelude, Instruction::branch(next_id));
660
661 let workgroup_vars_init_exit_block_id =
662 match (context.writer.zero_initialize_workgroup_memory, interface) {
663 (
664 super::ZeroInitializeWorkgroupMemoryMode::Polyfill,
665 Some(
666 ref mut interface @ FunctionInterface {
667 stage: crate::ShaderStage::Compute,
668 ..
669 },
670 ),
671 ) => context.writer.generate_workgroup_vars_init_block(
672 next_id,
673 ir_module,
674 info,
675 local_invocation_id,
676 interface,
677 context.function,
678 ),
679 _ => None,
680 };
681
682 let main_id = if let Some(exit_id) = workgroup_vars_init_exit_block_id {
683 exit_id
684 } else {
685 next_id
686 };
687
688 context.write_function_body(main_id, debug_info.as_ref())?;
689
690 let BlockContext {
693 cached, temp_list, ..
694 } = context;
695 self.saved_cached = cached;
696 self.temp_list = temp_list;
697
698 function.to_words(&mut self.logical_layout.function_definitions);
699 Instruction::function_end().to_words(&mut self.logical_layout.function_definitions);
700
701 Ok(function_id)
702 }
703
704 fn write_execution_mode(
705 &mut self,
706 function_id: Word,
707 mode: spirv::ExecutionMode,
708 ) -> Result<(), Error> {
709 Instruction::execution_mode(function_id, mode, &[])
711 .to_words(&mut self.logical_layout.execution_modes);
712 Ok(())
713 }
714
715 fn write_entry_point(
717 &mut self,
718 entry_point: &crate::EntryPoint,
719 info: &FunctionInfo,
720 ir_module: &crate::Module,
721 debug_info: &Option<DebugInfoInner>,
722 ) -> Result<Instruction, Error> {
723 let mut interface_ids = Vec::new();
724 let function_id = self.write_function(
725 &entry_point.function,
726 info,
727 ir_module,
728 Some(FunctionInterface {
729 varying_ids: &mut interface_ids,
730 stage: entry_point.stage,
731 }),
732 debug_info,
733 )?;
734
735 let exec_model = match entry_point.stage {
736 crate::ShaderStage::Vertex => spirv::ExecutionModel::Vertex,
737 crate::ShaderStage::Fragment => {
738 self.write_execution_mode(function_id, spirv::ExecutionMode::OriginUpperLeft)?;
739 if let Some(ref result) = entry_point.function.result {
740 if contains_builtin(
741 result.binding.as_ref(),
742 result.ty,
743 &ir_module.types,
744 crate::BuiltIn::FragDepth,
745 ) {
746 self.write_execution_mode(
747 function_id,
748 spirv::ExecutionMode::DepthReplacing,
749 )?;
750 }
751 }
752 spirv::ExecutionModel::Fragment
753 }
754 crate::ShaderStage::Compute => {
755 let execution_mode = spirv::ExecutionMode::LocalSize;
756 Instruction::execution_mode(
758 function_id,
759 execution_mode,
760 &entry_point.workgroup_size,
761 )
762 .to_words(&mut self.logical_layout.execution_modes);
763 spirv::ExecutionModel::GLCompute
764 }
765 };
766 Ok(Instruction::entry_point(
769 exec_model,
770 function_id,
771 &entry_point.name,
772 interface_ids.as_slice(),
773 ))
774 }
775
776 fn make_scalar(&mut self, id: Word, scalar: crate::Scalar) -> Instruction {
777 use crate::ScalarKind as Sk;
778
779 let bits = (scalar.width * BITS_PER_BYTE) as u32;
780 match scalar.kind {
781 Sk::Sint | Sk::Uint => {
782 let signedness = if scalar.kind == Sk::Sint {
783 super::instructions::Signedness::Signed
784 } else {
785 super::instructions::Signedness::Unsigned
786 };
787 let cap = match bits {
788 8 => Some(spirv::Capability::Int8),
789 16 => Some(spirv::Capability::Int16),
790 64 => Some(spirv::Capability::Int64),
791 _ => None,
792 };
793 if let Some(cap) = cap {
794 self.capabilities_used.insert(cap);
795 }
796 Instruction::type_int(id, bits, signedness)
797 }
798 Sk::Float => {
799 if bits == 64 {
800 self.capabilities_used.insert(spirv::Capability::Float64);
801 }
802 Instruction::type_float(id, bits)
803 }
804 Sk::Bool => Instruction::type_bool(id),
805 Sk::AbstractInt | Sk::AbstractFloat => {
806 unreachable!("abstract types should never reach the backend");
807 }
808 }
809 }
810
811 fn request_type_capabilities(&mut self, inner: &crate::TypeInner) -> Result<(), Error> {
812 match *inner {
813 crate::TypeInner::Image {
814 dim,
815 arrayed,
816 class,
817 } => {
818 let sampled = match class {
819 crate::ImageClass::Sampled { .. } => true,
820 crate::ImageClass::Depth { .. } => true,
821 crate::ImageClass::Storage { format, .. } => {
822 self.request_image_format_capabilities(format.into())?;
823 false
824 }
825 };
826
827 match dim {
828 crate::ImageDimension::D1 => {
829 if sampled {
830 self.require_any("sampled 1D images", &[spirv::Capability::Sampled1D])?;
831 } else {
832 self.require_any("1D storage images", &[spirv::Capability::Image1D])?;
833 }
834 }
835 crate::ImageDimension::Cube if arrayed => {
836 if sampled {
837 self.require_any(
838 "sampled cube array images",
839 &[spirv::Capability::SampledCubeArray],
840 )?;
841 } else {
842 self.require_any(
843 "cube array storage images",
844 &[spirv::Capability::ImageCubeArray],
845 )?;
846 }
847 }
848 _ => {}
849 }
850 }
851 crate::TypeInner::AccelerationStructure => {
852 self.require_any("Acceleration Structure", &[spirv::Capability::RayQueryKHR])?;
853 }
854 crate::TypeInner::RayQuery => {
855 self.require_any("Ray Query", &[spirv::Capability::RayQueryKHR])?;
856 }
857 crate::TypeInner::Atomic(crate::Scalar { width: 8, kind: _ }) => {
858 self.require_any("64 bit integer atomics", &[spirv::Capability::Int64Atomics])?;
859 }
860 _ => {}
861 }
862 Ok(())
863 }
864
865 fn write_numeric_type_declaration_local(&mut self, id: Word, numeric: NumericType) {
866 let instruction =
867 match numeric {
868 NumericType::Scalar(scalar) => self.make_scalar(id, scalar),
869 NumericType::Vector { size, scalar } => {
870 let scalar_id = self.get_type_id(LookupType::Local(LocalType::Numeric(
871 NumericType::Scalar(scalar),
872 )));
873 Instruction::type_vector(id, scalar_id, size)
874 }
875 NumericType::Matrix {
876 columns,
877 rows,
878 scalar,
879 } => {
880 let column_id = self.get_type_id(LookupType::Local(LocalType::Numeric(
881 NumericType::Vector { size: rows, scalar },
882 )));
883 Instruction::type_matrix(id, column_id, columns)
884 }
885 };
886
887 instruction.to_words(&mut self.logical_layout.declarations);
888 }
889
890 fn write_type_declaration_local(&mut self, id: Word, local_ty: LocalType) {
891 let instruction = match local_ty {
892 LocalType::Numeric(numeric) => {
893 self.write_numeric_type_declaration_local(id, numeric);
894 return;
895 }
896 LocalType::LocalPointer { base, class } => {
897 let base_id = self.get_type_id(LookupType::Local(LocalType::Numeric(base)));
898 Instruction::type_pointer(id, class, base_id)
899 }
900 LocalType::Pointer { base, class } => {
901 let type_id = self.get_type_id(LookupType::Handle(base));
902 Instruction::type_pointer(id, class, type_id)
903 }
904 LocalType::Image(image) => {
905 let local_type = LocalType::Numeric(NumericType::Scalar(image.sampled_type));
906 let type_id = self.get_type_id(LookupType::Local(local_type));
907 Instruction::type_image(id, type_id, image.dim, image.flags, image.image_format)
908 }
909 LocalType::Sampler => Instruction::type_sampler(id),
910 LocalType::SampledImage { image_type_id } => {
911 Instruction::type_sampled_image(id, image_type_id)
912 }
913 LocalType::BindingArray { base, size } => {
914 let inner_ty = self.get_type_id(LookupType::Handle(base));
915 let scalar_id = self.get_constant_scalar(crate::Literal::U32(size));
916 Instruction::type_array(id, inner_ty, scalar_id)
917 }
918 LocalType::PointerToBindingArray { base, size, space } => {
919 let inner_ty =
920 self.get_type_id(LookupType::Local(LocalType::BindingArray { base, size }));
921 let class = map_storage_class(space);
922 Instruction::type_pointer(id, class, inner_ty)
923 }
924 LocalType::AccelerationStructure => Instruction::type_acceleration_structure(id),
925 LocalType::RayQuery => Instruction::type_ray_query(id),
926 };
927
928 instruction.to_words(&mut self.logical_layout.declarations);
929 }
930
931 fn write_type_declaration_arena(
932 &mut self,
933 arena: &UniqueArena<crate::Type>,
934 handle: Handle<crate::Type>,
935 ) -> Result<Word, Error> {
936 let ty = &arena[handle];
937 self.request_type_capabilities(&ty.inner)?;
942 let id = if let Some(local) = LocalType::from_inner(&ty.inner) {
943 match self.lookup_type.entry(LookupType::Local(local)) {
947 Entry::Occupied(e) => *e.get(),
949
950 Entry::Vacant(e) => {
952 let id = self.id_gen.next();
953 e.insert(id);
954
955 self.write_type_declaration_local(id, local);
956
957 id
958 }
959 }
960 } else {
961 use spirv::Decoration;
962
963 let id = self.id_gen.next();
964 let instruction = match ty.inner {
965 crate::TypeInner::Array { base, size, stride } => {
966 self.decorate(id, Decoration::ArrayStride, &[stride]);
967
968 let type_id = self.get_type_id(LookupType::Handle(base));
969 match size {
970 crate::ArraySize::Constant(length) => {
971 let length_id = self.get_index_constant(length.get());
972 Instruction::type_array(id, type_id, length_id)
973 }
974 crate::ArraySize::Dynamic => Instruction::type_runtime_array(id, type_id),
975 }
976 }
977 crate::TypeInner::BindingArray { base, size } => {
978 let type_id = self.get_type_id(LookupType::Handle(base));
979 match size {
980 crate::ArraySize::Constant(length) => {
981 let length_id = self.get_index_constant(length.get());
982 Instruction::type_array(id, type_id, length_id)
983 }
984 crate::ArraySize::Dynamic => Instruction::type_runtime_array(id, type_id),
985 }
986 }
987 crate::TypeInner::Struct {
988 ref members,
989 span: _,
990 } => {
991 let mut has_runtime_array = false;
992 let mut member_ids = Vec::with_capacity(members.len());
993 for (index, member) in members.iter().enumerate() {
994 let member_ty = &arena[member.ty];
995 match member_ty.inner {
996 crate::TypeInner::Array {
997 base: _,
998 size: crate::ArraySize::Dynamic,
999 stride: _,
1000 } => {
1001 has_runtime_array = true;
1002 }
1003 _ => (),
1004 }
1005 self.decorate_struct_member(id, index, member, arena)?;
1006 let member_id = self.get_type_id(LookupType::Handle(member.ty));
1007 member_ids.push(member_id);
1008 }
1009 if has_runtime_array {
1010 self.decorate(id, Decoration::Block, &[]);
1011 }
1012 Instruction::type_struct(id, member_ids.as_slice())
1013 }
1014
1015 crate::TypeInner::Scalar(_)
1018 | crate::TypeInner::Atomic(_)
1019 | crate::TypeInner::Vector { .. }
1020 | crate::TypeInner::Matrix { .. }
1021 | crate::TypeInner::Pointer { .. }
1022 | crate::TypeInner::ValuePointer { .. }
1023 | crate::TypeInner::Image { .. }
1024 | crate::TypeInner::Sampler { .. }
1025 | crate::TypeInner::AccelerationStructure
1026 | crate::TypeInner::RayQuery => unreachable!(),
1027 };
1028
1029 instruction.to_words(&mut self.logical_layout.declarations);
1030 id
1031 };
1032
1033 self.lookup_type.insert(LookupType::Handle(handle), id);
1035
1036 if self.flags.contains(WriterFlags::DEBUG) {
1037 if let Some(ref name) = ty.name {
1038 self.debugs.push(Instruction::name(id, name));
1039 }
1040 }
1041
1042 Ok(id)
1043 }
1044
1045 fn request_image_format_capabilities(
1046 &mut self,
1047 format: spirv::ImageFormat,
1048 ) -> Result<(), Error> {
1049 use spirv::ImageFormat as If;
1050 match format {
1051 If::Rg32f
1052 | If::Rg16f
1053 | If::R11fG11fB10f
1054 | If::R16f
1055 | If::Rgba16
1056 | If::Rgb10A2
1057 | If::Rg16
1058 | If::Rg8
1059 | If::R16
1060 | If::R8
1061 | If::Rgba16Snorm
1062 | If::Rg16Snorm
1063 | If::Rg8Snorm
1064 | If::R16Snorm
1065 | If::R8Snorm
1066 | If::Rg32i
1067 | If::Rg16i
1068 | If::Rg8i
1069 | If::R16i
1070 | If::R8i
1071 | If::Rgb10a2ui
1072 | If::Rg32ui
1073 | If::Rg16ui
1074 | If::Rg8ui
1075 | If::R16ui
1076 | If::R8ui => self.require_any(
1077 "storage image format",
1078 &[spirv::Capability::StorageImageExtendedFormats],
1079 ),
1080 If::R64ui | If::R64i => self.require_any(
1081 "64-bit integer storage image format",
1082 &[spirv::Capability::Int64ImageEXT],
1083 ),
1084 If::Unknown
1085 | If::Rgba32f
1086 | If::Rgba16f
1087 | If::R32f
1088 | If::Rgba8
1089 | If::Rgba8Snorm
1090 | If::Rgba32i
1091 | If::Rgba16i
1092 | If::Rgba8i
1093 | If::R32i
1094 | If::Rgba32ui
1095 | If::Rgba16ui
1096 | If::Rgba8ui
1097 | If::R32ui => Ok(()),
1098 }
1099 }
1100
1101 pub(super) fn get_index_constant(&mut self, index: Word) -> Word {
1102 self.get_constant_scalar(crate::Literal::U32(index))
1103 }
1104
1105 pub(super) fn get_constant_scalar_with(
1106 &mut self,
1107 value: u8,
1108 scalar: crate::Scalar,
1109 ) -> Result<Word, Error> {
1110 Ok(
1111 self.get_constant_scalar(crate::Literal::new(value, scalar).ok_or(
1112 Error::Validation("Unexpected kind and/or width for Literal"),
1113 )?),
1114 )
1115 }
1116
1117 pub(super) fn get_constant_scalar(&mut self, value: crate::Literal) -> Word {
1118 let scalar = CachedConstant::Literal(value.into());
1119 if let Some(&id) = self.cached_constants.get(&scalar) {
1120 return id;
1121 }
1122 let id = self.id_gen.next();
1123 self.write_constant_scalar(id, &value, None);
1124 self.cached_constants.insert(scalar, id);
1125 id
1126 }
1127
1128 fn write_constant_scalar(
1129 &mut self,
1130 id: Word,
1131 value: &crate::Literal,
1132 debug_name: Option<&String>,
1133 ) {
1134 if self.flags.contains(WriterFlags::DEBUG) {
1135 if let Some(name) = debug_name {
1136 self.debugs.push(Instruction::name(id, name));
1137 }
1138 }
1139 let type_id = self.get_type_id(LookupType::Local(LocalType::Numeric(NumericType::Scalar(
1140 value.scalar(),
1141 ))));
1142 let instruction = match *value {
1143 crate::Literal::F64(value) => {
1144 let bits = value.to_bits();
1145 Instruction::constant_64bit(type_id, id, bits as u32, (bits >> 32) as u32)
1146 }
1147 crate::Literal::F32(value) => Instruction::constant_32bit(type_id, id, value.to_bits()),
1148 crate::Literal::U32(value) => Instruction::constant_32bit(type_id, id, value),
1149 crate::Literal::I32(value) => Instruction::constant_32bit(type_id, id, value as u32),
1150 crate::Literal::U64(value) => {
1151 Instruction::constant_64bit(type_id, id, value as u32, (value >> 32) as u32)
1152 }
1153 crate::Literal::I64(value) => {
1154 Instruction::constant_64bit(type_id, id, value as u32, (value >> 32) as u32)
1155 }
1156 crate::Literal::Bool(true) => Instruction::constant_true(type_id, id),
1157 crate::Literal::Bool(false) => Instruction::constant_false(type_id, id),
1158 crate::Literal::AbstractInt(_) | crate::Literal::AbstractFloat(_) => {
1159 unreachable!("Abstract types should not appear in IR presented to backends");
1160 }
1161 };
1162
1163 instruction.to_words(&mut self.logical_layout.declarations);
1164 }
1165
1166 pub(super) fn get_constant_composite(
1167 &mut self,
1168 ty: LookupType,
1169 constituent_ids: &[Word],
1170 ) -> Word {
1171 let composite = CachedConstant::Composite {
1172 ty,
1173 constituent_ids: constituent_ids.to_vec(),
1174 };
1175 if let Some(&id) = self.cached_constants.get(&composite) {
1176 return id;
1177 }
1178 let id = self.id_gen.next();
1179 self.write_constant_composite(id, ty, constituent_ids, None);
1180 self.cached_constants.insert(composite, id);
1181 id
1182 }
1183
1184 fn write_constant_composite(
1185 &mut self,
1186 id: Word,
1187 ty: LookupType,
1188 constituent_ids: &[Word],
1189 debug_name: Option<&String>,
1190 ) {
1191 if self.flags.contains(WriterFlags::DEBUG) {
1192 if let Some(name) = debug_name {
1193 self.debugs.push(Instruction::name(id, name));
1194 }
1195 }
1196 let type_id = self.get_type_id(ty);
1197 Instruction::constant_composite(type_id, id, constituent_ids)
1198 .to_words(&mut self.logical_layout.declarations);
1199 }
1200
1201 pub(super) fn get_constant_null(&mut self, type_id: Word) -> Word {
1202 let null = CachedConstant::ZeroValue(type_id);
1203 if let Some(&id) = self.cached_constants.get(&null) {
1204 return id;
1205 }
1206 let id = self.write_constant_null(type_id);
1207 self.cached_constants.insert(null, id);
1208 id
1209 }
1210
1211 pub(super) fn write_constant_null(&mut self, type_id: Word) -> Word {
1212 let null_id = self.id_gen.next();
1213 Instruction::constant_null(type_id, null_id)
1214 .to_words(&mut self.logical_layout.declarations);
1215 null_id
1216 }
1217
1218 fn write_constant_expr(
1219 &mut self,
1220 handle: Handle<crate::Expression>,
1221 ir_module: &crate::Module,
1222 mod_info: &ModuleInfo,
1223 ) -> Result<Word, Error> {
1224 let id = match ir_module.global_expressions[handle] {
1225 crate::Expression::Literal(literal) => self.get_constant_scalar(literal),
1226 crate::Expression::Constant(constant) => {
1227 let constant = &ir_module.constants[constant];
1228 self.constant_ids[constant.init]
1229 }
1230 crate::Expression::ZeroValue(ty) => {
1231 let type_id = self.get_type_id(LookupType::Handle(ty));
1232 self.get_constant_null(type_id)
1233 }
1234 crate::Expression::Compose { ty, ref components } => {
1235 let component_ids: Vec<_> = crate::proc::flatten_compose(
1236 ty,
1237 components,
1238 &ir_module.global_expressions,
1239 &ir_module.types,
1240 )
1241 .map(|component| self.constant_ids[component])
1242 .collect();
1243 self.get_constant_composite(LookupType::Handle(ty), component_ids.as_slice())
1244 }
1245 crate::Expression::Splat { size, value } => {
1246 let value_id = self.constant_ids[value];
1247 let component_ids = &[value_id; 4][..size as usize];
1248
1249 let ty = self.get_expression_lookup_type(&mod_info[handle]);
1250
1251 self.get_constant_composite(ty, component_ids)
1252 }
1253 _ => unreachable!(),
1254 };
1255
1256 self.constant_ids[handle] = id;
1257
1258 Ok(id)
1259 }
1260
1261 pub(super) fn write_barrier(&mut self, flags: crate::Barrier, block: &mut Block) {
1262 let memory_scope = if flags.contains(crate::Barrier::STORAGE) {
1263 spirv::Scope::Device
1264 } else {
1265 spirv::Scope::Workgroup
1266 };
1267 let mut semantics = spirv::MemorySemantics::ACQUIRE_RELEASE;
1268 semantics.set(
1269 spirv::MemorySemantics::UNIFORM_MEMORY,
1270 flags.contains(crate::Barrier::STORAGE),
1271 );
1272 semantics.set(
1273 spirv::MemorySemantics::WORKGROUP_MEMORY,
1274 flags.contains(crate::Barrier::WORK_GROUP),
1275 );
1276 let exec_scope_id = if flags.contains(crate::Barrier::SUB_GROUP) {
1277 self.get_index_constant(spirv::Scope::Subgroup as u32)
1278 } else {
1279 self.get_index_constant(spirv::Scope::Workgroup as u32)
1280 };
1281 let mem_scope_id = self.get_index_constant(memory_scope as u32);
1282 let semantics_id = self.get_index_constant(semantics.bits());
1283 block.body.push(Instruction::control_barrier(
1284 exec_scope_id,
1285 mem_scope_id,
1286 semantics_id,
1287 ));
1288 }
1289
1290 fn generate_workgroup_vars_init_block(
1291 &mut self,
1292 entry_id: Word,
1293 ir_module: &crate::Module,
1294 info: &FunctionInfo,
1295 local_invocation_id: Option<Word>,
1296 interface: &mut FunctionInterface,
1297 function: &mut Function,
1298 ) -> Option<Word> {
1299 let body = ir_module
1300 .global_variables
1301 .iter()
1302 .filter(|&(handle, var)| {
1303 !info[handle].is_empty() && var.space == crate::AddressSpace::WorkGroup
1304 })
1305 .map(|(handle, var)| {
1306 let var_id = self.global_variables[handle].var_id;
1310 let var_type_id = self.get_type_id(LookupType::Handle(var.ty));
1311 let init_word = self.get_constant_null(var_type_id);
1312 Instruction::store(var_id, init_word, None)
1313 })
1314 .collect::<Vec<_>>();
1315
1316 if body.is_empty() {
1317 return None;
1318 }
1319
1320 let uint3_type_id = self.get_uint3_type_id();
1321
1322 let mut pre_if_block = Block::new(entry_id);
1323
1324 let local_invocation_id = if let Some(local_invocation_id) = local_invocation_id {
1325 local_invocation_id
1326 } else {
1327 let varying_id = self.id_gen.next();
1328 let class = spirv::StorageClass::Input;
1329 let pointer_type_id = self.get_uint3_pointer_type_id(class);
1330
1331 Instruction::variable(pointer_type_id, varying_id, class, None)
1332 .to_words(&mut self.logical_layout.declarations);
1333
1334 self.decorate(
1335 varying_id,
1336 spirv::Decoration::BuiltIn,
1337 &[spirv::BuiltIn::LocalInvocationId as u32],
1338 );
1339
1340 interface.varying_ids.push(varying_id);
1341 let id = self.id_gen.next();
1342 pre_if_block
1343 .body
1344 .push(Instruction::load(uint3_type_id, id, varying_id, None));
1345
1346 id
1347 };
1348
1349 let zero_id = self.get_constant_null(uint3_type_id);
1350 let bool3_type_id = self.get_bool3_type_id();
1351
1352 let eq_id = self.id_gen.next();
1353 pre_if_block.body.push(Instruction::binary(
1354 spirv::Op::IEqual,
1355 bool3_type_id,
1356 eq_id,
1357 local_invocation_id,
1358 zero_id,
1359 ));
1360
1361 let condition_id = self.id_gen.next();
1362 let bool_type_id = self.get_bool_type_id();
1363 pre_if_block.body.push(Instruction::relational(
1364 spirv::Op::All,
1365 bool_type_id,
1366 condition_id,
1367 eq_id,
1368 ));
1369
1370 let merge_id = self.id_gen.next();
1371 pre_if_block.body.push(Instruction::selection_merge(
1372 merge_id,
1373 spirv::SelectionControl::NONE,
1374 ));
1375
1376 let accept_id = self.id_gen.next();
1377 function.consume(
1378 pre_if_block,
1379 Instruction::branch_conditional(condition_id, accept_id, merge_id),
1380 );
1381
1382 let accept_block = Block {
1383 label_id: accept_id,
1384 body,
1385 };
1386 function.consume(accept_block, Instruction::branch(merge_id));
1387
1388 let mut post_if_block = Block::new(merge_id);
1389
1390 self.write_barrier(crate::Barrier::WORK_GROUP, &mut post_if_block);
1391
1392 let next_id = self.id_gen.next();
1393 function.consume(post_if_block, Instruction::branch(next_id));
1394 Some(next_id)
1395 }
1396
1397 fn write_varying(
1417 &mut self,
1418 ir_module: &crate::Module,
1419 stage: crate::ShaderStage,
1420 class: spirv::StorageClass,
1421 debug_name: Option<&str>,
1422 ty: Handle<crate::Type>,
1423 binding: &crate::Binding,
1424 ) -> Result<Word, Error> {
1425 let id = self.id_gen.next();
1426 let pointer_type_id = self.get_pointer_id(ty, class);
1427 Instruction::variable(pointer_type_id, id, class, None)
1428 .to_words(&mut self.logical_layout.declarations);
1429
1430 if self
1431 .flags
1432 .contains(WriterFlags::DEBUG | WriterFlags::LABEL_VARYINGS)
1433 {
1434 if let Some(name) = debug_name {
1435 self.debugs.push(Instruction::name(id, name));
1436 }
1437 }
1438
1439 use spirv::{BuiltIn, Decoration};
1440
1441 match *binding {
1442 crate::Binding::Location {
1443 location,
1444 interpolation,
1445 sampling,
1446 second_blend_source,
1447 } => {
1448 self.decorate(id, Decoration::Location, &[location]);
1449
1450 let no_decorations =
1451 (class == spirv::StorageClass::Input && stage == crate::ShaderStage::Vertex) ||
1455 (class == spirv::StorageClass::Output && stage == crate::ShaderStage::Fragment);
1459
1460 if !no_decorations {
1461 match interpolation {
1462 None | Some(crate::Interpolation::Perspective) => (),
1464 Some(crate::Interpolation::Flat) => {
1465 self.decorate(id, Decoration::Flat, &[]);
1466 }
1467 Some(crate::Interpolation::Linear) => {
1468 self.decorate(id, Decoration::NoPerspective, &[]);
1469 }
1470 }
1471 match sampling {
1472 None
1474 | Some(
1475 crate::Sampling::Center
1476 | crate::Sampling::First
1477 | crate::Sampling::Either,
1478 ) => (),
1479 Some(crate::Sampling::Centroid) => {
1480 self.decorate(id, Decoration::Centroid, &[]);
1481 }
1482 Some(crate::Sampling::Sample) => {
1483 self.require_any(
1484 "per-sample interpolation",
1485 &[spirv::Capability::SampleRateShading],
1486 )?;
1487 self.decorate(id, Decoration::Sample, &[]);
1488 }
1489 }
1490 }
1491 if second_blend_source {
1492 self.decorate(id, Decoration::Index, &[1]);
1493 }
1494 }
1495 crate::Binding::BuiltIn(built_in) => {
1496 use crate::BuiltIn as Bi;
1497 let built_in = match built_in {
1498 Bi::Position { invariant } => {
1499 if invariant {
1500 self.decorate(id, Decoration::Invariant, &[]);
1501 }
1502
1503 if class == spirv::StorageClass::Output {
1504 BuiltIn::Position
1505 } else {
1506 BuiltIn::FragCoord
1507 }
1508 }
1509 Bi::ViewIndex => {
1510 self.require_any("`view_index` built-in", &[spirv::Capability::MultiView])?;
1511 BuiltIn::ViewIndex
1512 }
1513 Bi::BaseInstance => BuiltIn::BaseInstance,
1515 Bi::BaseVertex => BuiltIn::BaseVertex,
1516 Bi::ClipDistance => {
1517 self.require_any(
1518 "`clip_distance` built-in",
1519 &[spirv::Capability::ClipDistance],
1520 )?;
1521 BuiltIn::ClipDistance
1522 }
1523 Bi::CullDistance => {
1524 self.require_any(
1525 "`cull_distance` built-in",
1526 &[spirv::Capability::CullDistance],
1527 )?;
1528 BuiltIn::CullDistance
1529 }
1530 Bi::InstanceIndex => BuiltIn::InstanceIndex,
1531 Bi::PointSize => BuiltIn::PointSize,
1532 Bi::VertexIndex => BuiltIn::VertexIndex,
1533 Bi::DrawID => BuiltIn::DrawIndex,
1534 Bi::FragDepth => BuiltIn::FragDepth,
1536 Bi::PointCoord => BuiltIn::PointCoord,
1537 Bi::FrontFacing => BuiltIn::FrontFacing,
1538 Bi::PrimitiveIndex => {
1539 self.require_any(
1540 "`primitive_index` built-in",
1541 &[spirv::Capability::Geometry],
1542 )?;
1543 BuiltIn::PrimitiveId
1544 }
1545 Bi::SampleIndex => {
1546 self.require_any(
1547 "`sample_index` built-in",
1548 &[spirv::Capability::SampleRateShading],
1549 )?;
1550
1551 BuiltIn::SampleId
1552 }
1553 Bi::SampleMask => BuiltIn::SampleMask,
1554 Bi::GlobalInvocationId => BuiltIn::GlobalInvocationId,
1556 Bi::LocalInvocationId => BuiltIn::LocalInvocationId,
1557 Bi::LocalInvocationIndex => BuiltIn::LocalInvocationIndex,
1558 Bi::WorkGroupId => BuiltIn::WorkgroupId,
1559 Bi::WorkGroupSize => BuiltIn::WorkgroupSize,
1560 Bi::NumWorkGroups => BuiltIn::NumWorkgroups,
1561 Bi::NumSubgroups => {
1563 self.require_any(
1564 "`num_subgroups` built-in",
1565 &[spirv::Capability::GroupNonUniform],
1566 )?;
1567 BuiltIn::NumSubgroups
1568 }
1569 Bi::SubgroupId => {
1570 self.require_any(
1571 "`subgroup_id` built-in",
1572 &[spirv::Capability::GroupNonUniform],
1573 )?;
1574 BuiltIn::SubgroupId
1575 }
1576 Bi::SubgroupSize => {
1577 self.require_any(
1578 "`subgroup_size` built-in",
1579 &[
1580 spirv::Capability::GroupNonUniform,
1581 spirv::Capability::SubgroupBallotKHR,
1582 ],
1583 )?;
1584 BuiltIn::SubgroupSize
1585 }
1586 Bi::SubgroupInvocationId => {
1587 self.require_any(
1588 "`subgroup_invocation_id` built-in",
1589 &[
1590 spirv::Capability::GroupNonUniform,
1591 spirv::Capability::SubgroupBallotKHR,
1592 ],
1593 )?;
1594 BuiltIn::SubgroupLocalInvocationId
1595 }
1596 };
1597
1598 self.decorate(id, Decoration::BuiltIn, &[built_in as u32]);
1599
1600 use crate::ScalarKind as Sk;
1601
1602 if class == spirv::StorageClass::Input && stage == crate::ShaderStage::Fragment {
1608 let is_flat = match ir_module.types[ty].inner {
1609 crate::TypeInner::Scalar(scalar)
1610 | crate::TypeInner::Vector { scalar, .. } => match scalar.kind {
1611 Sk::Uint | Sk::Sint | Sk::Bool => true,
1612 Sk::Float => false,
1613 Sk::AbstractInt | Sk::AbstractFloat => {
1614 return Err(Error::Validation(
1615 "Abstract types should not appear in IR presented to backends",
1616 ))
1617 }
1618 },
1619 _ => false,
1620 };
1621
1622 if is_flat {
1623 self.decorate(id, Decoration::Flat, &[]);
1624 }
1625 }
1626 }
1627 }
1628
1629 Ok(id)
1630 }
1631
1632 fn write_global_variable(
1633 &mut self,
1634 ir_module: &crate::Module,
1635 global_variable: &crate::GlobalVariable,
1636 ) -> Result<Word, Error> {
1637 use spirv::Decoration;
1638
1639 let id = self.id_gen.next();
1640 let class = map_storage_class(global_variable.space);
1641
1642 if self.flags.contains(WriterFlags::DEBUG) {
1645 if let Some(ref name) = global_variable.name {
1646 self.debugs.push(Instruction::name(id, name));
1647 }
1648 }
1649
1650 let storage_access = match global_variable.space {
1651 crate::AddressSpace::Storage { access } => Some(access),
1652 _ => match ir_module.types[global_variable.ty].inner {
1653 crate::TypeInner::Image {
1654 class: crate::ImageClass::Storage { access, .. },
1655 ..
1656 } => Some(access),
1657 _ => None,
1658 },
1659 };
1660 if let Some(storage_access) = storage_access {
1661 if !storage_access.contains(crate::StorageAccess::LOAD) {
1662 self.decorate(id, Decoration::NonReadable, &[]);
1663 }
1664 if !storage_access.contains(crate::StorageAccess::STORE) {
1665 self.decorate(id, Decoration::NonWritable, &[]);
1666 }
1667 }
1668
1669 let mut substitute_inner_type_lookup = None;
1673 if let Some(ref res_binding) = global_variable.binding {
1674 self.decorate(id, Decoration::DescriptorSet, &[res_binding.group]);
1675 self.decorate(id, Decoration::Binding, &[res_binding.binding]);
1676
1677 if let Some(&BindingInfo {
1678 binding_array_size: Some(remapped_binding_array_size),
1679 }) = self.binding_map.get(res_binding)
1680 {
1681 if let crate::TypeInner::BindingArray { base, .. } =
1682 ir_module.types[global_variable.ty].inner
1683 {
1684 substitute_inner_type_lookup =
1685 Some(LookupType::Local(LocalType::PointerToBindingArray {
1686 base,
1687 size: remapped_binding_array_size,
1688 space: global_variable.space,
1689 }))
1690 }
1691 }
1692 };
1693
1694 let init_word = global_variable
1695 .init
1696 .map(|constant| self.constant_ids[constant]);
1697 let inner_type_id = self.get_type_id(
1698 substitute_inner_type_lookup.unwrap_or(LookupType::Handle(global_variable.ty)),
1699 );
1700
1701 let pointer_type_id = if global_needs_wrapper(ir_module, global_variable) {
1703 let wrapper_type_id = self.id_gen.next();
1704
1705 self.decorate(wrapper_type_id, Decoration::Block, &[]);
1706 let member = crate::StructMember {
1707 name: None,
1708 ty: global_variable.ty,
1709 binding: None,
1710 offset: 0,
1711 };
1712 self.decorate_struct_member(wrapper_type_id, 0, &member, &ir_module.types)?;
1713
1714 Instruction::type_struct(wrapper_type_id, &[inner_type_id])
1715 .to_words(&mut self.logical_layout.declarations);
1716
1717 let pointer_type_id = self.id_gen.next();
1718 Instruction::type_pointer(pointer_type_id, class, wrapper_type_id)
1719 .to_words(&mut self.logical_layout.declarations);
1720
1721 pointer_type_id
1722 } else {
1723 if let crate::AddressSpace::Storage { .. } = global_variable.space {
1729 match ir_module.types[global_variable.ty].inner {
1730 crate::TypeInner::BindingArray { base, .. } => {
1731 let ty = &ir_module.types[base];
1732 let mut should_decorate = true;
1733 if let crate::TypeInner::Struct { ref members, .. } = ty.inner {
1737 if let Some(last_member) = members.last() {
1739 if let &crate::TypeInner::Array {
1740 size: crate::ArraySize::Dynamic,
1741 ..
1742 } = &ir_module.types[last_member.ty].inner
1743 {
1744 should_decorate = false;
1745 }
1746 }
1747 }
1748 if should_decorate {
1749 let decorated_id = self.get_type_id(LookupType::Handle(base));
1750 self.decorate(decorated_id, Decoration::Block, &[]);
1751 }
1752 }
1753 _ => (),
1754 };
1755 }
1756 if substitute_inner_type_lookup.is_some() {
1757 inner_type_id
1758 } else {
1759 self.get_pointer_id(global_variable.ty, class)
1760 }
1761 };
1762
1763 let init_word = match (global_variable.space, self.zero_initialize_workgroup_memory) {
1764 (crate::AddressSpace::Private, _)
1765 | (crate::AddressSpace::WorkGroup, super::ZeroInitializeWorkgroupMemoryMode::Native) => {
1766 init_word.or_else(|| Some(self.get_constant_null(inner_type_id)))
1767 }
1768 _ => init_word,
1769 };
1770
1771 Instruction::variable(pointer_type_id, id, class, init_word)
1772 .to_words(&mut self.logical_layout.declarations);
1773 Ok(id)
1774 }
1775
1776 fn decorate_struct_member(
1781 &mut self,
1782 struct_id: Word,
1783 index: usize,
1784 member: &crate::StructMember,
1785 arena: &UniqueArena<crate::Type>,
1786 ) -> Result<(), Error> {
1787 use spirv::Decoration;
1788
1789 self.annotations.push(Instruction::member_decorate(
1790 struct_id,
1791 index as u32,
1792 Decoration::Offset,
1793 &[member.offset],
1794 ));
1795
1796 if self.flags.contains(WriterFlags::DEBUG) {
1797 if let Some(ref name) = member.name {
1798 self.debugs
1799 .push(Instruction::member_name(struct_id, index as u32, name));
1800 }
1801 }
1802
1803 let member_array_subty_inner = match arena[member.ty].inner {
1806 crate::TypeInner::Array { base, .. } => &arena[base].inner,
1807 ref other => other,
1808 };
1809 if let crate::TypeInner::Matrix {
1810 columns: _,
1811 rows,
1812 scalar,
1813 } = *member_array_subty_inner
1814 {
1815 let byte_stride = Alignment::from(rows) * scalar.width as u32;
1816 self.annotations.push(Instruction::member_decorate(
1817 struct_id,
1818 index as u32,
1819 Decoration::ColMajor,
1820 &[],
1821 ));
1822 self.annotations.push(Instruction::member_decorate(
1823 struct_id,
1824 index as u32,
1825 Decoration::MatrixStride,
1826 &[byte_stride],
1827 ));
1828 }
1829
1830 Ok(())
1831 }
1832
1833 fn get_function_type(&mut self, lookup_function_type: LookupFunctionType) -> Word {
1834 match self
1835 .lookup_function_type
1836 .entry(lookup_function_type.clone())
1837 {
1838 Entry::Occupied(e) => *e.get(),
1839 Entry::Vacant(_) => {
1840 let id = self.id_gen.next();
1841 let instruction = Instruction::type_function(
1842 id,
1843 lookup_function_type.return_type_id,
1844 &lookup_function_type.parameter_type_ids,
1845 );
1846 instruction.to_words(&mut self.logical_layout.declarations);
1847 self.lookup_function_type.insert(lookup_function_type, id);
1848 id
1849 }
1850 }
1851 }
1852
1853 fn write_physical_layout(&mut self) {
1854 self.physical_layout.bound = self.id_gen.0 + 1;
1855 }
1856
1857 fn write_logical_layout(
1858 &mut self,
1859 ir_module: &crate::Module,
1860 mod_info: &ModuleInfo,
1861 ep_index: Option<usize>,
1862 debug_info: &Option<DebugInfo>,
1863 ) -> Result<(), Error> {
1864 fn has_view_index_check(
1865 ir_module: &crate::Module,
1866 binding: Option<&crate::Binding>,
1867 ty: Handle<crate::Type>,
1868 ) -> bool {
1869 match ir_module.types[ty].inner {
1870 crate::TypeInner::Struct { ref members, .. } => members.iter().any(|member| {
1871 has_view_index_check(ir_module, member.binding.as_ref(), member.ty)
1872 }),
1873 _ => binding == Some(&crate::Binding::BuiltIn(crate::BuiltIn::ViewIndex)),
1874 }
1875 }
1876
1877 let has_storage_buffers =
1878 ir_module
1879 .global_variables
1880 .iter()
1881 .any(|(_, var)| match var.space {
1882 crate::AddressSpace::Storage { .. } => true,
1883 _ => false,
1884 });
1885 let has_view_index = ir_module
1886 .entry_points
1887 .iter()
1888 .flat_map(|entry| entry.function.arguments.iter())
1889 .any(|arg| has_view_index_check(ir_module, arg.binding.as_ref(), arg.ty));
1890 let mut has_ray_query = ir_module.special_types.ray_desc.is_some()
1891 | ir_module.special_types.ray_intersection.is_some();
1892
1893 for (_, &crate::Type { ref inner, .. }) in ir_module.types.iter() {
1894 if let &crate::TypeInner::AccelerationStructure | &crate::TypeInner::RayQuery = inner {
1895 has_ray_query = true
1896 }
1897 }
1898
1899 if self.physical_layout.version < 0x10300 && has_storage_buffers {
1900 Instruction::extension("SPV_KHR_storage_buffer_storage_class")
1902 .to_words(&mut self.logical_layout.extensions);
1903 }
1904 if has_view_index {
1905 Instruction::extension("SPV_KHR_multiview")
1906 .to_words(&mut self.logical_layout.extensions)
1907 }
1908 if has_ray_query {
1909 Instruction::extension("SPV_KHR_ray_query")
1910 .to_words(&mut self.logical_layout.extensions)
1911 }
1912 Instruction::type_void(self.void_type).to_words(&mut self.logical_layout.declarations);
1913 Instruction::ext_inst_import(self.gl450_ext_inst_id, "GLSL.std.450")
1914 .to_words(&mut self.logical_layout.ext_inst_imports);
1915
1916 let mut debug_info_inner = None;
1917 if self.flags.contains(WriterFlags::DEBUG) {
1918 if let Some(debug_info) = debug_info.as_ref() {
1919 let source_file_id = self.id_gen.next();
1920 self.debugs.push(Instruction::string(
1921 &debug_info.file_name.display().to_string(),
1922 source_file_id,
1923 ));
1924
1925 debug_info_inner = Some(DebugInfoInner {
1926 source_code: debug_info.source_code,
1927 source_file_id,
1928 });
1929 self.debugs.append(&mut Instruction::source_auto_continued(
1930 debug_info.language,
1931 0,
1932 &debug_info_inner,
1933 ));
1934 }
1935 }
1936
1937 for (handle, _) in ir_module.types.iter() {
1939 self.write_type_declaration_arena(&ir_module.types, handle)?;
1940 }
1941
1942 self.constant_ids
1944 .resize(ir_module.global_expressions.len(), 0);
1945 for (handle, _) in ir_module.global_expressions.iter() {
1946 self.write_constant_expr(handle, ir_module, mod_info)?;
1947 }
1948 debug_assert!(self.constant_ids.iter().all(|&id| id != 0));
1949
1950 if self.flags.contains(WriterFlags::DEBUG) {
1952 for (_, constant) in ir_module.constants.iter() {
1953 if let Some(ref name) = constant.name {
1954 let id = self.constant_ids[constant.init];
1955 self.debugs.push(Instruction::name(id, name));
1956 }
1957 }
1958 }
1959
1960 for (handle, var) in ir_module.global_variables.iter() {
1962 let gvar = match ep_index {
1966 Some(index) if mod_info.get_entry_point(index)[handle].is_empty() => {
1967 GlobalVariable::dummy()
1968 }
1969 _ => {
1970 let id = self.write_global_variable(ir_module, var)?;
1971 GlobalVariable::new(id)
1972 }
1973 };
1974 self.global_variables.insert(handle, gvar);
1975 }
1976
1977 for (handle, ir_function) in ir_module.functions.iter() {
1979 let info = &mod_info[handle];
1980 if let Some(index) = ep_index {
1981 let ep_info = mod_info.get_entry_point(index);
1982 if !ep_info.dominates_global_use(info) {
1986 log::info!("Skip function {:?}", ir_function.name);
1987 continue;
1988 }
1989
1990 if !info.available_stages.contains(ep_info.available_stages) {
2000 continue;
2001 }
2002 }
2003 let id = self.write_function(ir_function, info, ir_module, None, &debug_info_inner)?;
2004 self.lookup_function.insert(handle, id);
2005 }
2006
2007 for (index, ir_ep) in ir_module.entry_points.iter().enumerate() {
2009 if ep_index.is_some() && ep_index != Some(index) {
2010 continue;
2011 }
2012 let info = mod_info.get_entry_point(index);
2013 let ep_instruction =
2014 self.write_entry_point(ir_ep, info, ir_module, &debug_info_inner)?;
2015 ep_instruction.to_words(&mut self.logical_layout.entry_points);
2016 }
2017
2018 for capability in self.capabilities_used.iter() {
2019 Instruction::capability(*capability).to_words(&mut self.logical_layout.capabilities);
2020 }
2021 for extension in self.extensions_used.iter() {
2022 Instruction::extension(extension).to_words(&mut self.logical_layout.extensions);
2023 }
2024 if ir_module.entry_points.is_empty() {
2025 Instruction::capability(spirv::Capability::Linkage)
2027 .to_words(&mut self.logical_layout.capabilities);
2028 }
2029
2030 let addressing_model = spirv::AddressingModel::Logical;
2031 let memory_model = spirv::MemoryModel::GLSL450;
2032 Instruction::memory_model(addressing_model, memory_model)
2036 .to_words(&mut self.logical_layout.memory_model);
2037
2038 if self.flags.contains(WriterFlags::DEBUG) {
2039 for debug in self.debugs.iter() {
2040 debug.to_words(&mut self.logical_layout.debugs);
2041 }
2042 }
2043
2044 for annotation in self.annotations.iter() {
2045 annotation.to_words(&mut self.logical_layout.annotations);
2046 }
2047
2048 Ok(())
2049 }
2050
2051 pub fn write(
2052 &mut self,
2053 ir_module: &crate::Module,
2054 info: &ModuleInfo,
2055 pipeline_options: Option<&PipelineOptions>,
2056 debug_info: &Option<DebugInfo>,
2057 words: &mut Vec<Word>,
2058 ) -> Result<(), Error> {
2059 if !ir_module.overrides.is_empty() {
2060 return Err(Error::Override);
2061 }
2062
2063 self.reset();
2064
2065 let ep_index = match pipeline_options {
2067 Some(po) => {
2068 let index = ir_module
2069 .entry_points
2070 .iter()
2071 .position(|ep| po.shader_stage == ep.stage && po.entry_point == ep.name)
2072 .ok_or(Error::EntryPointNotFound)?;
2073 Some(index)
2074 }
2075 None => None,
2076 };
2077
2078 self.write_logical_layout(ir_module, info, ep_index, debug_info)?;
2079 self.write_physical_layout();
2080
2081 self.physical_layout.in_words(words);
2082 self.logical_layout.in_words(words);
2083 Ok(())
2084 }
2085
2086 pub const fn get_capabilities_used(&self) -> &crate::FastIndexSet<spirv::Capability> {
2088 &self.capabilities_used
2089 }
2090
2091 pub fn decorate_non_uniform_binding_array_access(&mut self, id: Word) -> Result<(), Error> {
2092 self.require_any("NonUniformEXT", &[spirv::Capability::ShaderNonUniform])?;
2093 self.use_extension("SPV_EXT_descriptor_indexing");
2094 self.decorate(id, spirv::Decoration::NonUniform, &[]);
2095 Ok(())
2096 }
2097}
2098
2099#[test]
2100fn test_write_physical_layout() {
2101 let mut writer = Writer::new(&Options::default()).unwrap();
2102 assert_eq!(writer.physical_layout.bound, 0);
2103 writer.write_physical_layout();
2104 assert_eq!(writer.physical_layout.bound, 3);
2105}