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
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
use crate::ir_inner::model::expr::{Expr, Ident};
#[cfg(test)]
use crate::ir_inner::model::node::Node;
use crate::ir_inner::model::program::BufferDecl;
use crate::ir_inner::model::types::DataType;
#[cfg(test)]
use crate::validate::barrier;
#[cfg(test)]
use crate::validate::binding::check_sibling_duplicate;
#[cfg(test)]
use crate::validate::bytes_rejection;
#[cfg(test)]
use crate::validate::depth::{self, LimitState};
#[cfg(test)]
use crate::validate::expr_rules::validate_expr;
#[cfg(test)]
use crate::validate::shadowing;
#[cfg(test)]
use crate::validate::typecheck::expr_type;
#[cfg(test)]
use crate::validate::uniformity::is_uniform;
use crate::validate::{err, Binding, ValidationError};
#[cfg(test)]
use crate::validate::{ValidationOptions, ValidationReport};
use rustc_hash::FxHashMap;
#[cfg(test)]
use rustc_hash::FxHashSet;

pub(crate) type ScopeLog = Vec<(Ident, Option<Binding>)>;

#[inline]
#[cfg(test)]
pub(crate) fn validate_nodes(
    nodes: &[Node],
    buffers: &FxHashMap<&str, &BufferDecl>,
    scope: &mut FxHashMap<Ident, Binding>,
    divergent: bool,
    depth: usize,
    limits: &mut LimitState,
    options: ValidationOptions<'_>,
    report: &mut ValidationReport,
) {
    let mut region_bindings = FxHashSet::default();
    validate_nodes_inner(
        nodes,
        buffers,
        scope,
        divergent,
        depth,
        limits,
        options,
        report,
        &mut region_bindings,
        None,
    );
}

#[allow(clippy::too_many_arguments)]
#[cfg(test)]
fn validate_nodes_inner(
    nodes: &[Node],
    buffers: &FxHashMap<&str, &BufferDecl>,
    scope: &mut FxHashMap<Ident, Binding>,
    divergent: bool,
    depth: usize,
    limits: &mut LimitState,
    options: ValidationOptions<'_>,
    report: &mut ValidationReport,
    region_bindings: &mut FxHashSet<Ident>,
    mut scope_log: Option<&mut ScopeLog>,
) {
    for node in nodes {
        validate_node_inner(
            node,
            buffers,
            scope,
            divergent,
            depth,
            limits,
            options,
            report,
            region_bindings,
            scope_log.as_deref_mut(),
        );
    }

    if let Some(pos) = nodes.iter().position(|n| matches!(n, Node::Return)) {
        if pos != nodes.len().saturating_sub(1) {
            report.errors.push(err(
                "unreachable statements after `return`. Fix: remove statements after `return` or reorder them.".to_string(),
            ));
        }
    }
}

