iridia-dxil 0.5.0

Translate Direct3D Shader Model 6 bytecode (DXIL, dxc output) to naga modules, for WGSL or SPIR-V output
Documentation
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
//! What a lift needs before it writes any code: the interface (the signature elements and resources the program
//! uses), how the entry point carries it, and the program's own instruction index.

use std::collections::{BTreeMap, BTreeSet};

use iridia::{
    EntryIo, Interface, Resource, ResourceId, ResourceKind, Stage, StageFacts, SystemValue, entry_io,
};

use crate::reflection;
use crate::{Result, error, read};
use dxcontainer::Chunk;
use dxil_reader::module::{Constant, Function, Module, Op, Value, ValueId};
use dxil_reader::reflection::{self as records, Element, Range};

/// The constant integer a value is, if it is one.
pub(super) fn const_int(m: &Module, f: &Function, v: ValueId) -> Option<i64> {
    let value = match v.checked_sub(f.first) {
        None => m.values.get(v)?,
        Some(local) => f.locals.get(local)?,
    };
    match value {
        Value::Constant(Constant::Integer(i)) => Some(*i),
        Value::Constant(Constant::Null) => Some(0),
        _ => None,
    }
}

/// The range a `CreateHandleFromBinding` names: its class, lower bound and register space (the binding constant
/// `{ lower, upper, space, class }`), and the offset into the range (the call's index is the register itself).
pub(super) fn binding_of(m: &Module, f: &Function, bind: ValueId) -> Option<(u8, u32, u32)> {
    let value = match bind.checked_sub(f.first) {
        None => m.values.get(bind)?,
        Some(local) => f.locals.get(local)?,
    };
    // a zero binding (register 0 of space 0, a shader resource) is stored as the null constant
    let field = |k: usize| match value {
        Value::Constant(Constant::Null) => Some(0),
        Value::Constant(Constant::Aggregate(items)) => const_int(m, f, *items.get(k)?),
        _ => None,
    };
    Some((
        u8::try_from(field(3)?).ok()?,
        u32::try_from(field(0)?).ok()?,
        u32::try_from(field(2)?).ok()?,
    ))
}

/// The system value a ray tracing `dx.op` reads (`InstanceID` 141 to `RayTCurrent` 154 except the matrices, and
/// `PrimitiveIndex` 161 and `GeometryIndex` 213).
pub(super) fn ray_system_value(code: u64) -> Option<SystemValue> {
    Some(match code {
        141 => SystemValue::InstanceId,
        142 => SystemValue::InstanceIndex,
        143 => SystemValue::HitKind,
        144 => SystemValue::RayFlags,
        145 => SystemValue::DispatchRaysIndex,
        146 => SystemValue::DispatchRaysDimensions,
        147 => SystemValue::WorldRayOrigin,
        148 => SystemValue::WorldRayDirection,
        149 => SystemValue::ObjectRayOrigin,
        150 => SystemValue::ObjectRayDirection,
        153 => SystemValue::RayTMin,
        154 => SystemValue::RayTCurrent,
        161 => SystemValue::PrimitiveIndex,
        213 => SystemValue::GeometryIndex,
        _ => return None,
    })
}

/// The module global whose value `v` is: the load of a global (or of a cast of one) that a library's handle is made
/// from.
pub(super) fn variable_loaded(m: &Module, f: &Function, v: ValueId) -> Option<ValueId> {
    let load = f
        .instructions
        .iter()
        .find(|i| i.result.is_some_and(|(r, _)| r == v))?;
    let Op::Load { pointer, .. } = &load.op else {
        return None;
    };
    let mut at = *pointer;
    loop {
        let value = match at.checked_sub(f.first) {
            None => m.values.get(at)?,
            Some(local) => f.locals.get(local)?,
        };
        match value {
            Value::Global { .. } if at < f.first => return Some(at),
            Value::Constant(Constant::Cast { value, .. }) => at = *value,
            _ => return None,
        }
    }
}

/// The `dx.op` opcode a call makes: the callee is a `dx.op.*` declaration and the first argument a constant.
pub(super) fn dx_opcode(m: &Module, f: &Function, function: ValueId, args: &[ValueId]) -> Option<u64> {
    if !m.name(function)?.starts_with("dx.op.") {
        return None;
    }
    u64::try_from(const_int(m, f, *args.first()?)?).ok()
}

