vyre-foundation 0.4.1

Foundation layer: IR, type system, memory model, wire format. Zero application semantics. Part of the vyre GPU compiler.
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
//! `region_promote_singleton_block` — unwrap `Region { body: [Block(inner)] }`
//! to `Region { body: inner }`.
//!
//! Op id: `vyre-foundation::optimizer::passes::region_promote_singleton_block`.
//! Soundness: `Exact` — `Node::Block` is a transparent container with no
//! observable behavior beyond grouping its children. A Region whose entire
//! body is a single `Block(inner)` is observationally equivalent to a Region
//! whose body is `inner` directly. Cost-direction: monotone-down on
//! `node_count`, `control_flow_count`, and `ir_heap_allocations` (Region
//! body Arc shrinks by one Vec layer). Preserves: every analysis. Invalidates:
//! nothing.
//!
//! ## Why
//!
//! Multiple substrate paths emit `Region { body: vec![Block(inner)] }`
//! shapes:
//!   - The default `Node::Region` constructor in primitive builders
//!     wraps the body in `Block` for visual symmetry with `If`/`Loop`.
//!   - `dce` collapses a multi-statement region down to one surviving
//!     `Block` of statements.
//!   - Macro-style code emitters
//!     wrap a Region body in a single Block to give the macro a stable
//!     handle to inject hooks into.
//!
//! Each extra Block layer costs a Vec allocation, an indirection in the
//! tree-walker (cost certificate, fingerprint, target emission), and one
//! nesting level in emitters that materialize lexical scopes.
//!
//! ## Rule
//!
//! ```text
//! Node::Region { body: Arc::new(vec![Node::Block(inner)]) }
//!//! Node::Region { body: Arc::new(inner) }
//! ```
//!
//! Applied recursively: the unwrap fires anywhere a Region body contains
//! exactly one Block as its only child. Multi-child Region bodies (the
//! common case for non-trivial primitives) are unchanged.
//!
//! ## Why not generalize to "remove any singleton child container"
//!
//! `Region` carries an `op_id` and `source_region` for region-chain audits
//! and bench attribution. This pass only removes the transparent `Block`
//! layer when the parent is a `Region`; it never removes or merges a
//! `Region` node.

use std::sync::Arc;

use crate::ir::{Node, Program};
use crate::optimizer::{fingerprint_program, vyre_pass, PassAnalysis, PassResult};
use crate::visit::node_map;

/// Unwrap `Region { body: [Block(inner)] }` to `Region { body: inner }`.
#[derive(Debug, Default)]
#[vyre_pass(
    name = "region_promote_singleton_block",
    requires = [],
    invalidates = []
)]
pub struct RegionPromoteSingletonBlockPass;

impl RegionPromoteSingletonBlockPass {
    /// Skip programs without any Region wrapping a singleton Block.
    #[must_use]
    pub fn analyze(program: &Program) -> PassAnalysis {
        if program
            .entry()
            .iter()
            .any(|n| node_map::any_descendant(n, &mut is_singleton_block_region))
        {
            PassAnalysis::RUN
        } else {
            PassAnalysis::SKIP
        }
    }

    /// Walk the entry tree and unwrap every singleton-block Region body.
    #[must_use]
    pub fn transform(program: Program) -> PassResult {
        let scaffold = program.with_rewritten_entry(Vec::new());
        let mut changed = false;
        let entry = program
            .into_entry_vec()
            .into_iter()
            .map(|n| promote_node(n, &mut changed))
            .collect();
        PassResult {
            program: scaffold.with_rewritten_entry(entry),
            changed,
        }
    }

    /// Fingerprint the program state.
    #[must_use]
    pub fn fingerprint(program: &Program) -> u64 {
        fingerprint_program(program)
    }
}

/// Recurse into `node`'s descendants. After recursion, if `node` is a
/// `Region` whose body is exactly a single `Block`, lift the Block's
/// children to be the Region's direct children.
fn promote_node(node: Node, changed: &mut bool) -> Node {
    let recursed = node_map::map_children(node, &mut |child| promote_node(child, changed));
    if let Node::Region {
        generator,
        source_region,
        body,
    } = recursed
    {
        let body_vec: Vec<Node> = match Arc::try_unwrap(body) {
            Ok(v) => v,
            Err(arc) => (*arc).clone(),
        };
        if matches!(body_vec.as_slice(), [Node::Block(_)]) {
            *changed = true;
            let mut iter = body_vec.into_iter();
            let inner = match iter.next() {
                Some(Node::Block(inner)) => inner,
                _ => unreachable!("matched [Node::Block(_)] above"),
            };
            return Node::Region {
                generator,
                source_region,
                body: Arc::new(inner),
            };
        }
        return Node::Region {
            generator,
            source_region,
            body: Arc::new(body_vec),
        };
    }
    recursed
}