#[allow(clippy::too_many_lines, clippy::unnested_or_patterns)]
#[cfg(test)]
fn validate_node_inner(
    node: &Node,
    buffers: &FxHashMap<&str, &BufferDecl>,
    scope: &mut FxHashMap<Ident, Binding>,
    divergent: bool,
    depth: usize,
    limits: &mut LimitState,
    options: ValidationOptions<'_>,
    report: &mut ValidationReport,
    region_bindings: &mut FxHashSet<Ident>,
    scope_log: Option<&mut ScopeLog>,
) {
    depth::check_limits(limits, depth, &mut report.errors);

    match node {
        Node::Let { name, value } => {
            validate_expr(value, buffers, scope, options, report, 0);
            let duplicate_sibling = check_sibling_duplicate(
                name,
                region_bindings,
                options.allow_shadowing,
                &mut report.errors,
            );
            if !duplicate_sibling {
                shadowing::check_local(name, scope, options, &mut report.errors);
            }
            let ty = expr_type(value, buffers, scope).unwrap_or(DataType::U32);
            let uniform = is_uniform(value, scope);
            insert_binding(
                scope,
                name.clone(),
                Binding {
                    ty,
                    mutable: true,
                    uniform,
                },
                scope_log,
            );
        }
        Node::Assign { name, value } => {
            if let Some(binding) = scope.get(name.as_str()) {
                if !binding.mutable {
                    report.errors.push(err(format!(
                        "V011: assignment to loop variable `{name}`. Fix: loop variables are immutable."
                    )));
                }
                if let Some(value_ty) = expr_type(value, buffers, scope) {
                    if value_ty != binding.ty {
                        report.errors.push(err(format!(
                            "V045: assignment to `{name}` has type `{value_ty}` but the binding was declared as `{declared}`. Fix: cast the value to `{declared}` or introduce a new binding with the intended type.",
                            declared = binding.ty
                        )));
                    }
                }
            } else {
                report.errors.push(err(format!(
                    "assignment to undeclared variable `{name}`. Fix: add `let {name} = ...;` before this assignment."
                )));
            }
            validate_expr(value, buffers, scope, options, report, 0);
            // Reassignment with a divergent rhs taints the binding's
            // uniformity for the remainder of its lifetime.
            let new_uniform = is_uniform(value, scope);
            if let Some(binding) = scope.get_mut(name.as_str()) {
                binding.uniform = binding.uniform && new_uniform;
            }
        }
        Node::Store {
            buffer,
            index,
            value,
        } => {
            bytes_rejection::check_store(buffer, buffers, &mut report.errors);
            if let Some(buf) = buffers.get(buffer.as_str()) {
                if let Some(val_ty) = expr_type(value, buffers, scope) {
                    let elem = &buf.element;
                    let compatible = val_ty == *elem
                        || matches!(
                            (&val_ty, elem),
                            (DataType::U32, DataType::Bytes)
                                | (DataType::Bytes, DataType::U32)
                                | (DataType::U32, DataType::Bool)
                                | (DataType::Bool, DataType::U32)
                        )
                        || matches!((&val_ty, elem), (DataType::F32, DataType::F32));
                    if !compatible {
                        let legal_targets = store_value_targets(elem);
                        report.errors.push(err(format!(
                            "Node::Store buffer `{buffer}` value has type `{val_ty}` but element type is `{elem}`. Fix: cast/store using one of {}.", legal_targets
                        )));
                    }
                }
                check_constant_store_index(buffer, buf, index, &mut report.errors);
            }
            validate_expr(index, buffers, scope, options, report, 0);
            validate_expr(value, buffers, scope, options, report, 0);
        }
        Node::If {
            cond,
            then,
            otherwise,
        } => {
            validate_expr(cond, buffers, scope, options, report, 0);
            if let Some(cond_ty) = expr_type(cond, buffers, scope) {
                if !matches!(cond_ty, DataType::U32 | DataType::Bool) {
                    report.errors.push(err(format!(
                        "Node::If condition has type `{cond_ty}` but must be `u32` or `bool`. Fix: cast or rewrite the condition expression to produce `u32` or `bool`."
                    )));
                }
            }
            // Branches stay non-divergent only when the parent scope is
            // already uniform AND the condition is uniform across the
            // workgroup. A non-uniform cond splits invocations across
            // the two branches; a divergent parent already failed the
            // uniformity precondition so we conservatively propagate.
            let branch_divergent = divergent || !is_uniform(cond, scope);
            validate_scoped_nested_nodes(
                then,
                buffers,
                scope,
                branch_divergent,
                depth,
                limits,
                options,
                report,
                |_, _| {},
            );
            validate_scoped_nested_nodes(
                otherwise,
                buffers,
                scope,
                branch_divergent,
                depth,
                limits,
                options,
                report,
                |_, _| {},
            );
        }
        Node::Loop {
            var,
            from,
            to,
            body,
        } => {
            validate_expr(from, buffers, scope, options, report, 0);
            validate_expr(to, buffers, scope, options, report, 0);
            if let Some(from_ty) = expr_type(from, buffers, scope) {
                if from_ty != DataType::U32 {
                    report.errors.push(err(format!(
                        "Node::Loop from-bound has type `{from_ty}`; legal loop bound type is `u32`. Fix: cast the `from` bound to `u32`."
                    )));
                }
            }
            if let Some(to_ty) = expr_type(to, buffers, scope) {
                if to_ty != DataType::U32 {
                    report.errors.push(err(format!(
                        "Node::Loop to-bound has type `{to_ty}`; legal loop bound type is `u32`. Fix: cast the `to` bound to `u32`."
                    )));
                }
            }
            shadowing::check_local(var, scope, options, &mut report.errors);
            // The loop body is divergent only when its parent already is
            // OR when either bound varies across the workgroup. Uniform
            // bounds keep every invocation in lockstep — same iteration
            // count, same loop-var value at each step — so a barrier
            // inside is reached by every lane simultaneously.
            let bounds_uniform = is_uniform(from, scope) && is_uniform(to, scope);
            let body_divergent = divergent || !bounds_uniform;
            // The loop counter inherits the bounds' uniformity; in a
            // uniform-bound loop every lane sees the same counter value
            // at the same source position.
            let var_uniform = bounds_uniform && !divergent;
            validate_scoped_nested_nodes(
                body,
                buffers,
                scope,
                body_divergent,
                depth,
                limits,
                options,
                report,
                |scope, scope_log| {
                    insert_binding(
                        scope,
                        var.clone(),
                        Binding {
                            ty: DataType::U32,
                            mutable: false,
                            uniform: var_uniform,
                        },
                        Some(scope_log),
                    );
                },
            );
        }
        Node::Return => {}
        Node::Block(nodes) => {
            validate_scoped_nested_nodes(
                nodes,
                buffers,
                scope,
                divergent,
                depth,
                limits,
                options,
                report,
                |_, _| {},
            );
        }
        Node::Barrier { ordering } => {
            barrier::check_barrier(divergent, *ordering, &mut report.errors);
        }
        Node::IndirectDispatch {
            count_buffer,
            count_offset,
        } => {
            if count_offset % 4 != 0 {
                report.errors.push(err(format!(
                    "indirect dispatch offset {count_offset} is not 4-byte aligned. Fix: use an offset aligned to a u32 dispatch count tuple."
                )));
            }
            if !buffers.contains_key(count_buffer.as_str()) {
                report.errors.push(err(format!(
                    "indirect dispatch references unknown buffer `{count_buffer}`. Fix: declare the count buffer before validation."
                )));
            }
        }
        Node::AsyncLoad { tag, .. } | Node::AsyncStore { tag, .. } | Node::AsyncWait { tag } => {
            if tag.is_empty() {
                report.errors.push(err(
                    "async stream tag is empty. Fix: use a stable non-empty tag to pair AsyncLoad and AsyncWait nodes."
                        .to_string(),
                ));
            }
        }
        Node::Trap { .. } | Node::Resume { .. } => {}
        Node::Region { body, .. } => {
            // Region is a tracing / grouping marker (emitted by
            // `crate::region::wrap_anonymous` / `wrap_child` so traces
            // and op-id breadcrumbs surface compositionally) — NOT a
            // variable-scoping construct. Builders all over vyre-libs
            // assume `Node::let_bind("acc", …)` declared at one
            // if_then level remains visible to a `wrap_child(...)`
            // sibling that reads `acc` (the gqa_attention max/sum/write
            // pass split, the python parser per-segment helpers, the
            // visual::gradient stop-blend chain, every Cat-A reduction
            // that wraps its hot loop in a named child region).
            //
            // Scoping here breaks those compositions: the inner
            // let_binds die on Region exit and downstream sibling
            // reads fail with V001/V032/V008. Dispatching through the
            // same recursive walker WITHOUT a fresh scope frame
            // restores the visible-across-siblings semantic the
            // builders depend on.
            //
            // True scoping constructs (Block, If/Else branches, Loop
            // body) keep their `validate_scoped_nested_nodes` call
            // sites — Region is the one that was misclassified.
            let mut region_bindings = FxHashSet::default();
            validate_nodes_inner(
                body,
                buffers,
                scope,
                divergent,
                depth.saturating_add(1),
                limits,
                options,
                report,
                &mut region_bindings,
                None,
            );
        }
        Node::Opaque(extension) => {
            if extension.extension_kind().is_empty() {
                report.errors.push(err(
                    "V031: opaque node extension has an empty extension_kind. Fix: return a stable non-empty namespace from NodeExtension::extension_kind.",
                ));
            }
            if extension.debug_identity().is_empty() {
                report.errors.push(err(format!(
                    "V031: opaque node extension `{}` has an empty debug_identity. Fix: return a stable human-readable identity from NodeExtension::debug_identity.",
                    extension.extension_kind()
                )));
            }
            if let Err(message) = extension.validate_extension() {
                report.errors.push(err(format!(
                    "V031: opaque node extension `{}`/`{}` failed validation: {message}",
                    extension.extension_kind(),
                    extension.debug_identity()
                )));
            }
        }
    }
}