/// The resource ranges of the program, in the interface's order, and which of them the program uses.
pub(crate) struct Setup {
    pub interface: Interface,
    pub io: EntryIo,
    pub input_elements: Vec<Element>,
    pub output_elements: Vec<Element>,
    /// A hull or domain program's patch-constant signature elements.
    pub patch_elements: Vec<Element>,
    /// The functions of a program of a stage with no entry point (see [`iridia::stage_functions`]).
    pub sigs: Option<Vec<iridia::FunctionSig>>,
    /// The kept resources' ranges, parallel to `interface.resources`.
    pub ranges: Vec<Range>,
    pub notes: BTreeSet<String>,
    /// A thread group laid out in more than one dimension has no lane-number built-in in WebGPU: the lane is made at
    /// the start of the program (see `Lift::lane_at_start`).
    pub lane_by_rank: bool,
    /// The resources of descriptor-heap handles (`ResourceDescriptorHeap[i]`): the interface resource of each
    /// `CreateHandleFromHeap` call's result.
    pub heap: BTreeMap<ValueId, usize>,
}

impl Setup {
    /// The setup of a program whose instructions are those of `functions` (the entry function, and a hull program's
    /// patch-constant function).
    pub(super) fn new(chunks: &[Chunk<'_>], m: &Module, functions: &[&Function]) -> Result<Self> {
        let named = dxil_reader::module(chunks, b"STAT").map_err(read)?;
        let mut interface = reflection::reflection(chunks, m, named.as_ref())?;
        if !matches!(
            interface.stage,
            Stage::Pixel
                | Stage::Vertex
                | Stage::Compute
                | Stage::Hull
                | Stage::Domain
                | Stage::Geometry
                | Stage::Mesh
        ) && !interface.stage.is_ray_tracing()
        {
            return Err(error(0, format!("{:?} programs are not lifted", interface.stage)));
        }
        let (input_elements, output_elements) = records::elements(m).map_err(read)?;
        let patch_elements = records::patch_elements(m).map_err(read)?;
        for elements in [&input_elements, &output_elements, &patch_elements] {
            crate::reflection::check_elements(elements)?;
        }
        let program_ranges: Vec<Range> = records::ranges(m)
            .map_err(read)?
            .into_iter()
            .map(|r| r.0)
            .collect();
        if program_ranges.len() != interface.resources.len() {
            return Err(error(
                0,
                "the reflection module's resources differ from the program's",
            ));
        }
        // which cells of the signatures and which ranges the instructions use
        let mut cells_in: BTreeSet<(u32, u8)> = BTreeSet::new();
        let mut cells_out: BTreeSet<(u32, u8)> = BTreeSet::new();
        let mut cells_patch: BTreeSet<(u32, u8)> = BTreeSet::new();
        let mut system_out: BTreeSet<u8> = BTreeSet::new();
        let mut used_ranges: BTreeSet<(u8, u32)> = BTreeSet::new();
        let mut used_bindings: BTreeSet<(u8, u32, u32)> = BTreeSet::new();
        // a library makes its handles from the value of the resource's global
        let mut used_variables: BTreeSet<ValueId> = BTreeSet::new();
        // the system inputs the program reads that the signature does not list: the sample index and, in a compute
        // program, the invocation's ids
        let mut system_inputs: BTreeSet<SystemValue> = BTreeSet::new();
        // the rows of an instance's transform the program reads
        let mut matrix_rows: BTreeSet<(SystemValue, u32)> = BTreeSet::new();
        for entry in functions.iter().copied() {
            for inst in &entry.instructions {
                let Op::Call { function, args, .. } = &inst.op else {
                    continue;
                };
                let Some(code) = dx_opcode(m, entry, *function, args) else {
                    continue;
                };
                let konst = |n: usize| args.get(n).and_then(|&a| const_int(m, entry, a));
                match code {
                    // LoadInput, StoreOutput, LoadOutputControlPoint, LoadPatchConstant, StorePatchConstant, StoreVertexOutput
                    4 | 5 | 103 | 104 | 106 | 171 => {
                        let list = match code {
                            4 => &input_elements,
                            5 | 103 | 171 => &output_elements,
                            _ => &patch_elements,
                        };
                        let Some(id) = konst(1) else {
                            return Err(error(inst.at, "a signature element named by a computed id"));
                        };
                        let e = list
                            .iter()
                            .find(|e| i64::from(e.id) == id)
                            .ok_or_else(|| error(inst.at, format!("signature element {id}")))?;
                        if !e.placed {
                            if code == 5 || code == 171 {
                                system_out.insert(e.system_value);
                                continue;
                            }
                            return Err(error(
                                inst.at,
                                format!("input element {} is not placed in a register", e.name),
                            ));
                        }
                        let (rows, columns) = match (konst(2), konst(3)) {
                            (Some(r), Some(c)) => (r..r.saturating_add(1), c..c.saturating_add(1)),
                            (Some(r), None) => (r..r.saturating_add(1), 0..i64::from(e.columns)),
                            (None, Some(c)) => (0..i64::from(e.rows), c..c.saturating_add(1)),
                            (None, None) => (0..i64::from(e.rows), 0..i64::from(e.columns)),
                        };
                        for r in rows {
                            for c in columns.clone() {
                                let cell = u32::try_from(r)
                                    .ok()
                                    .and_then(|r| e.row.checked_add(r))
                                    .zip(u8::try_from(c).ok().and_then(|c| e.column.checked_add(c)))
                                    .ok_or_else(|| {
                                        error(
                                            inst.at,
                                            format!(
                                                "row {r}, column {c} of element {}, which starts at row {}, column {}",
                                                e.name, e.row, e.column
                                            ),
                                        )
                                    })?;
                                match code {
                                    4 => cells_in.insert(cell),
                                    5 | 103 | 171 => cells_out.insert(cell),
                                    _ => cells_patch.insert(cell),
                                };
                            }
                        }
                    }
                    57 => {
                        if let (Some(class), Some(id)) = (konst(1), konst(2)) {
                            used_ranges.insert((
                                u8::try_from(class)
                                    .map_err(|_| error(inst.at, format!("resource class {class}")))?,
                                u32::try_from(id)
                                    .map_err(|_| error(inst.at, format!("resource range {id}")))?,
                            ));
                        } else {
                            return Err(error(inst.at, "a handle of a computed range"));
                        }
                    }
                    // SampleIndex: the pixel's sample number, which the input signature does not list
                    90 => {
                        system_inputs.insert(SystemValue::SampleIndex);
                    }
                    // ThreadId, GroupId, ThreadIdInGroup, FlattenedThreadIdInGroup
                    93 => {
                        system_inputs.insert(SystemValue::DispatchThreadId);
                    }
                    94 => {
                        system_inputs.insert(SystemValue::GroupId);
                    }
                    95 => {
                        system_inputs.insert(SystemValue::GroupThreadId);
                    }
                    96 => {
                        system_inputs.insert(SystemValue::GroupIndex);
                    }
                    // IsFirstLane, LaneIndex and PrefixBitCount read the lane's number; LaneCount the wave's size
                    110 | 111 | 136 => {
                        system_inputs.insert(SystemValue::LaneIndex);
                    }
                    112 => {
                        system_inputs.insert(SystemValue::LaneCount);
                    }
                    151 | 152 => {
                        let Some(row) = konst(1).filter(|r| (0..3).contains(r)) else {
                            return Err(error(inst.at, "a transform read at a computed row"));
                        };
                        let system = if code == 151 {
                            SystemValue::ObjectToWorld
                        } else {
                            SystemValue::WorldToObject
                        };
                        matrix_rows.insert((system, super::low32(row as u64)));
                    }
                    // the ray tracing system values: the ids and the traced ray's state
                    141..=150 | 153 | 154 | 161 | 213 => {
                        if let Some(system) = ray_system_value(code) {
                            system_inputs.insert(system);
                        }
                    }
                    217 => {
                        let Some((class, lower, space)) =
                            binding_of(m, entry, super::argument(args, 1, inst.at)?)
                        else {
                            return Err(error(inst.at, "a handle of a binding that is not constant"));
                        };
                        used_bindings.insert((class, lower, space));
                    }
                    160 => match variable_loaded(m, entry, super::argument(args, 1, inst.at)?) {
                        Some(global) => {
                            used_variables.insert(global);
                        }
                        None => {
                            return Err(error(
                                inst.at,
                                "a handle of a resource that is not a global's value",
                            ));
                        }
                    },
                    _ => {}
                }
            }
        }
        // the signature's varyings, every one with a register, as the container declares them (input layouts and stage
        // linking are matched against the signature): `used` where the program reads or writes a cell of it. A built-in
        // output without a register (depth, coverage) is kept only if the program writes it: it has no local otherwise.
        let settle = |v: &mut iridia::Varying, cells: &BTreeSet<(u32, u8)>, system: &BTreeSet<u8>| {
            match v.provenance.d3d {
                Some(d3d) if d3d.register != u32::MAX => {
                    // the program's own reading, not the signature's mask: the compiler's masks are not what is stored
                    v.used = (0..4u8)
                        .any(|lane| d3d.mask >> lane & 1 != 0 && cells.contains(&(d3d.register, lane)));
                    true
                }
                _ => match v.system {
                    // DXIL semantic kinds: 17 depth, 18 depth less-equal, 19 depth greater-equal, 14 coverage
                    Some(SystemValue::Depth) => system.contains(&17),
                    Some(SystemValue::DepthLessEqual) => system.contains(&18),
                    Some(SystemValue::DepthGreaterEqual) => system.contains(&19),
                    Some(SystemValue::Coverage) => system.contains(&14),
                    _ => false,
                },
            }
        };
        let none = BTreeSet::new();
        interface.inputs.retain_mut(|v| settle(v, &cells_in, &none));
        interface
            .outputs
            .retain_mut(|v| settle(v, &cells_out, &system_out));
        match &mut interface.facts {
            StageFacts::Hull(h) => h.patch_constants.retain_mut(|v| settle(v, &cells_patch, &none)),
            StageFacts::Domain(d) => d.patch_constants.retain_mut(|v| settle(v, &cells_patch, &none)),
            _ => {}
        }
        // a vertex program that writes no position feeds a tessellator (or a stream-output stage): it is functions
        if interface.stage == Stage::Vertex
            && !interface
                .outputs
                .iter()
                .any(|v| v.used && v.system == Some(SystemValue::ClipPosition))
        {
            interface.facts = StageFacts::VertexWithoutPosition;
        }
        // WebGPU gives a lane number only to a thread group laid out along x
        let multi_dimensional = interface.stage == Stage::Compute
            && records::num_threads(m)
                .map_err(read)?
                .is_some_and(|[_, y, z]| y != 1 || z != 1);
        let lane_by_rank = multi_dimensional && system_inputs.remove(&SystemValue::LaneIndex);
        for system in system_inputs {
            if interface.inputs.iter().any(|v| v.system == Some(system)) {
                continue;
            }
            let (name, width) = match system {
                SystemValue::SampleIndex => ("SV_SampleIndex", 1),
                SystemValue::DispatchThreadId => ("SV_DispatchThreadID", 3),
                SystemValue::GroupId => ("SV_GroupID", 3),
                SystemValue::GroupThreadId => ("SV_GroupThreadID", 3),
                SystemValue::LaneIndex => ("SV_LaneIndex", 1),
                SystemValue::LaneCount => ("SV_LaneCount", 1),
                SystemValue::DispatchRaysIndex => ("SV_DispatchRaysIndex", 3),
                SystemValue::DispatchRaysDimensions => ("SV_DispatchRaysDimensions", 3),
                SystemValue::WorldRayOrigin => ("SV_WorldRayOrigin", 3),
                SystemValue::WorldRayDirection => ("SV_WorldRayDirection", 3),
                SystemValue::ObjectRayOrigin => ("SV_ObjectRayOrigin", 3),
                SystemValue::ObjectRayDirection => ("SV_ObjectRayDirection", 3),
                SystemValue::RayTMin => ("SV_RayTMin", 1),
                SystemValue::RayTCurrent => ("SV_RayTCurrent", 1),
                SystemValue::RayFlags => ("SV_RayFlags", 1),
                SystemValue::InstanceId => ("SV_InstanceID", 1),
                SystemValue::InstanceIndex => ("SV_InstanceIndex", 1),
                SystemValue::PrimitiveIndex => ("SV_PrimitiveIndex", 1),
                SystemValue::GeometryIndex => ("SV_GeometryIndex", 1),
                SystemValue::HitKind => ("SV_HitKind", 1),
                _ => ("SV_GroupIndex", 1),
            };
            let float = matches!(
                system,
                SystemValue::WorldRayOrigin
                    | SystemValue::WorldRayDirection
                    | SystemValue::ObjectRayOrigin
                    | SystemValue::ObjectRayDirection
                    | SystemValue::RayTMin
                    | SystemValue::RayTCurrent
            );
            interface.inputs.push(iridia::Varying {
                label: iridia::Label {
                    name: name.into(),
                    index: 0,
                },
                system: Some(system),
                value: iridia::Value {
                    scalar: if float {
                        iridia::ScalarType::Float
                    } else {
                        iridia::ScalarType::Uint
                    },
                    width,
                },
                interp: None,
                used: true,
                provenance: iridia::VaryingProvenance::default(),
            });
        }
        for (system, row) in matrix_rows {
            interface.inputs.push(iridia::Varying {
                label: iridia::Label {
                    name: if system == SystemValue::ObjectToWorld {
                        "SV_ObjectToWorld"
                    } else {
                        "SV_WorldToObject"
                    }
                    .into(),
                    index: row,
                },
                system: Some(system),
                value: iridia::Value {
                    scalar: iridia::ScalarType::Float,
                    width: 4,
                },
                interp: None,
                used: true,
                provenance: iridia::VaryingProvenance::default(),
            });
        }
        // the resources the program creates handles for, numbered anew
        let mut resources = Vec::new();
        let mut ranges = Vec::new();
        for (original, range) in interface.resources.drain(..).zip(program_ranges) {
            if !used_ranges.contains(&(range.class, range.id))
                && !used_bindings.contains(&(range.class, range.lower, range.space))
                && !range.variable.is_some_and(|g| used_variables.contains(&g))
            {
                continue;
            }
            if original.is_array()
                && !matches!(
                    original.kind,
                    ResourceKind::Texture { .. }
                        | ResourceKind::ConstantBuffer { .. }
                        | ResourceKind::Sampler { .. }
                        | ResourceKind::Buffer(_)
                        | ResourceKind::Storage { .. }
                )
            {
                return Err(error(
                    0,
                    format!(
                        "{}: arrays of resources other than textures, samplers, buffers and storage ({}, a range of {}) are not lifted",
                        original.provenance.name,
                        match &original.kind {
                            ResourceKind::ConstantBuffer { .. } => "constant buffers",
                            ResourceKind::AccelerationStructure => "acceleration structures",
                            _ => "resources",
                        },
                        original.count
                    ),
                ));
            }
            resources.push(Resource {
                id: ResourceId(
                    u32::try_from(resources.len()).map_err(|_| error(0, "more than 4294967295 resources"))?,
                ),
                ..original
            });
            ranges.push(range);
        }
        let heap = heap_resources(m, functions, &mut resources, &mut ranges)?;
        interface.resources = resources;
        let sigs = iridia::stage_functions(&interface).map_err(|detail| error(0, detail))?;
        let io = match sigs {
            // the functions of such a program carry no bindings: no entry point to describe
            Some(_) => EntryIo {
                arguments: Vec::new(),
                results: Vec::new(),
            },
            None => entry_io(&interface).map_err(|detail| error(0, detail))?,
        };
        Ok(Setup {
            interface,
            io,
            sigs,
            input_elements,
            output_elements,
            patch_elements,
            ranges,
            notes: BTreeSet::new(),
            lane_by_rank,
            heap,
        })
    }

    /// The input varying whose register and lanes hold this cell, and the lane's position in its value.
    pub(super) fn input_cell(&self, register: u32, lane: u8) -> Option<(usize, u8)> {
        cell(&self.interface.inputs, register, lane)
    }
    pub(super) fn output_cell(&self, register: u32, lane: u8) -> Option<(usize, u8)> {
        cell(&self.interface.outputs, register, lane)
    }

    /// The kept resource of a binding's class, lower bound and register space.
    pub(super) fn resource_by_binding(&self, class: u8, lower: u32, space: u32) -> Option<usize> {
        self.ranges
            .iter()
            .position(|r| r.class == class && r.lower == lower && r.space == space)
    }

    /// The kept resource of a handle's class and range id.
    pub(super) fn resource(&self, class: u8, id: u32) -> Option<usize> {
        self.ranges.iter().position(|r| r.class == class && r.id == id)
    }
    /// The kept resource a library names by this module global.
    pub(super) fn resource_of_variable(&self, global: ValueId) -> Option<usize> {
        self.ranges.iter().position(|r| r.variable == Some(global))
    }
    pub(super) fn kind(&self, resource: usize) -> &ResourceKind {
        self.interface
            .resources
            .get(resource)
            .map_or(&ResourceKind::AccelerationStructure, |r| &r.kind)
    }
}

/// The register space the descriptor heaps' resources are numbered in: apart from every space a program declares.
const HEAP_SPACE: u32 = 0x8000;

/// The resources the program makes handles for from a descriptor heap (Shader Model 6.6 `ResourceDescriptorHeap` and
/// `SamplerDescriptorHeap`). A heap is untyped, so the resource is what the annotation of the handle says it is: one
/// unbounded array of that kind of view, in a register space of its own, indexed by the program's index. The same
/// annotation shares one resource. Appended to `resources` and `ranges`; the result maps each call's result to its
/// resource.
fn heap_resources(
    m: &Module,
    functions: &[&Function],
    resources: &mut Vec<Resource>,
    ranges: &mut Vec<Range>,
) -> Result<BTreeMap<ValueId, usize>> {
    let mut made: BTreeMap<(u8, i64, i64), usize> = BTreeMap::new();
    let mut handles = BTreeMap::new();
    for f in functions.iter().copied() {
        for inst in &f.instructions {
            let (Op::Call { function, args, .. }, Some((handle, _))) = (&inst.op, inst.result) else {
                continue;
            };
            if dx_opcode(m, f, *function, args) != Some(218) {
                continue;
            }
            let sampler = const_int(m, f, super::argument(args, 2, inst.at)?) == Some(1);
            // the annotation that says what the descriptor is: its properties, two constant words
            let properties = functions.iter().copied().find_map(|g| {
                g.instructions.iter().find_map(|i| {
                    let Op::Call { function, args, .. } = &i.op else {
                        return None;
                    };
                    if dx_opcode(m, g, *function, args) != Some(216) || args.get(1) != Some(&handle) {
                        return None;
                    }
                    let annotation = *args.get(2)?;
                    let value = match annotation.checked_sub(g.first) {
                        None => m.values.get(annotation)?,
                        Some(local) => g.locals.get(local)?,
                    };
                    match value {
                        Value::Constant(Constant::Aggregate(items)) => Some((
                            const_int(m, g, *items.first()?)?,
                            const_int(m, g, *items.get(1)?)?,
                        )),
                        Value::Constant(Constant::Null) => Some((0, 0)),
                        _ => None,
                    }
                })
            });
            let Some((first, second)) = properties else {
                return Err(error(
                    inst.at,
                    "a descriptor from a heap that the program does not annotate with its properties",
                ));
            };
            // the properties' words: the resource kind in the low byte; a view is an unordered-access one by 0x1000, a
            // comparison sampler by 0x8000; the second word is a typed view's component type (low byte) and lanes, a
            // structured buffer's stride, a constant buffer's size
            let kind = first & 0xff;
            let class = match (sampler || kind == 14, kind) {
                (true, _) => 3,
                (_, 13) => 2,
                _ if first & 0x1000 != 0 => 1,
                _ => 0,
            };
            let index = match made.get(&(class, first, second)) {
                Some(&i) => i,
                None => {
                    let n = u32::try_from(made.len())
                        .map_err(|_| error(inst.at, "more than 4294967295 heap descriptors"))?;
                    let range = Range {
                        class,
                        id: u32::MAX.saturating_sub(n),
                        lower: n,
                        count: Resource::UNBOUNDED,
                        extra: match class {
                            3 => u32::from(first & 0x8000 != 0),
                            2 => {
                                u32::try_from(second).map_err(|_| error(inst.at, "a constant buffer size"))?
                            }
                            _ => super::low32(kind as u64),
                        },
                        space: HEAP_SPACE,
                        element: (class < 2 && kind != 11 && kind != 12)
                            .then_some(super::low32(second as u64 & 0xff)),
                        stride: (kind == 12).then_some(super::low32(second as u64)),
                        counter: false,
                        variable: None,
                    };
                    let id = ResourceId(
                        u32::try_from(resources.len())
                            .map_err(|_| error(inst.at, "more than 4294967295 resources"))?,
                    );
                    let name = if class == 3 {
                        "SamplerDescriptorHeap"
                    } else {
                        "ResourceDescriptorHeap"
                    };
                    let mut resource = reflection::resource_of(id, &range, name.into(), None, m)
                        .map_err(|e| error(inst.at, e.to_string()))?;
                    // a heap's descriptors have no register of the source's own
                    resource.provenance.d3d = None;
                    resources.push(resource);
                    ranges.push(range);
                    let index = resources.len().saturating_sub(1);
                    made.insert((class, first, second), index);
                    index
                }
            };
            handles.insert(handle, index);
        }
    }
    Ok(handles)
}

fn cell(list: &[iridia::Varying], register: u32, lane: u8) -> Option<(usize, u8)> {
    list.iter().enumerate().find_map(|(i, v)| {
        let d3d = v.provenance.d3d?;
        (d3d.register == register)
            .then(|| super::stages::lanes_below(d3d.mask, lane))
            .flatten()
            .map(|position| (i, position))
    })
}