1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
mod block;
mod helpers;
mod image;
mod index;
mod instructions;
mod layout;
mod recyclable;
mod selection;
mod writer;
pub use spirv::Capability;
use crate::arena::Handle;
use crate::proc::{BoundsCheckPolicies, TypeResolution};
use spirv::Word;
use std::ops;
use thiserror::Error;
#[derive(Clone)]
struct PhysicalLayout {
magic_number: Word,
version: Word,
generator: Word,
bound: Word,
instruction_schema: Word,
}
#[derive(Default)]
struct LogicalLayout {
capabilities: Vec<Word>,
extensions: Vec<Word>,
ext_inst_imports: Vec<Word>,
memory_model: Vec<Word>,
entry_points: Vec<Word>,
execution_modes: Vec<Word>,
debugs: Vec<Word>,
annotations: Vec<Word>,
declarations: Vec<Word>,
function_declarations: Vec<Word>,
function_definitions: Vec<Word>,
}
struct Instruction {
op: spirv::Op,
wc: u32,
type_id: Option<Word>,
result_id: Option<Word>,
operands: Vec<Word>,
}
const BITS_PER_BYTE: crate::Bytes = 8;
#[derive(Clone, Debug, Error)]
pub enum Error {
#[error("The requested entry point couldn't be found")]
EntryPointNotFound,
#[error("target SPIRV-{0}.{1} is not supported")]
UnsupportedVersion(u8, u8),
#[error("using {0} requires at least one of the capabilities {1:?}, but none are available")]
MissingCapabilities(&'static str, Vec<Capability>),
#[error("unimplemented {0}")]
FeatureNotImplemented(&'static str),
#[error("module is not validated properly: {0}")]
Validation(&'static str),
}
#[derive(Default)]
struct IdGenerator(Word);
impl IdGenerator {
fn next(&mut self) -> Word {
self.0 += 1;
self.0
}
}
struct Block {
label_id: Word,
body: Vec<Instruction>,
}
struct TerminatedBlock {
label_id: Word,
body: Vec<Instruction>,
}
impl Block {
const fn new(label_id: Word) -> Self {
Block {
label_id,
body: Vec::new(),
}
}
}
struct LocalVariable {
id: Word,
instruction: Instruction,
}
struct ResultMember {
id: Word,
type_id: Word,
built_in: Option<crate::BuiltIn>,
}
struct EntryPointContext {
argument_ids: Vec<Word>,
results: Vec<ResultMember>,
}
#[derive(Default)]
struct Function {
signature: Option<Instruction>,
parameters: Vec<FunctionArgument>,
variables: crate::FastHashMap<Handle<crate::LocalVariable>, LocalVariable>,
blocks: Vec<TerminatedBlock>,
entry_point_context: Option<EntryPointContext>,
}
impl Function {
fn consume(&mut self, mut block: Block, termination: Instruction) {
block.body.push(termination);
self.blocks.push(TerminatedBlock {
label_id: block.label_id,
body: block.body,
})
}
fn parameter_id(&self, index: u32) -> Word {
match self.entry_point_context {
Some(ref context) => context.argument_ids[index as usize],
None => self.parameters[index as usize]
.instruction
.result_id
.unwrap(),
}
}
}
#[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)]
struct LocalImageType {
sampled_type: crate::ScalarKind,
dim: spirv::Dim,
flags: ImageTypeFlags,
image_format: spirv::ImageFormat,
}
bitflags::bitflags! {
pub struct ImageTypeFlags: u8 {
const DEPTH = 0x1;
const ARRAYED = 0x2;
const MULTISAMPLED = 0x4;
const SAMPLED = 0x8;
}
}
impl LocalImageType {
fn from_inner(dim: crate::ImageDimension, arrayed: bool, class: crate::ImageClass) -> Self {
let make_flags = |multi: bool, other: ImageTypeFlags| -> ImageTypeFlags {
let mut flags = other;
flags.set(ImageTypeFlags::ARRAYED, arrayed);
flags.set(ImageTypeFlags::MULTISAMPLED, multi);
flags
};
let dim = spirv::Dim::from(dim);
match class {
crate::ImageClass::Sampled { kind, multi } => LocalImageType {
sampled_type: kind,
dim,
flags: make_flags(multi, ImageTypeFlags::SAMPLED),
image_format: spirv::ImageFormat::Unknown,
},
crate::ImageClass::Depth { multi } => LocalImageType {
sampled_type: crate::ScalarKind::Float,
dim,
flags: make_flags(multi, ImageTypeFlags::DEPTH | ImageTypeFlags::SAMPLED),
image_format: spirv::ImageFormat::Unknown,
},
crate::ImageClass::Storage { format, access: _ } => LocalImageType {
sampled_type: crate::ScalarKind::from(format),
dim,
flags: make_flags(false, ImageTypeFlags::empty()),
image_format: format.into(),
},
}
}
}
#[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)]
enum LocalType {
Value {
vector_size: Option<crate::VectorSize>,
kind: crate::ScalarKind,
width: crate::Bytes,
pointer_space: Option<spirv::StorageClass>,
},
Matrix {
columns: crate::VectorSize,
rows: crate::VectorSize,
width: crate::Bytes,
},
Pointer {
base: Handle<crate::Type>,
class: spirv::StorageClass,
},
Image(LocalImageType),
SampledImage {
image_type_id: Word,
},
Sampler,
PointerToBindingArray {
base: Handle<crate::Type>,
size: u64,
},
BindingArray {
base: Handle<crate::Type>,
size: u64,
},
}
#[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)]
enum LookupType {
Handle(Handle<crate::Type>),
Local(LocalType),
}
impl From<LocalType> for LookupType {
fn from(local: LocalType) -> Self {
Self::Local(local)
}
}
#[derive(Debug, PartialEq, Clone, Hash, Eq)]
struct LookupFunctionType {
parameter_type_ids: Vec<Word>,
return_type_id: Word,
}
fn make_local(inner: &crate::TypeInner) -> Option<LocalType> {
Some(match *inner {
crate::TypeInner::Scalar { kind, width } | crate::TypeInner::Atomic { kind, width } => {
LocalType::Value {
vector_size: None,
kind,
width,
pointer_space: None,
}
}
crate::TypeInner::Vector { size, kind, width } => LocalType::Value {
vector_size: Some(size),
kind,
width,
pointer_space: None,
},
crate::TypeInner::Matrix {
columns,
rows,
width,
} => LocalType::Matrix {
columns,
rows,
width,
},
crate::TypeInner::Pointer { base, space } => LocalType::Pointer {
base,
class: helpers::map_storage_class(space),
},
crate::TypeInner::ValuePointer {
size,
kind,
width,
space,
} => LocalType::Value {
vector_size: size,
kind,
width,
pointer_space: Some(helpers::map_storage_class(space)),
},
crate::TypeInner::Image {
dim,
arrayed,
class,
} => LocalType::Image(LocalImageType::from_inner(dim, arrayed, class)),
crate::TypeInner::Sampler { comparison: _ } => LocalType::Sampler,
_ => return None,
})
}
#[derive(Debug)]
enum Dimension {
Scalar,
Vector,
Matrix,
}
#[derive(Default)]
struct CachedExpressions {
ids: Vec<Word>,
}
impl CachedExpressions {
fn reset(&mut self, length: usize) {
self.ids.clear();
self.ids.resize(length, 0);
}
}
impl ops::Index<Handle<crate::Expression>> for CachedExpressions {
type Output = Word;
fn index(&self, h: Handle<crate::Expression>) -> &Word {
let id = &self.ids[h.index()];
if *id == 0 {
unreachable!("Expression {:?} is not cached!", h);
}
id
}
}
impl ops::IndexMut<Handle<crate::Expression>> for CachedExpressions {
fn index_mut(&mut self, h: Handle<crate::Expression>) -> &mut Word {
let id = &mut self.ids[h.index()];
if *id != 0 {
unreachable!("Expression {:?} is already cached!", h);
}
id
}
}
impl recyclable::Recyclable for CachedExpressions {
fn recycle(self) -> Self {
CachedExpressions {
ids: self.ids.recycle(),
}
}
}
#[derive(Clone)]
struct GlobalVariable {
var_id: Word,
handle_id: Word,
access_id: Word,
}
impl GlobalVariable {
const fn dummy() -> Self {
Self {
var_id: 0,
handle_id: 0,
access_id: 0,
}
}
const fn new(id: Word) -> Self {
Self {
var_id: id,
handle_id: 0,
access_id: 0,
}
}
fn reset_for_function(&mut self) {
self.handle_id = 0;
self.access_id = 0;
}
}
struct FunctionArgument {
instruction: Instruction,
handle_id: Word,
}
struct BlockContext<'w> {
writer: &'w mut Writer,
ir_module: &'w crate::Module,
ir_function: &'w crate::Function,
fun_info: &'w crate::valid::FunctionInfo,
function: &'w mut Function,
cached: CachedExpressions,
temp_list: Vec<Word>,
}
impl BlockContext<'_> {
fn gen_id(&mut self) -> Word {
self.writer.id_gen.next()
}
fn get_type_id(&mut self, lookup_type: LookupType) -> Word {
self.writer.get_type_id(lookup_type)
}
fn get_expression_type_id(&mut self, tr: &TypeResolution) -> Word {
self.writer.get_expression_type_id(tr)
}
fn get_index_constant(&mut self, index: Word) -> Word {
self.writer
.get_constant_scalar(crate::ScalarValue::Uint(index as _), 4)
}
fn get_scope_constant(&mut self, scope: Word) -> Word {
self.writer
.get_constant_scalar(crate::ScalarValue::Sint(scope as _), 4)
}
}
#[derive(Clone, Copy, Default)]
struct LoopContext {
continuing_id: Option<Word>,
break_id: Option<Word>,
}
pub struct Writer {
physical_layout: PhysicalLayout,
logical_layout: LogicalLayout,
id_gen: IdGenerator,
capabilities_available: Option<crate::FastHashSet<Capability>>,
capabilities_used: crate::FastHashSet<Capability>,
extensions_used: crate::FastHashSet<&'static str>,
debugs: Vec<Instruction>,
annotations: Vec<Instruction>,
flags: WriterFlags,
bounds_check_policies: BoundsCheckPolicies,
zero_initialize_workgroup_memory: ZeroInitializeWorkgroupMemoryMode,
void_type: Word,
lookup_type: crate::FastHashMap<LookupType, Word>,
lookup_function: crate::FastHashMap<Handle<crate::Function>, Word>,
lookup_function_type: crate::FastHashMap<LookupFunctionType, Word>,
constant_ids: Vec<Word>,
cached_constants: crate::FastHashMap<(crate::ScalarValue, crate::Bytes), Word>,
global_variables: Vec<GlobalVariable>,
binding_map: BindingMap,
saved_cached: CachedExpressions,
gl450_ext_inst_id: Word,
temp_list: Vec<Word>,
}
bitflags::bitflags! {
pub struct WriterFlags: u32 {
const DEBUG = 0x1;
const ADJUST_COORDINATE_SPACE = 0x2;
const LABEL_VARYINGS = 0x4;
const FORCE_POINT_SIZE = 0x8;
const CLAMP_FRAG_DEPTH = 0x10;
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
pub struct BindingInfo {
pub binding_array_size: Option<u32>,
}
pub type BindingMap = std::collections::BTreeMap<crate::ResourceBinding, BindingInfo>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ZeroInitializeWorkgroupMemoryMode {
Native,
Polyfill,
None,
}
#[derive(Debug, Clone)]
pub struct Options {
pub lang_version: (u8, u8),
pub flags: WriterFlags,
pub binding_map: BindingMap,
pub capabilities: Option<crate::FastHashSet<Capability>>,
pub bounds_check_policies: BoundsCheckPolicies,
pub zero_initialize_workgroup_memory: ZeroInitializeWorkgroupMemoryMode,
}
impl Default for Options {
fn default() -> Self {
let mut flags = WriterFlags::ADJUST_COORDINATE_SPACE
| WriterFlags::LABEL_VARYINGS
| WriterFlags::CLAMP_FRAG_DEPTH;
if cfg!(debug_assertions) {
flags |= WriterFlags::DEBUG;
}
Options {
lang_version: (1, 0),
flags,
binding_map: BindingMap::default(),
capabilities: None,
bounds_check_policies: crate::proc::BoundsCheckPolicies::default(),
zero_initialize_workgroup_memory: ZeroInitializeWorkgroupMemoryMode::Polyfill,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
pub struct PipelineOptions {
pub shader_stage: crate::ShaderStage,
pub entry_point: String,
}
pub fn write_vec(
module: &crate::Module,
info: &crate::valid::ModuleInfo,
options: &Options,
pipeline_options: Option<&PipelineOptions>,
) -> Result<Vec<u32>, Error> {
let mut words = Vec::new();
let mut w = Writer::new(options)?;
w.write(module, info, pipeline_options, &mut words)?;
Ok(words)
}