softgpu-functional 0.8.0

SoftGPU Phase 6 CPU functional executor for disclosed SoftGPU Functional IR (not gfx1201 ISA)
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
//! SoftGPU Phase 8 sanitizers (functional fidelity).
//!
//! Declared subset (honest, not AMDGPU memory-model evidence):
//! - Shadow tracks allocated / uninitialized / initialized / freed per byte
//! - SoftGPU race: different workitems, overlapping bytes, ≥1 non-atomic write,
//!   same workgroup, same barrier generation (no SoftGPU barrier between them)
//! - Cross-workgroup non-atomic conflicting global accesses are findings
//! - SoftGPU atomics on the same address do not race with each other under the
//!   SoftGPU sequential interpreter; they still mark bytes initialized
//! - Divergent barriers remain validate-time errors (Phase 7)
//!
//! Blind spots (documented): full GPU memory orders, silent aliasing through
//! host pointers, and true hardware concurrency are out of scope.

use crate::error::{FunctionalError, Result};
use crate::exec::{ExecConfig, SchedulePolicy};
use crate::ir::{AddrSpace, Program, TypeId};
use crate::memory::ty_size;
use serde::{Deserialize, Serialize};

pub const SANITIZER_REPLAY_SCHEMA: &str = "softgpu-sanitizer-replay-v1";
pub const MAX_SHADOW_BYTES: usize = 4 * 1024 * 1024;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SanitizeMode {
    /// No shadow / race instrumentation.
    Off,
    /// Collect findings; execution continues unless a hard bounds fault occurs.
    Collect,
    /// Stop at the first sanitizer finding.
    FailFast,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FindingKind {
    OutOfBounds,
    UseAfterFree,
    UninitializedRead,
    Race,
    MissingBarrier,
    CrossWorkgroupRace,
    ShadowLimit,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct WorkItemId {
    pub workgroup: [u32; 3],
    pub wave: u32,
    pub lane: u32,
    pub flat_local: u32,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Finding {
    pub kind: FindingKind,
    pub space: AddrSpace,
    pub addr: u64,
    pub size: usize,
    pub step: u64,
    pub barrier_gen: u64,
    pub actor: WorkItemId,
    pub other: Option<WorkItemId>,
    pub detail: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SanitizeReport {
    pub fidelity: &'static str,
    pub mode: &'static str,
    pub note: &'static str,
    pub findings: Vec<Finding>,
}

impl SanitizeReport {
    pub fn clean() -> Self {
        Self {
            fidelity: "sanitized",
            mode: "softgpu_functional_sanitizer_v1",
            note: "not_gfx1201_isa_emulation",
            findings: Vec::new(),
        }
    }

    pub fn ok(&self) -> bool {
        self.findings.is_empty()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReplayBundle {
    pub schema: String,
    pub program_name: String,
    pub source_provenance: String,
    pub exec: ReplayExec,
    pub finding: Finding,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReplayExec {
    pub grid: [u32; 3],
    pub workgroup: [u32; 3],
    pub wave_size: u32,
    pub group_bytes: u32,
    pub schedule: SchedulePolicy,
    pub step_budget: u64,
}

impl ReplayBundle {
    pub fn from_finding(program: &Program, cfg: &ExecConfig, finding: Finding) -> Self {
        Self {
            schema: SANITIZER_REPLAY_SCHEMA.into(),
            program_name: program.name.clone(),
            source_provenance: program.source_provenance.clone(),
            exec: ReplayExec {
                grid: cfg.launch.grid,
                workgroup: cfg.launch.workgroup,
                wave_size: cfg.wave_size,
                group_bytes: cfg.group_bytes.max(program.group_bytes),
                schedule: cfg.schedule,
                step_budget: cfg.step_budget,
            },
            finding,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ByteState {
    Unallocated,
    Uninitialized,
    Initialized,
    Freed,
}

#[derive(Debug, Clone, Copy)]
struct AccessRecord {
    actor: WorkItemId,
    barrier_gen: u64,
    #[allow(dead_code)]
    step: u64,
    is_write: bool,
    is_atomic: bool,
}

#[derive(Debug, Clone)]
struct ByteShadow {
    state: ByteState,
    last: Option<AccessRecord>,
}

impl Default for ByteShadow {
    fn default() -> Self {
        Self {
            state: ByteState::Unallocated,
            last: None,
        }
    }
}

#[derive(Debug)]
pub struct Sanitizer {
    mode: SanitizeMode,
    global: Vec<ByteShadow>,
    group: Vec<ByteShadow>,
    findings: Vec<Finding>,
    /// SoftGPU WG-local barrier generation (bumped between barrier segments).
    pub barrier_gen: u64,
    pub step: u64,
}

impl Sanitizer {
    pub fn new(mode: SanitizeMode, global_len: usize, group_len: usize) -> Result<Self> {
        if mode == SanitizeMode::Off {
            return Ok(Self {
                mode,
                global: Vec::new(),
                group: Vec::new(),
                findings: Vec::new(),
                barrier_gen: 0,
                step: 0,
            });
        }
        let total = global_len.saturating_add(group_len);
        if total > MAX_SHADOW_BYTES {
            return Err(FunctionalError::Sanitize(Finding {
                kind: FindingKind::ShadowLimit,
                space: AddrSpace::Global,
                addr: 0,
                size: total,
                step: 0,
                barrier_gen: 0,
                actor: WorkItemId {
                    workgroup: [0, 0, 0],
                    wave: 0,
                    lane: 0,
                    flat_local: 0,
                },
                other: None,
                detail: format!("shadow bytes {total} > SoftGPU max {MAX_SHADOW_BYTES}"),
            }));
        }
        let mut s = Self {
            mode,
            global: vec![ByteShadow::default(); global_len],
            group: vec![ByteShadow::default(); group_len],
            findings: Vec::new(),
            barrier_gen: 0,
            step: 0,
        };
        // Host-visible global arena bytes are SoftGPU-initialized at launch; group
        // memory starts uninitialized each workgroup (see reset_group).
        s.mark_initialized(AddrSpace::Global, 0, global_len);
        s.mark_allocated(AddrSpace::Group, 0, group_len);
        Ok(s)
    }

    pub fn mode(&self) -> SanitizeMode {
        self.mode
    }

    pub fn findings(&self) -> &[Finding] {
        &self.findings
    }

    pub fn into_report(self) -> SanitizeReport {
        let mut r = SanitizeReport::clean();
        r.findings = self.findings;
        r
    }

    pub fn reset_group(&mut self) {
        for b in &mut self.group {
            *b = ByteShadow {
                state: ByteState::Uninitialized,
                last: None,
            };
        }
    }

    pub fn mark_allocated(&mut self, space: AddrSpace, addr: u64, len: usize) {
        if self.mode == SanitizeMode::Off || len == 0 {
            return;
        }
        let map = self.map_mut(space);
        let start = addr as usize;
        let end = (start + len).min(map.len());
        for b in map.iter_mut().take(end).skip(start) {
            b.state = ByteState::Uninitialized;
            b.last = None;
        }
    }

    pub fn mark_initialized(&mut self, space: AddrSpace, addr: u64, len: usize) {
        if self.mode == SanitizeMode::Off || len == 0 {
            return;
        }
        let map = self.map_mut(space);
        let start = addr as usize;
        let end = (start + len).min(map.len());
        for b in map.iter_mut().take(end).skip(start) {
            b.state = ByteState::Initialized;
            b.last = None;
        }
    }

    pub fn mark_uninitialized(&mut self, space: AddrSpace, addr: u64, len: usize) {
        self.mark_allocated(space, addr, len);
    }

    pub fn mark_freed(&mut self, space: AddrSpace, addr: u64, len: usize) {
        if self.mode == SanitizeMode::Off || len == 0 {
            return;
        }
        let map = self.map_mut(space);
        let start = addr as usize;
        let end = (start + len).min(map.len());
        for b in map.iter_mut().take(end).skip(start) {
            b.state = ByteState::Freed;
            b.last = None;
        }
    }

    pub fn note_barrier(&mut self) {
        self.barrier_gen = self.barrier_gen.saturating_add(1);
    }

    pub fn on_access(
        &mut self,
        space: AddrSpace,
        addr: u64,
        ty: TypeId,
        is_write: bool,
        is_atomic: bool,
        actor: WorkItemId,
    ) -> Result<()> {
        if self.mode == SanitizeMode::Off {
            return Ok(());
        }
        let size = ty_size(ty);
        let map_len = self.map(space).len();
        let start = match usize::try_from(addr) {
            Ok(s) => s,
            Err(_) => {
                return self.push_finding(Finding {
                    kind: FindingKind::OutOfBounds,
                    space,
                    addr,
                    size,
                    step: self.step,
                    barrier_gen: self.barrier_gen,
                    actor,
                    other: None,
                    detail: "address does not fit SoftGPU arena".into(),
                });
            }
        };
        let end = match start.checked_add(size) {
            Some(e) => e,
            None => {
                return self.push_finding(Finding {
                    kind: FindingKind::OutOfBounds,
                    space,
                    addr,
                    size,
                    step: self.step,
                    barrier_gen: self.barrier_gen,
                    actor,
                    other: None,
                    detail: "access size overflow".into(),
                });
            }
        };
        if end > map_len {
            return self.push_finding(Finding {
                kind: FindingKind::OutOfBounds,
                space,
                addr,
                size,
                step: self.step,
                barrier_gen: self.barrier_gen,
                actor,
                other: None,
                detail: format!("addr+size exceeds arena_len={map_len}"),
            });
        }

        for off in 0..size {
            let idx = start + off;
            let state = self.map(space)[idx].state;
            match state {
                ByteState::Unallocated => {
                    return self.push_finding(Finding {
                        kind: FindingKind::OutOfBounds,
                        space,
                        addr: addr + off as u64,
                        size: 1,
                        step: self.step,
                        barrier_gen: self.barrier_gen,
                        actor,
                        other: None,
                        detail: "access to unallocated SoftGPU shadow byte".into(),
                    });
                }
                ByteState::Freed => {
                    return self.push_finding(Finding {
                        kind: FindingKind::UseAfterFree,
                        space,
                        addr: addr + off as u64,
                        size: 1,
                        step: self.step,
                        barrier_gen: self.barrier_gen,
                        actor,
                        other: None,
                        detail: "access to SoftGPU-freed shadow byte".into(),
                    });
                }
                ByteState::Uninitialized if !is_write => {
                    return self.push_finding(Finding {
                        kind: FindingKind::UninitializedRead,
                        space,
                        addr: addr + off as u64,
                        size: 1,
                        step: self.step,
                        barrier_gen: self.barrier_gen,
                        actor,
                        other: None,
                        detail: "read of uninitialized SoftGPU shadow byte".into(),
                    });
                }
                _ => {}
            }

            if let Some(prev) = self.map(space)[idx].last {
                if let Some(kind) =
                    race_kind(prev, actor, self.barrier_gen, is_write, is_atomic, space)
                {
                    let detail = match kind {
                        FindingKind::MissingBarrier => {
                            "group conflict in same SoftGPU barrier generation without barrier"
                                .into()
                        }
                        FindingKind::Race => {
                            "global conflict in same SoftGPU barrier generation (declared SoftGPU HB subset)".into()
                        }
                        FindingKind::CrossWorkgroupRace => {
                            "conflicting SoftGPU global accesses from different workgroups".into()
                        }
                        _ => "SoftGPU happens-before race in declared subset".into(),
                    };
                    return self.push_finding(Finding {
                        kind,
                        space,
                        addr: addr + off as u64,
                        size: 1,
                        step: self.step,
                        barrier_gen: self.barrier_gen,
                        actor,
                        other: Some(prev.actor),
                        detail,
                    });
                }
            }
        }

        let record = AccessRecord {
            actor,
            barrier_gen: self.barrier_gen,
            step: self.step,
            is_write,
            is_atomic,
        };
        for off in 0..size {
            let b = &mut self.map_mut(space)[start + off];
            if is_write {
                b.state = ByteState::Initialized;
            }
            b.last = Some(record);
        }
        Ok(())
    }

    fn push_finding(&mut self, finding: Finding) -> Result<()> {
        self.findings.push(finding.clone());
        let hard = matches!(
            finding.kind,
            FindingKind::OutOfBounds | FindingKind::UseAfterFree | FindingKind::ShadowLimit
        );
        if self.mode == SanitizeMode::FailFast || hard {
            return Err(FunctionalError::Sanitize(finding));
        }
        Ok(())
    }

    fn map(&self, space: AddrSpace) -> &[ByteShadow] {
        match space {
            AddrSpace::Global => &self.global,
            AddrSpace::Group => &self.group,
        }
    }

    fn map_mut(&mut self, space: AddrSpace) -> &mut [ByteShadow] {
        match space {
            AddrSpace::Global => &mut self.global,
            AddrSpace::Group => &mut self.group,
        }
    }
}

fn race_kind(
    prev: AccessRecord,
    cur: WorkItemId,
    cur_barrier_gen: u64,
    cur_write: bool,
    cur_atomic: bool,
    space: AddrSpace,
) -> Option<FindingKind> {
    // Same workitem: SoftGPU program order — not a race.
    if prev.actor.workgroup == cur.workgroup && prev.actor.flat_local == cur.flat_local {
        return None;
    }
    // Need a write involved.
    if !prev.is_write && !cur_write {
        return None;
    }
    // SoftGPU atomics on both sides: ordered by SoftGPU sequential interpreter.
    if prev.is_atomic && cur_atomic {
        return None;
    }
    if prev.actor.workgroup != cur.workgroup {
        return Some(FindingKind::CrossWorkgroupRace);
    }
    // Same WG: race if same SoftGPU barrier generation (no barrier between).
    if prev.barrier_gen == cur_barrier_gen {
        return Some(match space {
            AddrSpace::Group => FindingKind::MissingBarrier,
            AddrSpace::Global => FindingKind::Race,
        });
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn replay_schema_is_stable() {
        assert_eq!(SANITIZER_REPLAY_SCHEMA, "softgpu-sanitizer-replay-v1");
    }
}