/// True iff `node` is a `Region` whose body is exactly a single `Block`.
fn is_singleton_block_region(node: &Node) -> bool {
    matches!(
        node,
        Node::Region { body, .. } if matches!(body.as_slice(), [Node::Block(_)])
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ir::model::expr::Ident;
    use crate::ir::{BufferAccess, BufferDecl, DataType, Expr, Node};

    fn buf() -> BufferDecl {
        BufferDecl::storage("buf", 0, BufferAccess::ReadWrite, DataType::U32).with_count(4)
    }

    fn region_with_body(body: Vec<Node>) -> Node {
        Node::Region {
            generator: Ident::from("test_op"),
            source_region: None,
            body: Arc::new(body),
        }
    }

    fn program_with_entry(entry: Vec<Node>) -> Program {
        Program::wrapped(vec![buf()], [1, 1, 1], entry)
    }

    fn count_singleton_block_regions(node: &Node) -> usize {
        let mut count = 0;
        if let Node::Region { body, .. } = node {
            if matches!(body.as_slice(), [Node::Block(_)]) {
                count += 1;
            }
            for child in body.iter() {
                count += count_singleton_block_regions(child);
            }
        }
        match node {
            Node::If {
                then, otherwise, ..
            } => {
                for n in then {
                    count += count_singleton_block_regions(n);
                }
                for n in otherwise {
                    count += count_singleton_block_regions(n);
                }
            }
            Node::Loop { body, .. } => {
                for n in body {
                    count += count_singleton_block_regions(n);
                }
            }
            Node::Block(body) => {
                for n in body {
                    count += count_singleton_block_regions(n);
                }
            }
            _ => {}
        }
        count
    }

    #[test]
    fn skip_analysis_on_program_without_region() {
        let entry = vec![Node::store("buf", Expr::u32(0), Expr::u32(7))];
        let program = program_with_entry(entry);
        assert_eq!(
            RegionPromoteSingletonBlockPass::analyze(&program),
            PassAnalysis::SKIP
        );
    }

    #[test]
    fn skip_analysis_on_region_with_multiple_children() {
        // Multi-child Region body must not match the singleton rule.
        let entry = vec![region_with_body(vec![
            Node::store("buf", Expr::u32(0), Expr::u32(7)),
            Node::store("buf", Expr::u32(1), Expr::u32(8)),
        ])];
        let program = program_with_entry(entry);
        assert_eq!(
            RegionPromoteSingletonBlockPass::analyze(&program),
            PassAnalysis::SKIP
        );
    }

    #[test]
    fn run_analysis_on_singleton_block_region() {
        let entry = vec![region_with_body(vec![Node::Block(vec![Node::store(
            "buf",
            Expr::u32(0),
            Expr::u32(7),
        )])])];
        let program = program_with_entry(entry);
        assert_eq!(
            RegionPromoteSingletonBlockPass::analyze(&program),
            PassAnalysis::RUN
        );
    }

    #[test]
    fn transform_unwraps_simple_singleton_block() {
        let entry = vec![region_with_body(vec![Node::Block(vec![Node::store(
            "buf",
            Expr::u32(0),
            Expr::u32(7),
        )])])];
        let program = program_with_entry(entry);
        let result = RegionPromoteSingletonBlockPass::transform(program);
        assert!(result.changed);
        let total: usize = result
            .program
            .entry()
            .iter()
            .map(count_singleton_block_regions)
            .sum();
        assert_eq!(total, 0, "no singleton-block Regions must remain");
    }

    #[test]
    fn transform_preserves_region_op_id() {
        let entry = vec![region_with_body(vec![Node::Block(vec![Node::store(
            "buf",
            Expr::u32(0),
            Expr::u32(7),
        )])])];
        let program = program_with_entry(entry);
        let result = RegionPromoteSingletonBlockPass::transform(program);
        match &result.program.entry()[0] {
            Node::Region { generator, .. } => {
                assert_eq!(generator.as_str(), "test_op", "op id must be preserved");
            }
            _ => panic!(
                "expected Region at top of entry; got {:?}",
                result.program.entry()[0]
            ),
        }
    }

    #[test]
    fn transform_lifts_inner_children_to_region_body() {
        let entry = vec![region_with_body(vec![Node::Block(vec![
            Node::store("buf", Expr::u32(0), Expr::u32(1)),
            Node::store("buf", Expr::u32(1), Expr::u32(2)),
            Node::store("buf", Expr::u32(2), Expr::u32(3)),
        ])])];
        let program = program_with_entry(entry);
        let result = RegionPromoteSingletonBlockPass::transform(program);
        match &result.program.entry()[0] {
            Node::Region { body, .. } => {
                assert_eq!(
                    body.len(),
                    3,
                    "the 3 inner Block children must be promoted to Region body"
                );
            }
            other => panic!("expected Region; got {other:?}"),
        }
    }

    #[test]
    fn transform_skips_multi_child_region_unchanged() {
        let entry = vec![region_with_body(vec![
            Node::store("buf", Expr::u32(0), Expr::u32(7)),
            Node::store("buf", Expr::u32(1), Expr::u32(8)),
        ])];
        let program = program_with_entry(entry);
        let result = RegionPromoteSingletonBlockPass::transform(program);
        assert!(
            !result.changed,
            "multi-child Region must not match the singleton rule"
        );
    }

    #[test]
    fn transform_handles_nested_singleton_block_regions() {
        // Region wraps Block which wraps another Region wrapping a Block.
        let inner_region = region_with_body(vec![Node::Block(vec![Node::store(
            "buf",
            Expr::u32(0),
            Expr::u32(1),
        )])]);
        let entry = vec![region_with_body(vec![Node::Block(vec![inner_region])])];
        let program = program_with_entry(entry);
        let result = RegionPromoteSingletonBlockPass::transform(program);
        assert!(result.changed);
        let total: usize = result
            .program
            .entry()
            .iter()
            .map(count_singleton_block_regions)
            .sum();
        assert_eq!(
            total, 0,
            "every layer of singleton-block Region must be unwrapped, including nested"
        );
    }

    #[test]
    fn transform_is_idempotent() {
        let entry = vec![region_with_body(vec![Node::Block(vec![Node::store(
            "buf",
            Expr::u32(0),
            Expr::u32(7),
        )])])];
        let program = program_with_entry(entry);
        let once = RegionPromoteSingletonBlockPass::transform(program);
        let twice_program = once.program.clone();
        let twice = RegionPromoteSingletonBlockPass::transform(twice_program);
        assert!(once.changed);
        assert!(!twice.changed, "second run must report no change");
    }

    #[test]
    fn transform_preserves_region_inside_removed_block() {
        let entry = vec![Node::Block(vec![region_with_body(vec![Node::store(
            "buf",
            Expr::u32(0),
            Expr::u32(7),
        )])])];
        let program = program_with_entry(entry);
        let result = RegionPromoteSingletonBlockPass::transform(program);
        match &result.program.entry()[0] {
            Node::Region { body, .. } => {
                assert!(
                    matches!(body[0], Node::Region { .. }),
                    "inner Region must still be present after transparent Block removal"
                );
            }
            other => panic!("expected root Region; got {other:?}"),
        }
    }

    #[test]
    fn transform_handles_empty_program() {
        let program = Program::wrapped(vec![buf()], [1, 1, 1], vec![]);
        let result = RegionPromoteSingletonBlockPass::transform(program);
        assert!(!result.changed);
    }

    #[test]
    fn transform_unwraps_region_inside_if_branch() {
        let inner_region = region_with_body(vec![Node::Block(vec![Node::store(
            "buf",
            Expr::u32(0),
            Expr::u32(1),
        )])]);
        let entry = vec![Node::if_then(
            Expr::lt(Expr::u32(0), Expr::u32(1)),
            vec![inner_region],
        )];
        let program = program_with_entry(entry);
        let result = RegionPromoteSingletonBlockPass::transform(program);
        assert!(
            result.changed,
            "Regions inside If branches must be processed"
        );
        let total: usize = result
            .program
            .entry()
            .iter()
            .map(count_singleton_block_regions)
            .sum();
        assert_eq!(total, 0);
    }

    #[test]
    fn transform_unwraps_region_inside_loop_body() {
        let inner_region = region_with_body(vec![Node::Block(vec![Node::store(
            "buf",
            Expr::u32(0),
            Expr::u32(1),
        )])]);
        let entry = vec![Node::Loop {
            var: Ident::from("i"),
            from: Expr::u32(0),
            to: Expr::u32(4),
            body: vec![inner_region],
        }];
        let program = program_with_entry(entry);
        let result = RegionPromoteSingletonBlockPass::transform(program);
        assert!(
            result.changed,
            "Regions inside Loop bodies must be processed"
        );
        let total: usize = result
            .program
            .entry()
            .iter()
            .map(count_singleton_block_regions)
            .sum();
        assert_eq!(total, 0);
    }

    #[test]
    fn fingerprint_returns_stable_value() {
        let entry = vec![region_with_body(vec![Node::Block(vec![Node::store(
            "buf",
            Expr::u32(0),
            Expr::u32(7),
        )])])];
        let program = program_with_entry(entry);
        let fp1 = RegionPromoteSingletonBlockPass::fingerprint(&program);
        let fp2 = RegionPromoteSingletonBlockPass::fingerprint(&program);
        assert_eq!(fp1, fp2);
    }
}