-
Notifications
You must be signed in to change notification settings - Fork 249
/
Copy pathspecializer.rs
2608 lines (2333 loc) · 102 KB
/
specializer.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
//! Specialize globals (types, constants and module-scoped variables) and functions,
//! to legalize a SPIR-V module representing a "family" of types with a single type,
//! by treating some globals and functions as "generic", inferring minimal sets
//! of "generic parameters", and "monomorphizing" them (i.e. expanding them into
//! one specialized copy per distinctly parameterized instance required).
//!
//! For now, this is only used for pointer type storage classes, because
//! Rust's pointer/reference types don't have an "address space" distinction,
//! and we also wouldn't want users to annotate every single type anyway.
//!
//! # Future plans
//!
//! Recursive data types (using `OpTypeForwardPointer`) are not supported, but
//! here is an outline of how that could work:
//! * groups of mutually-recursive `OpTypeForwardPointer`s are computed via SCCs
//! * each mutual-recursive group gets a single "generic" parameter count, that all
//! pointer types in the group will use, and which is the sum of the "generic"
//! parameters of all the leaves referenced by the pointer types in the group,
//! ignoring the pointer types in the group themselves
//! * once the pointer types have been assigned their "g"eneric parameter count,
//! the non-pointer types in each SCC - i.e. (indirectly) referenced by one of
//! the pointer types in the group, and which in turn (indirectly) references
//! a pointer type in the group - can have their "generic" parameters computed
//! as normal, taking care to record where in the combined lists of "generic"
//! parameters, any of the pointer types in the group show up
//! * each pointer type in the group will "fan out" a copy of its full set of
//! "generic" parameters to every (indirect) mention of any pointer type in
//! the group, using an additional parameter remapping, for which `Generic`:
//! * requires this extra documentation:
//! ```
//! /// The one exception are `OpTypePointer`s involved in recursive data types
//! /// (i.e. they were declared by `OpTypeForwardPointer`s, and their pointees are
//! /// `OpTypeStruct`s that have the same pointer type as a leaf).
//! /// As the pointee `OpTypeStruct` has more parameters than the pointer (each leaf
//! /// use of the same pointer type requires its own copy of the pointer parameters),
//! /// a mapping (`expand_params`) indicates how to create the flattened list.
//! ```
//! * and this extra field:
//! ```
//! /// For every entry in the regular flattened list of parameters expected by
//! /// operands, this contains the parameter index (i.e. `0..self.param_count`)
//! /// to use for that parameter.
//! ///
//! /// For example, to duplicate `5` parameters into `10`, `expand_params`
//! /// would be `[0, 1, 2, 3, 4, 0, 1, 2, 3, 4]`.
//! ///
//! /// See also `Generic` documentation above for why this is needed
//! /// (i.e. to replicate parameters for recursive data types).
//! expand_params: Option<Vec<usize>>,
//! ```
use crate::spirv_type_constraints::{self, InstSig, StorageClassPat, TyListPat, TyPat};
use indexmap::{IndexMap, IndexSet};
use rspirv::dr::{Builder, Function, Instruction, Module, Operand};
use rspirv::spirv::{Op, StorageClass, Word};
use rustc_data_structures::captures::Captures;
use smallvec::SmallVec;
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::convert::{TryFrom, TryInto};
use std::ops::{Range, RangeTo};
use std::{fmt, io, iter, mem, slice};
// FIXME(eddyb) move this elsewhere.
struct FmtBy<F: Fn(&mut fmt::Formatter<'_>) -> fmt::Result>(F);
impl<F: Fn(&mut fmt::Formatter<'_>) -> fmt::Result> fmt::Debug for FmtBy<F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0(f)
}
}
impl<F: Fn(&mut fmt::Formatter<'_>) -> fmt::Result> fmt::Display for FmtBy<F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0(f)
}
}
pub trait Specialization {
/// Return `true` if the specializer should replace every occurence of
/// `operand` with some other inferred `Operand`.
fn specialize_operand(&self, operand: &Operand) -> bool;
/// The operand that should be used to replace unresolved inference variables,
/// i.e. the uses of operands for which `specialize_operand` returns `true`,
/// but which none of the instructions in the same SPIR-V function require
/// any particular concrete value or relate it to the function's signature,
/// so an arbitrary choice can be made (as long as it's valid SPIR-V etc.).
fn concrete_fallback(&self) -> Operand;
}
/// Helper to avoid needing an `impl` of `Specialization`, while allowing the rest
/// of this module to use `Specialization` (instead of `Fn(&Operand) -> bool`).
pub struct SimpleSpecialization<SO: Fn(&Operand) -> bool> {
pub specialize_operand: SO,
pub concrete_fallback: Operand,
}
impl<SO: Fn(&Operand) -> bool> Specialization for SimpleSpecialization<SO> {
fn specialize_operand(&self, operand: &Operand) -> bool {
(self.specialize_operand)(operand)
}
fn concrete_fallback(&self) -> Operand {
self.concrete_fallback.clone()
}
}
pub fn specialize(module: Module, specialization: impl Specialization) -> Module {
// FIXME(eddyb) use `log`/`tracing` instead.
let debug = std::env::var("SPECIALIZER_DEBUG").is_ok();
let dump_instances = std::env::var("SPECIALIZER_DUMP_INSTANCES").ok();
let mut debug_names = HashMap::new();
if debug || dump_instances.is_some() {
debug_names = module
.debugs
.iter()
.filter(|inst| inst.class.opcode == Op::Name)
.map(|inst| {
(
inst.operands[0].unwrap_id_ref(),
inst.operands[1].unwrap_literal_string().to_string(),
)
})
.collect();
}
let mut specializer = Specializer {
specialization,
debug,
debug_names,
generics: IndexMap::new(),
int_consts: HashMap::new(),
};
specializer.collect_generics(&module);
let call_graph = CallGraph::collect(&module);
let mut non_generic_replacements = vec![];
for func_idx in call_graph.post_order() {
if let Some(replacements) = specializer.infer_function(&module.functions[func_idx]) {
non_generic_replacements.push((func_idx, replacements));
}
}
let mut expander = Expander::new(&specializer, module);
// For non-"generic" functions, we can apply `replacements` right away,
// though not before finishing inference for all functions first
// (because `expander` needs to borrow `specializer` immutably).
if debug {
eprintln!("non-generic replacements:");
}
for (func_idx, replacements) in non_generic_replacements {
let mut func = mem::replace(
&mut expander.builder.module_mut().functions[func_idx],
Function::new(),
);
if debug {
let empty = replacements.with_instance.is_empty()
&& replacements.with_concrete_or_param.is_empty();
if !empty {
eprintln!(" in %{}:", func.def_id().unwrap());
}
}
for (loc, operand) in
replacements.to_concrete(&[], |instance| expander.alloc_instance_id(instance))
{
if debug {
eprintln!(" {} -> {:?}", operand, loc);
}
func.index_set(loc, operand.into());
}
expander.builder.module_mut().functions[func_idx] = func;
}
expander.propagate_instances();
if let Some(path) = dump_instances {
expander
.dump_instances(&mut std::fs::File::create(path).unwrap())
.unwrap();
}
expander.expand_module()
}
// FIXME(eddyb) use newtyped indices and `IndexVec`.
type FuncIdx = usize;
struct CallGraph {
entry_points: IndexSet<FuncIdx>,
/// `callees[i].contains(j)` implies `functions[i]` calls `functions[j]`.
callees: Vec<IndexSet<FuncIdx>>,
}
impl CallGraph {
fn collect(module: &Module) -> Self {
let func_id_to_idx: HashMap<_, _> = module
.functions
.iter()
.enumerate()
.map(|(i, func)| (func.def_id().unwrap(), i))
.collect();
let entry_points = module
.entry_points
.iter()
.map(|entry| {
assert_eq!(entry.class.opcode, Op::EntryPoint);
func_id_to_idx[&entry.operands[1].unwrap_id_ref()]
})
.collect();
let callees = module
.functions
.iter()
.map(|func| {
func.all_inst_iter()
.filter(|inst| inst.class.opcode == Op::FunctionCall)
.map(|inst| func_id_to_idx[&inst.operands[0].unwrap_id_ref()])
.collect()
})
.collect();
Self {
entry_points,
callees,
}
}
/// Order functions using a post-order traversal, i.e. callees before callers.
// FIXME(eddyb) replace this with `rustc_data_structures::graph::iterate`
// (or similar).
fn post_order(&self) -> Vec<FuncIdx> {
let num_funcs = self.callees.len();
// FIXME(eddyb) use a proper bitset.
let mut visited = vec![false; num_funcs];
let mut post_order = Vec::with_capacity(num_funcs);
// Visit the call graph with entry points as roots.
for &entry in &self.entry_points {
self.post_order_step(entry, &mut visited, &mut post_order);
}
// Also visit any functions that were not reached from entry points
// (they might be dead but they should be processed nonetheless).
for func in 0..num_funcs {
if !visited[func] {
self.post_order_step(func, &mut visited, &mut post_order);
}
}
post_order
}
fn post_order_step(&self, func: FuncIdx, visited: &mut [bool], post_order: &mut Vec<FuncIdx>) {
if visited[func] {
return;
}
visited[func] = true;
for &callee in &self.callees[func] {
self.post_order_step(callee, visited, post_order)
}
post_order.push(func);
}
}
// HACK(eddyb) `Copy` version of `Operand` that only includes the cases that
// are relevant to the inference algorithm (and is also smaller).
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum CopyOperand {
IdRef(Word),
StorageClass(StorageClass),
}
#[derive(Debug)]
struct NotSupportedAsCopyOperand(Operand);
impl TryFrom<&Operand> for CopyOperand {
type Error = NotSupportedAsCopyOperand;
fn try_from(operand: &Operand) -> Result<Self, Self::Error> {
match *operand {
Operand::IdRef(id) => Ok(Self::IdRef(id)),
Operand::StorageClass(s) => Ok(Self::StorageClass(s)),
_ => Err(NotSupportedAsCopyOperand(operand.clone())),
}
}
}
impl From<CopyOperand> for Operand {
fn from(op: CopyOperand) -> Self {
match op {
CopyOperand::IdRef(id) => Self::IdRef(id),
CopyOperand::StorageClass(s) => Self::StorageClass(s),
}
}
}
impl fmt::Display for CopyOperand {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::IdRef(id) => write!(f, "%{}", id),
Self::StorageClass(s) => write!(f, "{:?}", s),
}
}
}
/// The "value" of a `Param`/`InferVar`, if we know anything about it.
// FIXME(eddyb) find a more specific name.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
enum Value<T> {
/// The value of this `Param`/`InferVar` is completely known.
Unknown,
/// The value of this `Param`/`InferVar` is known to be a specific `Operand`.
Known(CopyOperand),
/// The value of this `Param`/`InferVar` is the same as another `Param`/`InferVar`.
///
/// For consistency, and to allow some `Param` <-> `InferVar` mapping,
/// all cases of `values[y] == Value::SameAs(x)` should have `x < y`,
/// i.e. "newer" variables must be redirected to "older" ones.
SameAs(T),
}
impl<T> Value<T> {
fn map_var<U>(self, f: impl FnOnce(T) -> U) -> Value<U> {
match self {
Value::Unknown => Value::Unknown,
Value::Known(o) => Value::Known(o),
Value::SameAs(var) => Value::SameAs(f(var)),
}
}
}
/// Newtype'd "generic" parameter index.
// FIXME(eddyb) use `rustc_index` for this instead.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct Param(u32);
impl fmt::Display for Param {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "${}", self.0)
}
}
impl Param {
// HACK(eddyb) this works around `Range<Param>` not being iterable
// because `Param` doesn't implement the (unstable) `Step` trait.
fn range_iter(range: &Range<Self>) -> impl Iterator<Item = Self> + Clone {
(range.start.0..range.end.0).map(Self)
}
}
/// A specific instance of a "generic" global/function.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct Instance<GA> {
generic_id: Word,
generic_args: GA,
}
impl<GA> Instance<GA> {
fn as_ref(&self) -> Instance<&GA> {
Instance {
generic_id: self.generic_id,
generic_args: &self.generic_args,
}
}
fn map_generic_args<T, U, GA2>(self, f: impl FnMut(T) -> U) -> Instance<GA2>
where
GA: IntoIterator<Item = T>,
GA2: std::iter::FromIterator<U>,
{
Instance {
generic_id: self.generic_id,
generic_args: self.generic_args.into_iter().map(f).collect(),
}
}
// FIXME(eddyb) implement `Step` for `Param` and `InferVar` instead.
fn display<'a, T: fmt::Display, GAI: Iterator<Item = T> + Clone>(
&'a self,
f: impl FnOnce(&'a GA) -> GAI,
) -> impl fmt::Display {
let &Self {
generic_id,
ref generic_args,
} = self;
let generic_args_iter = f(generic_args);
FmtBy(move |f| {
write!(f, "%{}<", generic_id)?;
for (i, arg) in generic_args_iter.clone().enumerate() {
if i != 0 {
write!(f, ", ")?;
}
write!(f, "{}", arg)?;
}
write!(f, ">")
})
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum InstructionLocation {
Module,
FnParam(usize),
FnBody {
/// Block index within a function.
block_idx: usize,
/// Instruction index within the block with index `block_idx`.
inst_idx: usize,
},
}
trait OperandIndexGetSet<I> {
fn index_get(&self, index: I) -> Operand;
fn index_set(&mut self, index: I, operand: Operand);
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum OperandIdx {
ResultType,
Input(usize),
}
impl OperandIndexGetSet<OperandIdx> for Instruction {
fn index_get(&self, idx: OperandIdx) -> Operand {
match idx {
OperandIdx::ResultType => Operand::IdRef(self.result_type.unwrap()),
OperandIdx::Input(i) => self.operands[i].clone(),
}
}
fn index_set(&mut self, idx: OperandIdx, operand: Operand) {
match idx {
OperandIdx::ResultType => self.result_type = Some(operand.unwrap_id_ref()),
OperandIdx::Input(i) => self.operands[i] = operand,
}
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
struct OperandLocation {
inst_loc: InstructionLocation,
operand_idx: OperandIdx,
}
impl OperandIndexGetSet<OperandLocation> for Instruction {
fn index_get(&self, loc: OperandLocation) -> Operand {
assert_eq!(loc.inst_loc, InstructionLocation::Module);
self.index_get(loc.operand_idx)
}
fn index_set(&mut self, loc: OperandLocation, operand: Operand) {
assert_eq!(loc.inst_loc, InstructionLocation::Module);
self.index_set(loc.operand_idx, operand);
}
}
impl OperandIndexGetSet<OperandLocation> for Function {
fn index_get(&self, loc: OperandLocation) -> Operand {
let inst = match loc.inst_loc {
InstructionLocation::Module => self.def.as_ref().unwrap(),
InstructionLocation::FnParam(i) => &self.parameters[i],
InstructionLocation::FnBody {
block_idx,
inst_idx,
} => &self.blocks[block_idx].instructions[inst_idx],
};
inst.index_get(loc.operand_idx)
}
fn index_set(&mut self, loc: OperandLocation, operand: Operand) {
let inst = match loc.inst_loc {
InstructionLocation::Module => self.def.as_mut().unwrap(),
InstructionLocation::FnParam(i) => &mut self.parameters[i],
InstructionLocation::FnBody {
block_idx,
inst_idx,
} => &mut self.blocks[block_idx].instructions[inst_idx],
};
inst.index_set(loc.operand_idx, operand);
}
}
// FIXME(eddyb) this is a bit like `Value<Param>` but more explicit,
// and the name isn't too nice, but at least it's very clear.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
enum ConcreteOrParam {
Concrete(CopyOperand),
Param(Param),
}
impl ConcreteOrParam {
/// Replace `Param(i)` with `generic_args[i]` while preserving `Concrete`.
fn apply_generic_args(self, generic_args: &[CopyOperand]) -> CopyOperand {
match self {
Self::Concrete(x) => x,
Self::Param(Param(i)) => generic_args[i as usize],
}
}
}
#[derive(Debug)]
struct Replacements {
/// Operands that need to be replaced with instances of "generic" globals.
/// Keyed by instance to optimize for few instances used many times.
// FIXME(eddyb) fine-tune the length of `SmallVec<[_; 4]>` here.
with_instance: IndexMap<Instance<SmallVec<[ConcreteOrParam; 4]>>, Vec<OperandLocation>>,
/// Operands that need to be replaced with a concrete operand or a parameter.
with_concrete_or_param: Vec<(OperandLocation, ConcreteOrParam)>,
}
impl Replacements {
/// Apply `generic_args` to all the `ConcreteOrParam`s in this `Replacements`
/// (i.e. replacing `Param(i)` with `generic_args[i]`), producing a stream of
/// "replace the operand at `OperandLocation` with this concrete `CopyOperand`".
/// The `concrete_instance_id` closure should look up and/or allocate an ID
/// for a specific concrete `Instance`.
fn to_concrete<'a>(
&'a self,
generic_args: &'a [CopyOperand],
mut concrete_instance_id: impl FnMut(Instance<SmallVec<[CopyOperand; 4]>>) -> Word + 'a,
) -> impl Iterator<Item = (OperandLocation, CopyOperand)> + 'a {
self.with_instance
.iter()
.flat_map(move |(instance, locations)| {
let concrete = CopyOperand::IdRef(concrete_instance_id(
instance
.as_ref()
.map_generic_args(|x| x.apply_generic_args(generic_args)),
));
locations.iter().map(move |&loc| (loc, concrete))
})
.chain(
self.with_concrete_or_param
.iter()
.map(move |&(loc, x)| (loc, x.apply_generic_args(generic_args))),
)
}
}
/// Computed "generic" shape for a SPIR-V global/function. In the interest of efficient
/// representation, the parameters of operands that are themselves "generic",
/// are concatenated by default, i.e. parameters come from disjoint leaves.
///
/// As an example, for `%T = OpTypeStruct %A %B`, if `%A` and `%B` have 2 and 3
/// parameters, respectively, `%T` will have `A0, A1, B0, B1, B2` as parameters.
struct Generic {
param_count: u32,
/// Defining instruction for this global (`OpType...`, `OpConstant...`, etc.)
/// or function (`OpFunction`).
// FIXME(eddyb) consider using `SmallVec` for the operands, or converting
// the operands into something more like `InferOperand`, but that would
// complicate `InferOperandList`, which has to be able to iterate them.
def: Instruction,
/// `param_values[p]` constrains what "generic" args `Param(p)` could take.
/// This is only present if any constraints were inferred from the defining
/// instruction of a global, or the body of a function. Inference performed
/// after `collect_generics` (e.g. from instructions in function bodies) is
/// monotonic, i.e. it may only introduce more constraints, not remove any.
// FIXME(eddyb) use `rustc_index`'s `IndexVec` for this.
param_values: Option<Vec<Value<Param>>>,
/// Operand replacements that need to be performed on the defining instruction
/// of a global, or an entire function (including all instructions in its body),
/// in order to expand an instance of it.
replacements: Replacements,
}
struct Specializer<S: Specialization> {
specialization: S,
// FIXME(eddyb) use `log`/`tracing` instead.
debug: bool,
// HACK(eddyb) if debugging is requested, this is used to quickly get `OpName`s.
debug_names: HashMap<Word, String>,
// FIXME(eddyb) compact SPIR-V IDs to allow flatter maps.
generics: IndexMap<Word, Generic>,
/// Integer `OpConstant`s (i.e. containing a `LiteralInt32`), to be used
/// for interpreting `TyPat::IndexComposite` (such as for `OpAccessChain`).
int_consts: HashMap<Word, u32>,
}
impl<S: Specialization> Specializer<S> {
/// Returns the number of "generic" parameters `operand` "takes", either
/// because it's specialized by, or it refers to a "generic" global/function.
/// In the latter case, the `&Generic` for that global/function is also returned.
fn params_needed_by(&self, operand: &Operand) -> (u32, Option<&Generic>) {
if self.specialization.specialize_operand(operand) {
// Each operand we specialize by is one leaf "generic" parameter.
(1, None)
} else if let Operand::IdRef(id) = operand {
self.generics
.get(id)
.map_or((0, None), |generic| (generic.param_count, Some(generic)))
} else {
(0, None)
}
}
fn collect_generics(&mut self, module: &Module) {
// Process all defining instructions for globals (types, constants,
// and module-scoped variables), and functions' `OpFunction` instructions,
// but note that for `OpFunction`s only the signature is considered,
// actual inference based on bodies happens later, in `infer_function`.
let types_global_values_and_functions = module
.types_global_values
.iter()
.chain(module.functions.iter().filter_map(|f| f.def.as_ref()));
let mut forward_declared_pointers = HashSet::new();
for inst in types_global_values_and_functions {
let result_id = inst.result_id.unwrap_or_else(|| {
unreachable!(
"Op{:?} is in `types_global_values` but not have a result ID",
inst.class.opcode
);
});
if inst.class.opcode == Op::TypeForwardPointer {
forward_declared_pointers.insert(inst.operands[0].unwrap_id_ref());
}
if forward_declared_pointers.remove(&result_id) {
// HACK(eddyb) this is a forward-declared pointer, pretend
// it's not "generic" at all to avoid breaking the rest of
// the logic - see module-level docs for how this should be
// handled in the future to support recursive data types.
assert_eq!(inst.class.opcode, Op::TypePointer);
continue;
}
// Record all integer `OpConstant`s (used for `IndexComposite`).
if inst.class.opcode == Op::Constant {
if let Operand::LiteralInt32(x) = inst.operands[0] {
self.int_consts.insert(result_id, x);
}
}
// Instantiate `inst` in a fresh inference context, to determine
// how many parameters it needs, and how they might be constrained.
let (param_count, param_values, replacements) = {
let mut infer_cx = InferCx::new(self);
infer_cx.instantiate_instruction(inst, InstructionLocation::Module);
let param_count = infer_cx.infer_var_values.len() as u32;
// FIXME(eddyb) dedup this with `infer_function`.
let param_values = infer_cx
.infer_var_values
.iter()
.map(|v| v.map_var(|InferVar(i)| Param(i)));
// Only allocate `param_values` if they constrain parameters.
let param_values = if param_values.clone().any(|v| v != Value::Unknown) {
Some(param_values.collect())
} else {
None
};
(
param_count,
param_values,
infer_cx.into_replacements(..Param(param_count)),
)
};
// Inference variables become "generic" parameters.
if param_count > 0 {
self.generics.insert(
result_id,
Generic {
param_count,
def: inst.clone(),
param_values,
replacements,
},
);
}
}
}
/// Perform inference across the entire definition of `func`, including all
/// the instructions in its body, and either store the resulting `Replacements`
/// in its `Generic` (if `func` is "generic"), or return them otherwise.
fn infer_function(&mut self, func: &Function) -> Option<Replacements> {
let func_id = func.def_id().unwrap();
let param_count = self
.generics
.get(&func_id)
.map_or(0, |generic| generic.param_count);
let (param_values, replacements) = {
let mut infer_cx = InferCx::new(self);
infer_cx.instantiate_function(func);
// FIXME(eddyb) dedup this with `collect_generics`.
let param_values = infer_cx.infer_var_values[..param_count as usize]
.iter()
.map(|v| v.map_var(|InferVar(i)| Param(i)));
// Only allocate `param_values` if they constrain parameters.
let param_values = if param_values.clone().any(|v| v != Value::Unknown) {
Some(param_values.collect())
} else {
None
};
(
param_values,
infer_cx.into_replacements(..Param(param_count)),
)
};
if let Some(generic) = self.generics.get_mut(&func_id) {
// All constraints `func` could have from `collect_generics`
// would have to come from its `OpTypeFunction`, but types don't have
// internal constraints like e.g. `OpConstant*` and `OpVariable` do.
assert!(generic.param_values.is_none());
generic.param_values = param_values;
generic.replacements = replacements;
None
} else {
Some(replacements)
}
}
}
/// Newtype'd inference variable index.
// FIXME(eddyb) use `rustc_index` for this instead.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct InferVar(u32);
impl fmt::Display for InferVar {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "?{}", self.0)
}
}
impl InferVar {
// HACK(eddyb) this works around `Range<InferVar>` not being iterable
// because `InferVar` doesn't implement the (unstable) `Step` trait.
fn range_iter(range: &Range<Self>) -> impl Iterator<Item = Self> + Clone {
(range.start.0..range.end.0).map(Self)
}
}
struct InferCx<'a, S: Specialization> {
specializer: &'a Specializer<S>,
/// `infer_var_values[i]` holds the current state of `InferVar(i)`.
/// Each inference variable starts out as `Unknown`, may become `SameAs`
/// pointing to another inference variable, but eventually inference must
/// result in `Known` values (i.e. concrete `Operand`s).
// FIXME(eddyb) use `rustc_index`'s `IndexVec` for this.
infer_var_values: Vec<Value<InferVar>>,
/// Instantiated *Result Type* of each instruction that has any `InferVar`s,
/// used when an instruction's result is an input to a later instruction.
///
/// Note that for consistency, for `OpFunction` this contains *Function Type*
/// instead of *Result Type*, which is inexplicably specified as:
/// > *Result Type* must be the same as the *Return Type* declared in *Function Type*
type_of_result: IndexMap<Word, InferOperand>,
/// Operands that need to be replaced with instances of "generic" globals/functions
/// (taking as "generic" arguments the results of inference).
instantiated_operands: Vec<(OperandLocation, Instance<Range<InferVar>>)>,
/// Operands that need to be replaced with results of inference.
inferred_operands: Vec<(OperandLocation, InferVar)>,
}
impl<'a, S: Specialization> InferCx<'a, S> {
fn new(specializer: &'a Specializer<S>) -> Self {
InferCx {
specializer,
infer_var_values: vec![],
type_of_result: IndexMap::new(),
instantiated_operands: vec![],
inferred_operands: vec![],
}
}
}
#[derive(Clone, Debug, PartialEq)]
enum InferOperand {
Unknown,
Var(InferVar),
Concrete(CopyOperand),
Instance(Instance<Range<InferVar>>),
}
impl InferOperand {
/// Construct an `InferOperand` based on whether `operand` refers to some
/// "generic" definition, or we're specializing by it.
/// Also returns the remaining inference variables, not used by this operand.
fn from_operand_and_generic_args(
operand: &Operand,
generic_args: Range<InferVar>,
cx: &InferCx<'_, impl Specialization>,
) -> (Self, Range<InferVar>) {
let (needed, generic) = cx.specializer.params_needed_by(operand);
let split = InferVar(generic_args.start.0 + needed);
let (generic_args, rest) = (generic_args.start..split, split..generic_args.end);
(
if generic.is_some() {
Self::Instance(Instance {
generic_id: operand.unwrap_id_ref(),
generic_args,
})
} else if needed == 0 {
CopyOperand::try_from(operand).map_or(Self::Unknown, Self::Concrete)
} else {
assert_eq!(needed, 1);
Self::Var(generic_args.start)
},
rest,
)
}
fn display_with_infer_var_values<'a>(
&'a self,
infer_var_value: impl Fn(InferVar) -> Value<InferVar> + Copy + 'a,
) -> impl fmt::Display + '_ {
FmtBy(move |f| {
let var_with_value = |v| {
FmtBy(move |f| {
write!(f, "{}", v)?;
match infer_var_value(v) {
Value::Unknown => Ok(()),
Value::Known(o) => write!(f, " = {}", o),
Value::SameAs(v) => write!(f, " = {}", v),
}
})
};
match self {
Self::Unknown => write!(f, "_"),
Self::Var(v) => write!(f, "{}", var_with_value(*v)),
Self::Concrete(o) => write!(f, "{}", o),
Self::Instance(instance) => write!(
f,
"{}",
instance.display(|generic_args| {
InferVar::range_iter(generic_args).map(var_with_value)
})
),
}
})
}
fn display_with_infer_cx<'a>(
&'a self,
cx: &'a InferCx<'_, impl Specialization>,
) -> impl fmt::Display + '_ {
self.display_with_infer_var_values(move |v| {
// HACK(eddyb) can't use `resolve_infer_var` because that mutates
// `InferCx` (for the "path compression" union-find optimization).
let get = |v: InferVar| cx.infer_var_values[v.0 as usize];
let mut value = get(v);
while let Value::SameAs(v) = value {
let next = get(v);
if next == Value::Unknown {
break;
}
value = next;
}
value
})
}
}
impl fmt::Display for InferOperand {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.display_with_infer_var_values(|_| Value::Unknown)
.fmt(f)
}
}
/// How to filter and/or map the operands in an `InferOperandList`, while iterating.
///
/// Having this in `InferOperandList` itself, instead of using iterator combinators,
/// allows storing `InferOperandList`s directly in `Match`, for `TyPatList` matches.
#[derive(Copy, Clone, PartialEq, Eq)]
enum InferOperandListTransform {
/// The list is the result of keeping only ID operands, and mapping them to
/// their types (or `InferOperand::Unknown` for non-value operands, or
/// value operands which don't have a "generic" type).
///
/// This is used to match against the `inputs` `TyListPat` of `InstSig`.
TypeOfId,
}
#[derive(Clone, PartialEq)]
struct InferOperandList<'a> {
operands: &'a [Operand],
/// Joined ranges of all `InferVar`s needed by individual `Operand`s,
/// either for `InferOperand::Instance` or `InferOperand::Var`.
all_generic_args: Range<InferVar>,
transform: Option<InferOperandListTransform>,
}
impl<'a> InferOperandList<'a> {
fn split_first(
&self,
cx: &InferCx<'_, impl Specialization>,
) -> Option<(InferOperand, InferOperandList<'a>)> {
let mut list = self.clone();
loop {
let (first_operand, rest) = list.operands.split_first()?;
list.operands = rest;
let (first, rest_args) = InferOperand::from_operand_and_generic_args(
first_operand,
list.all_generic_args.clone(),
cx,
);
list.all_generic_args = rest_args;
// Maybe filter this operand, but only *after* consuming the "generic" args for it.
match self.transform {
None => {}
// Skip a non-ID operand.
Some(InferOperandListTransform::TypeOfId) => {
if first_operand.id_ref_any().is_none() {
continue;
}
}
}
// Maybe replace this operand with a different one.
let first = match self.transform {
None => first,
// Map `first` to its type.
Some(InferOperandListTransform::TypeOfId) => match first {
InferOperand::Concrete(CopyOperand::IdRef(id)) => cx
.type_of_result
.get(&id)
.cloned()
.unwrap_or(InferOperand::Unknown),
InferOperand::Unknown | InferOperand::Var(_) | InferOperand::Concrete(_) => {
InferOperand::Unknown
}
InferOperand::Instance(instance) => {
let generic = &cx.specializer.generics[&instance.generic_id];
// HACK(eddyb) work around the inexplicable fact that `OpFunction` is
// specified with a *Result Type* that isn't the type of its *Result*:
// > *Result Type* must be the same as the *Return Type* declared in *Function Type*
// So we use *Function Type* instead as the type of its *Result*, and
// we are helped by `instantiate_instruction`, which ensures that the
// "generic" args we have are specifically meant for *Function Type*.
let type_of_result = match generic.def.class.opcode {
Op::Function => Some(generic.def.operands[1].unwrap_id_ref()),
_ => generic.def.result_type,
};
match type_of_result {
Some(type_of_result) => {
InferOperand::from_operand_and_generic_args(
&Operand::IdRef(type_of_result),
instance.generic_args,
cx,
)
.0
}
None => InferOperand::Unknown,
}
}
},
};
return Some((first, list));
}
}
fn iter<'b>(
&self,
cx: &'b InferCx<'_, impl Specialization>,
) -> impl Iterator<Item = InferOperand> + 'b
where
'a: 'b,
{
let mut list = self.clone();
iter::from_fn(move || {
let (next, rest) = list.split_first(cx)?;
list = rest;