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
//! Dead code elimination
//!
//! This pass removes any instruction that doesn't affect the module. It does so by considering all
//! `OpEntryPoint` instructions to be "rooted", and then everything a rooted instruction touches is
//! also rooted (done transitively). Then, any instruction not rooted is removed. It gets a little
//! weird with things like `OpDecorate`, where the reference is reversed - an `OpDecorate` that
//! *references* a rooted thing is also rooted, not the other way around - but that's the basic
//! concept.

use rspirv::dr::{Function, Instruction, Module, Operand};
use rspirv::spirv::{Decoration, LinkageType, Op, StorageClass, Word};
use rustc_data_structures::fx::FxIndexSet;

pub fn dce(module: &mut Module) {
    let mut rooted = collect_roots(module);
    while spread_roots(module, &mut rooted) {}
    kill_unrooted(module, &rooted);
}

pub fn collect_roots(module: &Module) -> FxIndexSet<Word> {
    let mut rooted = FxIndexSet::default();

    for inst in &module.entry_points {
        root(inst, &mut rooted);
    }

    // NOTE(eddyb) such "link exports" roots are only relevant when `Options`'s
    // `keep_link_export`s field is used to request that `Export`s are left in
    // (primarily for unit testing - see also its doc comment).
    for inst in &module.annotations {
        if inst.class.opcode == Op::Decorate
            && inst.operands[1].unwrap_decoration() == Decoration::LinkageAttributes
            && inst.operands[3].unwrap_linkage_type() == LinkageType::Export
        {
            root(inst, &mut rooted);
        }
    }

    rooted
}

// Exactly the same as Function::all_inst_iter, except return type is `impl DoubleEndedIterator`
// instead of `impl Iterator`
fn all_inst_iter(func: &Function) -> impl DoubleEndedIterator<Item = &Instruction> {
    func.def
        .iter()
        .chain(func.parameters.iter())
        .chain(
            func.blocks
                .iter()
                .flat_map(|b| b.label.iter().chain(b.instructions.iter())),
        )
        .chain(func.end.iter())
}

fn spread_roots(module: &Module, rooted: &mut FxIndexSet<Word>) -> bool {
    let mut any = false;
    for inst in module.global_inst_iter() {
        if let Some(id) = inst.result_id {
            if rooted.contains(&id) {
                any |= root(inst, rooted);
            }
        }
    }
    for func in &module.functions {
        if rooted.contains(&func.def_id().unwrap()) {
            // NB (Mobius 2021) - since later insts are much more likely to reference
            // earlier insts, by reversing the iteration order, we're more likely to root the
            // entire relevant function at once.
            // See https://github.com/EmbarkStudios/rust-gpu/pull/691#discussion_r681477091
            for inst in all_inst_iter(func).rev() {
                if !instruction_is_pure(inst) {
                    any |= root(inst, rooted);
                } else if let Some(id) = inst.result_id {
                    if rooted.contains(&id) {
                        any |= root(inst, rooted);
                    }
                }
            }
        }
    }
    any
}

fn root(inst: &Instruction, rooted: &mut FxIndexSet<Word>) -> bool {
    let mut any = false;
    if let Some(id) = inst.result_type {
        any |= rooted.insert(id);
    }
    for op in &inst.operands {
        if let Some(id) = op.id_ref_any() {
            any |= rooted.insert(id);
        }
    }
    any
}

fn is_rooted(inst: &Instruction, rooted: &FxIndexSet<Word>) -> bool {
    if let Some(result_id) = inst.result_id {
        rooted.contains(&result_id)
    } else {
        // For things like OpDecorate which apply attributes to rooted things, but are not
        // referenced by roots
        inst.operands
            .iter()
            .any(|op| op.id_ref_any().map_or(false, |w| rooted.contains(&w)))
    }
}