#[allow(clippy::too_many_arguments)]
#[cfg(test)]
fn validate_scoped_nested_nodes(
    nodes: &[Node],
    buffers: &FxHashMap<&str, &BufferDecl>,
    scope: &mut FxHashMap<Ident, Binding>,
    divergent: bool,
    depth: usize,
    limits: &mut LimitState,
    options: ValidationOptions<'_>,
    report: &mut ValidationReport,
    configure_scope: impl FnOnce(&mut FxHashMap<Ident, Binding>, &mut ScopeLog),
) {
    let mut scope_log = Vec::new();
    let mut region_bindings = FxHashSet::default();
    configure_scope(scope, &mut scope_log);
    validate_nodes_inner(
        nodes,
        buffers,
        scope,
        divergent,
        depth.saturating_add(1),
        limits,
        options,
        report,
        &mut region_bindings,
        Some(&mut scope_log),
    );
    restore_scope(scope, scope_log);
}

pub(crate) fn check_constant_store_index(
    buffer_name: &str,
    buffer: &BufferDecl,
    index: &Expr,
    errors: &mut Vec<ValidationError>,
) {
    if buffer.count == 0 {
        return;
    }
    match index {
        Expr::LitU32(value) => {
            if *value >= buffer.count {
                errors.push(err(format!(
                    "V036: store index {value} overflows buffer `{buffer_name}` with count {}. Fix: keep constant store indices below the declared element count.",
                    buffer.count
                )));
            }
        }
        Expr::LitI32(value) if *value < 0 => {
            errors.push(err(format!(
                "V036: store index {value} overflows buffer `{buffer_name}` with count {}. Fix: keep constant store indices in 0..{}.",
                buffer.count,
                buffer.count
            )));
        }
        Expr::LitI32(value) => {
            let as_u32 = *value as u32;
            if as_u32 >= buffer.count {
                errors.push(err(format!(
                    "V036: store index {value} overflows buffer `{buffer_name}` with count {}. Fix: keep constant store indices below the declared element count.",
                    buffer.count
                )));
            }
        }
        _ => {}
    }
}

