-
Notifications
You must be signed in to change notification settings - Fork 249
/
Copy pathbuilder_methods.rs
2144 lines (2020 loc) · 77.5 KB
/
builder_methods.rs
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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use super::Builder;
use crate::builder_spirv::{BuilderCursor, SpirvConst, SpirvValue, SpirvValueExt, SpirvValueKind};
use crate::spirv_type::SpirvType;
use rspirv::dr::{InsertPoint, Instruction, Operand};
use rspirv::spirv::{Capability, MemoryModel, MemorySemantics, Op, Scope, StorageClass, Word};
use rustc_codegen_ssa::common::{
AtomicOrdering, AtomicRmwBinOp, IntPredicate, RealPredicate, SynchronizationScope,
};
use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
use rustc_codegen_ssa::mir::place::PlaceRef;
use rustc_codegen_ssa::traits::{
BuilderMethods, ConstMethods, IntrinsicCallMethods, LayoutTypeMethods, OverflowOp,
};
use rustc_codegen_ssa::MemFlags;
use rustc_middle::bug;
use rustc_middle::ty::Ty;
use rustc_span::Span;
use rustc_target::abi::{Abi, Align, Scalar, Size};
use std::convert::TryInto;
use std::iter::empty;
use std::ops::Range;
macro_rules! simple_op {
(
$func_name:ident, $inst_name:ident
$(, fold_const {
$(int($fold_int_lhs:ident, $fold_int_rhs:ident) => $fold_int:expr)?
})?
) => {
fn $func_name(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value {
assert_ty_eq!(self, lhs.ty, rhs.ty);
let result_type = lhs.ty;
$(if let Some(const_lhs) = self.builder.lookup_const(lhs) {
if let Some(const_rhs) = self.builder.lookup_const(rhs) {
match self.lookup_type(result_type) {
$(SpirvType::Integer(bits, signed) => {
let size = Size::from_bits(bits);
let as_u128 = |const_val| {
let x = match const_val {
SpirvConst::U32(_, x) => x as u128,
SpirvConst::U64(_, x) => x as u128,
_ => return None,
};
Some(if signed {
size.sign_extend(x)
} else {
size.truncate(x)
})
};
if let Some($fold_int_lhs) = as_u128(const_lhs) {
if let Some($fold_int_rhs) = as_u128(const_rhs) {
return self.const_uint_big(result_type, $fold_int);
}
}
})?
_ => {}
}
}
})?
self.emit()
.$inst_name(result_type, None, lhs.def(self), rhs.def(self))
.unwrap()
.with_type(result_type)
}
};
}
// shl and shr allow different types as their operands
macro_rules! simple_op_unchecked_type {
($func_name:ident, $inst_name:ident) => {
fn $func_name(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value {
self.emit()
.$inst_name(lhs.ty, None, lhs.def(self), rhs.def(self))
.unwrap()
.with_type(lhs.ty)
}
};
}
macro_rules! simple_uni_op {
($func_name:ident, $inst_name:ident) => {
fn $func_name(&mut self, val: Self::Value) -> Self::Value {
self.emit()
.$inst_name(val.ty, None, val.def(self))
.unwrap()
.with_type(val.ty)
}
};
}
fn memset_fill_u16(b: u8) -> u16 {
b as u16 | ((b as u16) << 8)
}
fn memset_fill_u32(b: u8) -> u32 {
b as u32 | ((b as u32) << 8) | ((b as u32) << 16) | ((b as u32) << 24)
}
fn memset_fill_u64(b: u8) -> u64 {
b as u64
| ((b as u64) << 8)
| ((b as u64) << 16)
| ((b as u64) << 24)
| ((b as u64) << 32)
| ((b as u64) << 40)
| ((b as u64) << 48)
| ((b as u64) << 56)
}
fn memset_dynamic_scalar(
builder: &Builder<'_, '_>,
fill_var: Word,
byte_width: usize,
is_float: bool,
) -> Word {
let composite_type = SpirvType::Vector {
element: SpirvType::Integer(8, false).def(builder.span(), builder),
count: byte_width as u32,
}
.def(builder.span(), builder);
let composite = builder
.emit()
.composite_construct(
composite_type,
None,
std::iter::repeat(fill_var).take(byte_width),
)
.unwrap();
let result_type = if is_float {
SpirvType::Float(byte_width as u32 * 8)
} else {
SpirvType::Integer(byte_width as u32 * 8, false)
};
builder
.emit()
.bitcast(result_type.def(builder.span(), builder), None, composite)
.unwrap()
}
impl<'a, 'tcx> Builder<'a, 'tcx> {
fn ordering_to_semantics_def(&self, ordering: AtomicOrdering) -> SpirvValue {
let mut invalid_seq_cst = false;
let semantics = match ordering {
AtomicOrdering::NotAtomic | AtomicOrdering::Unordered | AtomicOrdering::Monotonic => {
MemorySemantics::NONE
}
// Note: rustc currently has AtomicOrdering::Consume commented out, if it ever becomes
// uncommented, it should be MakeVisible | Acquire.
AtomicOrdering::Acquire => MemorySemantics::MAKE_VISIBLE | MemorySemantics::ACQUIRE,
AtomicOrdering::Release => MemorySemantics::MAKE_AVAILABLE | MemorySemantics::RELEASE,
AtomicOrdering::AcquireRelease => {
MemorySemantics::MAKE_AVAILABLE
| MemorySemantics::MAKE_VISIBLE
| MemorySemantics::ACQUIRE_RELEASE
}
AtomicOrdering::SequentiallyConsistent => {
let emit = self.emit();
let memory_model = emit.module_ref().memory_model.as_ref().unwrap();
if memory_model.operands[1].unwrap_memory_model() == MemoryModel::Vulkan {
invalid_seq_cst = true;
}
MemorySemantics::MAKE_AVAILABLE
| MemorySemantics::MAKE_VISIBLE
| MemorySemantics::SEQUENTIALLY_CONSISTENT
}
};
let semantics = self.constant_u32(self.span(), semantics.bits());
if invalid_seq_cst {
self.zombie(
semantics.def(self),
"Cannot use AtomicOrdering=SequentiallyConsistent on Vulkan memory model. Check if AcquireRelease fits your needs.",
);
}
semantics
}
fn memset_const_pattern(&self, ty: &SpirvType, fill_byte: u8) -> Word {
match *ty {
SpirvType::Void => self.fatal("memset invalid on void pattern"),
SpirvType::Bool => self.fatal("memset invalid on bool pattern"),
SpirvType::Integer(width, _signedness) => match width {
8 => self.constant_u8(self.span(), fill_byte).def(self),
16 => self
.constant_u16(self.span(), memset_fill_u16(fill_byte))
.def(self),
32 => self
.constant_u32(self.span(), memset_fill_u32(fill_byte))
.def(self),
64 => self
.constant_u64(self.span(), memset_fill_u64(fill_byte))
.def(self),
_ => self.fatal(&format!(
"memset on integer width {} not implemented yet",
width
)),
},
SpirvType::Float(width) => match width {
32 => self
.constant_f32(self.span(), f32::from_bits(memset_fill_u32(fill_byte)))
.def(self),
64 => self
.constant_f64(self.span(), f64::from_bits(memset_fill_u64(fill_byte)))
.def(self),
_ => self.fatal(&format!(
"memset on float width {} not implemented yet",
width
)),
},
SpirvType::Adt { .. } => self.fatal("memset on structs not implemented yet"),
SpirvType::Opaque { .. } => self.fatal("memset on opaque type is invalid"),
SpirvType::Vector { element, count } => {
let elem_pat = self.memset_const_pattern(&self.lookup_type(element), fill_byte);
self.constant_composite(
ty.clone().def(self.span(), self),
vec![elem_pat; count as usize],
)
.def(self)
}
SpirvType::Array { element, count } => {
let elem_pat = self.memset_const_pattern(&self.lookup_type(element), fill_byte);
let count = self.builder.lookup_const_u64(count).unwrap() as usize;
self.constant_composite(ty.clone().def(self.span(), self), vec![elem_pat; count])
.def(self)
}
SpirvType::RuntimeArray { .. } => {
self.fatal("memset on runtime arrays not implemented yet")
}
SpirvType::Pointer { .. } => self.fatal("memset on pointers not implemented yet"),
SpirvType::Function { .. } => self.fatal("memset on functions not implemented yet"),
SpirvType::Image { .. } => self.fatal("cannot memset image"),
SpirvType::Sampler => self.fatal("cannot memset sampler"),
SpirvType::SampledImage { .. } => self.fatal("cannot memset sampled image"),
}
}
fn memset_dynamic_pattern(&self, ty: &SpirvType, fill_var: Word) -> Word {
match *ty {
SpirvType::Void => self.fatal("memset invalid on void pattern"),
SpirvType::Bool => self.fatal("memset invalid on bool pattern"),
SpirvType::Integer(width, _signedness) => match width {
8 => fill_var,
16 => memset_dynamic_scalar(self, fill_var, 2, false),
32 => memset_dynamic_scalar(self, fill_var, 4, false),
64 => memset_dynamic_scalar(self, fill_var, 8, false),
_ => self.fatal(&format!(
"memset on integer width {} not implemented yet",
width
)),
},
SpirvType::Float(width) => match width {
32 => memset_dynamic_scalar(self, fill_var, 4, true),
64 => memset_dynamic_scalar(self, fill_var, 8, true),
_ => self.fatal(&format!(
"memset on float width {} not implemented yet",
width
)),
},
SpirvType::Adt { .. } => self.fatal("memset on structs not implemented yet"),
SpirvType::Opaque { .. } => self.fatal("memset on opaque type is invalid"),
SpirvType::Array { element, count } => {
let elem_pat = self.memset_dynamic_pattern(&self.lookup_type(element), fill_var);
let count = self.builder.lookup_const_u64(count).unwrap() as usize;
self.emit()
.composite_construct(
ty.clone().def(self.span(), self),
None,
std::iter::repeat(elem_pat).take(count),
)
.unwrap()
}
SpirvType::Vector { element, count } => {
let elem_pat = self.memset_dynamic_pattern(&self.lookup_type(element), fill_var);
self.emit()
.composite_construct(
ty.clone().def(self.span(), self),
None,
std::iter::repeat(elem_pat).take(count as usize),
)
.unwrap()
}
SpirvType::RuntimeArray { .. } => {
self.fatal("memset on runtime arrays not implemented yet")
}
SpirvType::Pointer { .. } => self.fatal("memset on pointers not implemented yet"),
SpirvType::Function { .. } => self.fatal("memset on functions not implemented yet"),
SpirvType::Image { .. } => self.fatal("cannot memset image"),
SpirvType::Sampler => self.fatal("cannot memset sampler"),
SpirvType::SampledImage { .. } => self.fatal("cannot memset sampled image"),
}
}
fn memset_constant_size(&mut self, ptr: SpirvValue, pat: SpirvValue, size_bytes: u64) {
let size_elem = self
.lookup_type(pat.ty)
.sizeof(self)
.expect("Memset on unsized values not supported");
let count = size_bytes / size_elem.bytes();
if count == 1 {
self.store(pat, ptr, Align::from_bytes(0).unwrap());
} else {
for index in 0..count {
let const_index = self.constant_u32(self.span(), index as u32);
let gep_ptr = self.gep(ptr, &[const_index]);
self.store(pat, gep_ptr, Align::from_bytes(0).unwrap());
}
}
}
// TODO: Test this is correct
fn memset_dynamic_size(&mut self, ptr: SpirvValue, pat: SpirvValue, size_bytes: SpirvValue) {
let size_elem = self
.lookup_type(pat.ty)
.sizeof(self)
.expect("Unable to memset a dynamic sized object");
let size_elem_const = self.constant_int(size_bytes.ty, size_elem.bytes());
let zero = self.constant_int(size_bytes.ty, 0);
let one = self.constant_int(size_bytes.ty, 1);
let zero_align = Align::from_bytes(0).unwrap();
let mut header = self.build_sibling_block("memset_header");
let mut body = self.build_sibling_block("memset_body");
let exit = self.build_sibling_block("memset_exit");
let count = self.udiv(size_bytes, size_elem_const);
let index = self.alloca(count.ty, zero_align);
self.store(zero, index, zero_align);
self.br(header.llbb());
let current_index = header.load(index, zero_align);
let cond = header.icmp(IntPredicate::IntULT, current_index, count);
header.cond_br(cond, body.llbb(), exit.llbb());
let gep_ptr = body.gep(ptr, &[current_index]);
body.store(pat, gep_ptr, zero_align);
let current_index_plus_1 = body.add(current_index, one);
body.store(current_index_plus_1, index, zero_align);
body.br(header.llbb());
*self = exit;
}
fn zombie_convert_ptr_to_u(&self, def: Word) {
if !self.builder.has_capability(Capability::Addresses)
&& !self
.builder
.has_capability(Capability::PhysicalStorageBufferAddresses)
{
self.zombie(
def,
"OpConvertPtrToU without OpCapability Addresses or PhysicalStorageBufferAddresses",
);
}
}
fn zombie_convert_u_to_ptr(&self, def: Word) {
if !self.builder.has_capability(Capability::Addresses)
&& !self
.builder
.has_capability(Capability::PhysicalStorageBufferAddresses)
{
self.zombie(
def,
"OpConvertUToPtr OpCapability Addresses or PhysicalStorageBufferAddresses",
);
}
}
/// If possible, return the appropriate `OpAccessChain` indices for going from
/// a pointer to `ty`, to a pointer to `leaf_ty`, with an added `offset`.
///
/// That is, try to turn `((_: *T) as *u8).add(offset) as *Leaf` into a series
/// of struct field and array/vector element accesses.
fn recover_access_chain_from_offset(
&self,
mut ty: Word,
leaf_ty: Word,
mut offset: Size,
) -> Option<Vec<u32>> {
assert_ne!(ty, leaf_ty);
// NOTE(eddyb) `ty` and `ty_kind` should be kept in sync.
let mut ty_kind = self.lookup_type(ty);
let mut indices = Vec::new();
loop {
match ty_kind {
SpirvType::Adt {
field_types,
field_offsets,
..
} => {
let (i, field_ty, field_ty_kind, offset_in_field) = field_offsets
.iter()
.enumerate()
.find_map(|(i, &field_offset)| {
if field_offset > offset {
return None;
}
// Grab the actual field type to be able to confirm that
// the leaf is somewhere inside the field.
let field_ty = field_types[i];
let field_ty_kind = self.lookup_type(field_ty);
let offset_in_field = offset - field_offset;
if field_ty_kind
.sizeof(self)
.map_or(true, |size| offset_in_field < size)
{
Some((i, field_ty, field_ty_kind, offset_in_field))
} else {
None
}
})?;
ty = field_ty;
ty_kind = field_ty_kind;
indices.push(i as u32);
offset = offset_in_field;
}
SpirvType::Vector { element, .. }
| SpirvType::Array { element, .. }
| SpirvType::RuntimeArray { element } => {
ty = element;
ty_kind = self.lookup_type(ty);
let stride = ty_kind.sizeof(self)?;
indices.push((offset.bytes() / stride.bytes()).try_into().ok()?);
offset = Size::from_bytes(offset.bytes() % stride.bytes());
}
_ => return None,
}
if offset == Size::ZERO && ty == leaf_ty {
return Some(indices);
}
}
}
}
impl<'a, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'tcx> {
fn new_block<'b>(cx: &'a Self::CodegenCx, llfn: Self::Function, _name: &'b str) -> Self {
let cursor_fn = cx.builder.select_function_by_id(llfn.def_cx(cx));
let label = cx.emit_with_cursor(cursor_fn).begin_block(None).unwrap();
let cursor = cx.builder.select_block_by_id(label);
Self {
cx,
cursor,
current_fn: llfn,
basic_block: label,
current_span: Default::default(),
}
}
fn with_cx(cx: &'a Self::CodegenCx) -> Self {
// Note: all defaults here *must* be filled out by position_at_end
Self {
cx,
cursor: Default::default(),
current_fn: 0.with_type(0),
basic_block: Default::default(),
current_span: Default::default(),
}
}
fn build_sibling_block(&self, _name: &str) -> Self {
let mut builder = self.emit_with_cursor(BuilderCursor {
function: self.cursor.function,
block: None,
});
let new_bb = builder.begin_block(None).unwrap();
let new_cursor = BuilderCursor {
function: self.cursor.function,
block: builder.selected_block(),
};
Self {
cx: self.cx,
cursor: new_cursor,
current_fn: self.current_fn,
basic_block: new_bb,
current_span: Default::default(),
}
}
fn cx(&self) -> &Self::CodegenCx {
self.cx
}
fn llbb(&self) -> Self::BasicBlock {
self.basic_block
}
fn set_span(&mut self, span: Span) {
self.current_span = Some(span);
}
fn position_at_end(&mut self, llbb: Self::BasicBlock) {
let cursor = self.cx.builder.select_block_by_id(llbb);
let current_fn = {
let emit = self.emit_with_cursor(cursor);
let selected_function = emit.selected_function().unwrap();
let selected_function = &emit.module_ref().functions[selected_function];
let def_inst = selected_function.def.as_ref().unwrap();
let def = def_inst.result_id.unwrap();
let ty = def_inst.operands[1].unwrap_id_ref();
def.with_type(ty)
};
self.cursor = cursor;
self.current_fn = current_fn;
self.basic_block = llbb;
}
fn ret_void(&mut self) {
self.emit().ret().unwrap();
}
fn ret(&mut self, value: Self::Value) {
self.emit().ret_value(value.def(self)).unwrap();
}
fn br(&mut self, dest: Self::BasicBlock) {
self.emit().branch(dest).unwrap()
}
fn cond_br(
&mut self,
cond: Self::Value,
then_llbb: Self::BasicBlock,
else_llbb: Self::BasicBlock,
) {
self.emit()
.branch_conditional(cond.def(self), then_llbb, else_llbb, empty())
.unwrap()
}
fn switch(
&mut self,
v: Self::Value,
else_llbb: Self::BasicBlock,
cases: impl ExactSizeIterator<Item = (u128, Self::BasicBlock)>,
) {
fn construct_8(self_: &Builder<'_, '_>, signed: bool, v: u128) -> Operand {
if v > u8::MAX as u128 {
self_.fatal(&format!(
"Switches to values above u8::MAX not supported: {:?}",
v
))
} else if signed {
// this cast chain can probably be collapsed, but, whatever, be safe
Operand::LiteralInt32(v as u8 as i8 as i32 as u32)
} else {
Operand::LiteralInt32(v as u8 as u32)
}
}
fn construct_16(self_: &Builder<'_, '_>, signed: bool, v: u128) -> Operand {
if v > u16::MAX as u128 {
self_.fatal(&format!(
"Switches to values above u16::MAX not supported: {:?}",
v
))
} else if signed {
Operand::LiteralInt32(v as u16 as i16 as i32 as u32)
} else {
Operand::LiteralInt32(v as u16 as u32)
}
}
fn construct_32(self_: &Builder<'_, '_>, _signed: bool, v: u128) -> Operand {
if v > u32::MAX as u128 {
self_.fatal(&format!(
"Switches to values above u32::MAX not supported: {:?}",
v
))
} else {
Operand::LiteralInt32(v as u32)
}
}
fn construct_64(self_: &Builder<'_, '_>, _signed: bool, v: u128) -> Operand {
if v > u64::MAX as u128 {
self_.fatal(&format!(
"Switches to values above u64::MAX not supported: {:?}",
v
))
} else {
Operand::LiteralInt64(v as u64)
}
}
// pass in signed into the closure to be able to unify closure types
let (signed, construct_case) = match self.lookup_type(v.ty) {
SpirvType::Integer(width, signed) => {
let construct_case = match width {
8 => construct_8,
16 => construct_16,
32 => construct_32,
64 => construct_64,
other => self.fatal(&format!(
"switch selector cannot have width {} (only 8, 16, 32, and 64 bits allowed)",
other
)),
};
(signed, construct_case)
}
other => self.fatal(&format!(
"switch selector cannot have non-integer type {}",
other.debug(v.ty, self)
)),
};
let cases = cases
.map(|(i, b)| (construct_case(self, signed, i), b))
.collect::<Vec<_>>();
self.emit().switch(v.def(self), else_llbb, cases).unwrap()
}
fn invoke(
&mut self,
llfn: Self::Value,
args: &[Self::Value],
then: Self::BasicBlock,
_catch: Self::BasicBlock,
funclet: Option<&Self::Funclet>,
) -> Self::Value {
// Exceptions don't exist, jump directly to then block
let result = self.call(llfn, args, funclet);
self.emit().branch(then).unwrap();
result
}
fn unreachable(&mut self) {
self.emit().unreachable().unwrap()
}
simple_op! {add, i_add}
simple_op! {fadd, f_add}
simple_op! {fadd_fast, f_add} // fast=normal
simple_op! {sub, i_sub}
simple_op! {fsub, f_sub}
simple_op! {fsub_fast, f_sub} // fast=normal
simple_op! {
mul, i_mul,
// HACK(eddyb) `rustc_codegen_ssa` relies on `Builder` methods doing
// on-the-fly constant-folding, for e.g. intrinsics that copy memory.
fold_const {
int(a, b) => a * b
}
}
simple_op! {fmul, f_mul}
simple_op! {fmul_fast, f_mul} // fast=normal
simple_op! {udiv, u_div}
// Note: exactudiv is UB when there's a remainder, so it's valid to implement as a normal div.
// TODO: Can we take advantage of the UB and emit something else?
simple_op! {exactudiv, u_div}
simple_op! {sdiv, s_div}
// Same note and TODO as exactudiv
simple_op! {exactsdiv, s_div}
simple_op! {fdiv, f_div}
simple_op! {fdiv_fast, f_div} // fast=normal
simple_op! {urem, u_mod}
simple_op! {srem, s_rem}
simple_op! {frem, f_rem}
simple_op! {frem_fast, f_rem} // fast=normal
simple_op_unchecked_type! {shl, shift_left_logical}
simple_op_unchecked_type! {lshr, shift_right_logical}
simple_op_unchecked_type! {ashr, shift_right_arithmetic}
simple_op! {unchecked_sadd, i_add} // already unchecked by default
simple_op! {unchecked_uadd, i_add} // already unchecked by default
simple_op! {unchecked_ssub, i_sub} // already unchecked by default
simple_op! {unchecked_usub, i_sub} // already unchecked by default
simple_op! {unchecked_smul, i_mul} // already unchecked by default
simple_op! {unchecked_umul, i_mul} // already unchecked by default
simple_uni_op! {neg, s_negate}
simple_uni_op! {fneg, f_negate}
fn and(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value {
assert_ty_eq!(self, lhs.ty, rhs.ty);
let ty = lhs.ty;
match self.lookup_type(ty) {
SpirvType::Integer(_, _) => {
self.emit()
.bitwise_and(ty, None, lhs.def(self), rhs.def(self))
}
SpirvType::Bool => self
.emit()
.logical_and(ty, None, lhs.def(self), rhs.def(self)),
o => self.fatal(&format!(
"and() not implemented for type {}",
o.debug(ty, self)
)),
}
.unwrap()
.with_type(ty)
}
fn or(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value {
assert_ty_eq!(self, lhs.ty, rhs.ty);
let ty = lhs.ty;
match self.lookup_type(ty) {
SpirvType::Integer(_, _) => {
self.emit()
.bitwise_or(ty, None, lhs.def(self), rhs.def(self))
}
SpirvType::Bool => self
.emit()
.logical_or(ty, None, lhs.def(self), rhs.def(self)),
o => self.fatal(&format!(
"or() not implemented for type {}",
o.debug(ty, self)
)),
}
.unwrap()
.with_type(ty)
}
fn xor(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value {
assert_ty_eq!(self, lhs.ty, rhs.ty);
let ty = lhs.ty;
match self.lookup_type(ty) {
SpirvType::Integer(_, _) => {
self.emit()
.bitwise_xor(ty, None, lhs.def(self), rhs.def(self))
}
SpirvType::Bool => {
self.emit()
.logical_not_equal(ty, None, lhs.def(self), rhs.def(self))
}
o => self.fatal(&format!(
"xor() not implemented for type {}",
o.debug(ty, self)
)),
}
.unwrap()
.with_type(ty)
}
fn not(&mut self, val: Self::Value) -> Self::Value {
match self.lookup_type(val.ty) {
SpirvType::Integer(_, _) => self.emit().not(val.ty, None, val.def(self)),
SpirvType::Bool => {
let true_ = self.constant_bool(self.span(), true);
// intel-compute-runtime doesn't like OpLogicalNot
self.emit()
.logical_not_equal(val.ty, None, val.def(self), true_.def(self))
}
o => self.fatal(&format!(
"not() not implemented for type {}",
o.debug(val.ty, self)
)),
}
.unwrap()
.with_type(val.ty)
}
fn checked_binop(
&mut self,
oop: OverflowOp,
_ty: Ty<'_>,
lhs: Self::Value,
rhs: Self::Value,
) -> (Self::Value, Self::Value) {
let fals = self.constant_bool(self.span(), false);
let result = match oop {
OverflowOp::Add => (self.add(lhs, rhs), fals),
OverflowOp::Sub => (self.sub(lhs, rhs), fals),
OverflowOp::Mul => (self.mul(lhs, rhs), fals),
};
self.zombie(
result.0.def(self),
match oop {
OverflowOp::Add => "checked add is not supported yet",
OverflowOp::Sub => "checked sub is not supported yet",
OverflowOp::Mul => "checked mul is not supported yet",
},
);
result
}
fn from_immediate(&mut self, val: Self::Value) -> Self::Value {
if self.lookup_type(val.ty) == SpirvType::Bool {
let i8 = SpirvType::Integer(8, false).def(self.span(), self);
self.zext(val, i8)
} else {
val
}
}
fn to_immediate_scalar(&mut self, val: Self::Value, scalar: &Scalar) -> Self::Value {
if scalar.is_bool() {
let bool = SpirvType::Bool.def(self.span(), self);
return self.trunc(val, bool);
}
val
}
fn alloca(&mut self, ty: Self::Type, _align: Align) -> Self::Value {
let ptr_ty = SpirvType::Pointer { pointee: ty }.def(self.span(), self);
// "All OpVariable instructions in a function must be the first instructions in the first block."
let mut builder = self.emit();
builder.select_block(Some(0)).unwrap();
let index = {
let block = &builder.module_ref().functions[builder.selected_function().unwrap()]
.blocks[builder.selected_block().unwrap()];
block
.instructions
.iter()
.enumerate()
.find_map(|(index, inst)| {
if inst.class.opcode != Op::Variable {
Some(InsertPoint::FromBegin(index))
} else {
None
}
})
.unwrap_or(InsertPoint::End)
};
// TODO: rspirv doesn't have insert_variable function
let result_id = builder.id();
let inst = Instruction::new(
Op::Variable,
Some(ptr_ty),
Some(result_id),
vec![Operand::StorageClass(StorageClass::Function)],
);
builder.insert_into_block(index, inst).unwrap();
result_id.with_type(ptr_ty)
}
fn dynamic_alloca(&mut self, ty: Self::Type, align: Align) -> Self::Value {
let result = self.alloca(ty, align);
self.err("dynamic alloca is not supported yet");
result
}
fn array_alloca(&mut self, _ty: Self::Type, _len: Self::Value, _align: Align) -> Self::Value {
self.fatal("array alloca not supported yet")
}
fn load(&mut self, ptr: Self::Value, _align: Align) -> Self::Value {
// See comment on `SpirvValueKind::ConstantPointer`
if let Some(value) = ptr.const_ptr_val(self) {
return value;
}
let ty = match self.lookup_type(ptr.ty) {
SpirvType::Pointer { pointee } => pointee,
ty => self.fatal(&format!(
"load called on variable that wasn't a pointer: {:?}",
ty
)),
};
self.emit()
.load(ty, None, ptr.def(self), None, empty())
.unwrap()
.with_type(ty)
}
fn volatile_load(&mut self, ptr: Self::Value) -> Self::Value {
// TODO: Implement this
let result = self.load(ptr, Align::from_bytes(0).unwrap());
self.zombie(result.def(self), "volatile load is not supported yet");
result
}
fn atomic_load(&mut self, ptr: Self::Value, order: AtomicOrdering, _size: Size) -> Self::Value {
let ty = match self.lookup_type(ptr.ty) {
SpirvType::Pointer { pointee } => pointee,
ty => self.fatal(&format!(
"atomic_load called on variable that wasn't a pointer: {:?}",
ty
)),
};
// TODO: Default to device scope
let memory = self.constant_u32(self.span(), Scope::Device as u32);
let semantics = self.ordering_to_semantics_def(order);
let result = self
.emit()
.atomic_load(
ty,
None,
ptr.def(self),
memory.def(self),
semantics.def(self),
)
.unwrap()
.with_type(ty);
self.validate_atomic(ty, result.def(self));
result
}
fn load_operand(
&mut self,
place: PlaceRef<'tcx, Self::Value>,
) -> OperandRef<'tcx, Self::Value> {
if place.layout.is_zst() {
return OperandRef::new_zst(self, place.layout);
}
let val = if let Some(llextra) = place.llextra {
OperandValue::Ref(place.llval, Some(llextra), place.align)
} else if self.cx.is_backend_immediate(place.layout) {
let llval = self.load(place.llval, place.align);
OperandValue::Immediate(self.to_immediate(llval, place.layout))
} else if let Abi::ScalarPair(ref a, ref b) = place.layout.abi {
let b_offset = a.value.size(self).align_to(b.value.align(self).abi);
let mut load = |i, scalar: &Scalar, align| {
let llptr = self.struct_gep(place.llval, i as u64);
let load = self.load(llptr, align);
// WARN! This does not go through to_immediate due to only having a Scalar, not a Ty, but it still does
// whatever to_immediate does!
if scalar.is_bool() {
self.trunc(load, SpirvType::Bool.def(self.span(), self))
} else {
load
}
};
OperandValue::Pair(
load(0, a, place.align),
load(1, b, place.align.restrict_for_offset(b_offset)),
)
} else {
OperandValue::Ref(place.llval, None, place.align)
};
OperandRef {
val,
layout: place.layout,
}
}
/// Called for `Rvalue::Repeat` when the elem is neither a ZST nor optimizable using memset.
fn write_operand_repeatedly(
mut self,
cg_elem: OperandRef<'tcx, Self::Value>,
count: u64,
dest: PlaceRef<'tcx, Self::Value>,
) -> Self {
let zero = self.const_usize(0);
let start = dest.project_index(&mut self, zero).llval;
let align = dest
.align
.restrict_for_offset(dest.layout.field(self.cx(), 0).size);
for i in 0..count {
let current = self.inbounds_gep(start, &[self.const_usize(i)]);
cg_elem.val.store(
&mut self,
PlaceRef::new_sized_aligned(current, cg_elem.layout, align),
);
}
self
}
fn range_metadata(&mut self, _load: Self::Value, _range: Range<u128>) {
// ignore
}
fn nonnull_metadata(&mut self, _load: Self::Value) {
// ignore
}
fn store(&mut self, val: Self::Value, ptr: Self::Value, _align: Align) -> Self::Value {
let ptr_elem_ty = match self.lookup_type(ptr.ty) {
SpirvType::Pointer { pointee } => pointee,
ty => self.fatal(&format!(
"store called on variable that wasn't a pointer: {:?}",
ty
)),
};
assert_ty_eq!(self, ptr_elem_ty, val.ty);
self.emit()
.store(ptr.def(self), val.def(self), None, empty())
.unwrap();
val
}
fn store_with_flags(
&mut self,
val: Self::Value,
ptr: Self::Value,
align: Align,
flags: MemFlags,
) -> Self::Value {
if flags != MemFlags::empty() {
self.err(&format!(
"store_with_flags is not supported yet: {:?}",
flags
));
}
self.store(val, ptr, align)
}
fn atomic_store(
&mut self,
val: Self::Value,
ptr: Self::Value,
order: AtomicOrdering,
_size: Size,
) {
let ptr_elem_ty = match self.lookup_type(ptr.ty) {
SpirvType::Pointer { pointee } => pointee,
ty => self.fatal(&format!(