fn kill_unrooted(module: &mut Module, rooted: &FxIndexSet<Word>) {
    module
        .ext_inst_imports
        .retain(|inst| is_rooted(inst, rooted));
    module
        .execution_modes
        .retain(|inst| is_rooted(inst, rooted));
    module
        .debug_string_source
        .retain(|inst| is_rooted(inst, rooted));
    module.debug_names.retain(|inst| is_rooted(inst, rooted));
    module
        .debug_module_processed
        .retain(|inst| is_rooted(inst, rooted));
    module.annotations.retain(|inst| is_rooted(inst, rooted));
    module
        .types_global_values
        .retain(|inst| is_rooted(inst, rooted));
    module
        .functions
        .retain(|f| is_rooted(f.def.as_ref().unwrap(), rooted));
    for fun in &mut module.functions {
        for block in &mut fun.blocks {
            block
                .instructions
                .retain(|inst| !instruction_is_pure(inst) || is_rooted(inst, rooted));
        }
    }
}

pub fn dce_phi(func: &mut Function) {
    let mut used = FxIndexSet::default();
    loop {
        let mut changed = false;
        for inst in func.all_inst_iter() {
            if inst.class.opcode != Op::Phi || used.contains(&inst.result_id.unwrap()) {
                for op in &inst.operands {
                    if let Some(id) = op.id_ref_any() {
                        changed |= used.insert(id);
                    }
                }
            }
        }
        if !changed {
            break;
        }
    }
    for block in &mut func.blocks {
        block
            .instructions
            .retain(|inst| inst.class.opcode != Op::Phi || used.contains(&inst.result_id.unwrap()));
    }
}

fn instruction_is_pure(inst: &Instruction) -> bool {
    use Op::*;
    match inst.class.opcode {
        Nop
        | Undef
        | ConstantTrue
        | ConstantFalse
        | Constant
        | ConstantComposite
        | ConstantSampler
        | ConstantNull
        | AccessChain
        | InBoundsAccessChain
        | PtrAccessChain
        | ArrayLength
        | InBoundsPtrAccessChain
        | CompositeConstruct
        | CompositeExtract
        | CompositeInsert
        | CopyObject
        | Transpose
        | ConvertFToU
        | ConvertFToS
        | ConvertSToF
        | ConvertUToF
        | UConvert
        | SConvert
        | FConvert
        | QuantizeToF16
        | ConvertPtrToU
        | SatConvertSToU
        | SatConvertUToS
        | ConvertUToPtr
        | PtrCastToGeneric
        | GenericCastToPtr
        | GenericCastToPtrExplicit
        | Bitcast
        | SNegate
        | FNegate
        | IAdd
        | FAdd
        | ISub
        | FSub
        | IMul
        | FMul
        | UDiv
        | SDiv
        | FDiv
        | UMod
        | SRem
        | SMod
        | FRem
        | FMod
        | VectorTimesScalar
        | MatrixTimesScalar
        | VectorTimesMatrix
        | MatrixTimesVector
        | MatrixTimesMatrix
        | OuterProduct
        | Dot
        | IAddCarry
        | ISubBorrow
        | UMulExtended
        | SMulExtended
        | Any
        | All
        | IsNan
        | IsInf
        | IsFinite
        | IsNormal
        | SignBitSet
        | LessOrGreater
        | Ordered
        | Unordered
        | LogicalEqual
        | LogicalNotEqual
        | LogicalOr
        | LogicalAnd
        | LogicalNot
        | Select
        | IEqual
        | INotEqual
        | UGreaterThan
        | SGreaterThan
        | UGreaterThanEqual
        | SGreaterThanEqual
        | ULessThan
        | SLessThan
        | ULessThanEqual
        | SLessThanEqual
        | FOrdEqual
        | FUnordEqual
        | FOrdNotEqual
        | FUnordNotEqual
        | FOrdLessThan
        | FUnordLessThan
        | FOrdGreaterThan
        | FUnordGreaterThan
        | FOrdLessThanEqual
        | FUnordLessThanEqual
        | FOrdGreaterThanEqual
        | FUnordGreaterThanEqual
        | ShiftRightLogical
        | ShiftRightArithmetic
        | ShiftLeftLogical
        | BitwiseOr
        | BitwiseXor
        | BitwiseAnd
        | Not
        | BitFieldInsert
        | BitFieldSExtract
        | BitFieldUExtract
        | BitReverse
        | BitCount
        | Phi
        | SizeOf
        | CopyLogical
        | PtrEqual
        | PtrNotEqual
        | PtrDiff => true,
        Variable => inst.operands.get(0) == Some(&Operand::StorageClass(StorageClass::Function)),
        _ => false,
    }
}