pub(crate) fn insert_binding(
    scope: &mut FxHashMap<Ident, Binding>,
    name: Ident,
    binding: Binding,
    scope_log: Option<&mut ScopeLog>,
) {
    let previous = scope.insert(name.clone(), binding);
    if let Some(scope_log) = scope_log {
        scope_log.push((name, previous));
    }
}

pub(crate) fn restore_scope(scope: &mut FxHashMap<Ident, Binding>, mut scope_log: ScopeLog) {
    while let Some((name, previous)) = scope_log.pop() {
        if let Some(binding) = previous {
            scope.insert(name, binding);
        } else {
            scope.remove(&name);
        }
    }
}

#[inline]
pub(crate) fn store_value_targets(element: &DataType) -> String {
    let mut targets = vec![element.clone()];
    let legal = match element {
        DataType::U32 => vec![DataType::Bytes, DataType::Bool],
        DataType::Bytes => vec![DataType::U32],
        DataType::Bool => vec![DataType::U32],
        _ => Vec::new(),
    };
    for target in legal {
        if !targets.contains(&target) {
            targets.push(target);
        }
    }

    targets
        .into_iter()
        .map(|target| format!("`{target}`"))
        .collect::<Vec<_>>()
        .join(", ")
}

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

    #[test]
    fn store_value_targets_u32_includes_bytes_and_bool() {
        let targets = store_value_targets(&DataType::U32);
        assert!(
            targets.contains("u32"),
            "target list should contain u32: {targets}"
        );
        assert!(
            targets.contains("bytes"),
            "target list should contain bytes: {targets}"
        );
        assert!(
            targets.contains("bool"),
            "target list should contain bool: {targets}"
        );
    }

    #[test]
    fn store_value_targets_f32_is_self_only() {
        let targets = store_value_targets(&DataType::F32);
        assert!(targets.contains("f32"));
        assert!(!targets.contains("u32"));
    }

    #[test]
    fn check_constant_store_index_within_bounds_no_error() {
        let buf = BufferDecl::read_write("buf", 0, DataType::U32).with_count(4);
        let mut errors = Vec::new();
        check_constant_store_index("buf", &buf, &Expr::u32(3), &mut errors);
        assert!(errors.is_empty());
    }

    #[test]
    fn check_constant_store_index_at_boundary_errors() {
        let buf = BufferDecl::read_write("buf", 0, DataType::U32).with_count(4);
        let mut errors = Vec::new();
        check_constant_store_index("buf", &buf, &Expr::u32(4), &mut errors);
        assert_eq!(
            errors.len(),
            1,
            "index == count should overflow: {errors:?}"
        );
    }

    #[test]
    fn check_constant_store_index_negative_i32_errors() {
        let buf = BufferDecl::read_write("buf", 0, DataType::U32).with_count(4);
        let mut errors = Vec::new();
        check_constant_store_index("buf", &buf, &Expr::i32(-1), &mut errors);
        assert_eq!(errors.len(), 1, "negative index should error: {errors:?}");
    }

    #[test]
    fn check_constant_store_index_zero_count_skips() {
        let buf = BufferDecl::read_write("buf", 0, DataType::U32);
        let mut errors = Vec::new();
        check_constant_store_index("buf", &buf, &Expr::u32(999), &mut errors);
        assert!(
            errors.is_empty(),
            "count=0 means dynamic and must be accepted"
        );
    }

    #[test]
    fn check_constant_store_index_dynamic_index_skips() {
        let buf = BufferDecl::read_write("buf", 0, DataType::U32).with_count(4);
        let mut errors = Vec::new();
        check_constant_store_index("buf", &buf, &Expr::Var(Ident::from("i")), &mut errors);
        assert!(errors.is_empty(), "dynamic index must be accepted");
    }
}