trueno-gpu 0.4.11

Pure Rust PTX generation for NVIDIA CUDA - no LLVM, no nvcc
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
//! PTX Control Flow Extension Trait.
//!
//! Provides labels, branches, returns, and immediate value operations.

use super::super::instructions::{Operand, Predicate, PtxInstruction, PtxOp};
use super::super::registers::VirtualReg;
use super::super::types::PtxType;
use super::core::KernelBuilderCore;

/// Extension trait for PTX control flow operations.
///
/// # Example
///
/// ```ignore
/// use trueno_gpu::ptx::builder::{KernelBuilder, PtxControl};
///
/// fn build_kernel(kb: &mut KernelBuilder) {
///     kb.label("loop_start");
///     // ... loop body ...
///     kb.branch("loop_start");
/// }
/// ```
pub trait PtxControl: KernelBuilderCore {
    // ===== Labels and Branches =====

    /// Create a label at the current position
    fn label(&mut self, name: &str) {
        self.labels_mut().push(name.to_string());
        // Labels are stored as a Mov instruction with label field
        let mut instr = PtxInstruction::new(PtxOp::Mov, PtxType::B32);
        instr.label = Some(format!("{}:", name));
        self.instructions_mut().push(instr);
    }

    /// Unconditional branch
    fn branch(&mut self, target: &str) {
        self.instructions_mut().push(
            PtxInstruction::new(PtxOp::Bra, PtxType::B32).label(target),
        );
    }

    /// Conditional branch (if predicate is true)
    fn branch_if(&mut self, pred: VirtualReg, target: &str) {
        let predicate = Predicate {
            reg: pred,
            negated: false,
        };
        self.instructions_mut().push(
            PtxInstruction::new(PtxOp::Bra, PtxType::B32)
                .predicated(predicate)
                .label(target),
        );
    }

    /// Conditional branch (if predicate is false)
    fn branch_if_not(&mut self, pred: VirtualReg, target: &str) {
        let predicate = Predicate {
            reg: pred,
            negated: true,
        };
        self.instructions_mut().push(
            PtxInstruction::new(PtxOp::Bra, PtxType::B32)
                .predicated(predicate)
                .label(target),
        );
    }

    /// Return from kernel
    fn ret(&mut self) {
        self.instructions_mut()
            .push(PtxInstruction::new(PtxOp::Ret, PtxType::Pred));
    }

    // ===== Immediate Moves =====

    /// Move u64 immediate into new register
    fn mov_u64_imm(&mut self, val: u64) -> VirtualReg {
        let dst = self.registers_mut().allocate_virtual(PtxType::U64);
        self.instructions_mut().push(
            PtxInstruction::new(PtxOp::Mov, PtxType::U64)
                .dst(Operand::Reg(dst))
                .src(Operand::ImmU64(val)),
        );
        dst
    }

    /// Move u32 immediate into new register
    fn mov_u32_imm(&mut self, val: u32) -> VirtualReg {
        let dst = self.registers_mut().allocate_virtual(PtxType::U32);
        self.instructions_mut().push(
            PtxInstruction::new(PtxOp::Mov, PtxType::U32)
                .dst(Operand::Reg(dst))
                .src(Operand::ImmI64(val as i64)),
        );
        dst
    }

    /// Move f32 immediate into new register
    fn mov_f32_imm(&mut self, val: f32) -> VirtualReg {
        let dst = self.registers_mut().allocate_virtual(PtxType::F32);
        self.instructions_mut().push(
            PtxInstruction::new(PtxOp::Mov, PtxType::F32)
                .dst(Operand::Reg(dst))
                .src(Operand::ImmF32(val)),
        );
        dst
    }

    /// Move register to register (copy)
    fn mov_reg(&mut self, src: VirtualReg, ty: PtxType) -> VirtualReg {
        let dst = self.registers_mut().allocate_virtual(ty);
        self.instructions_mut().push(
            PtxInstruction::new(PtxOp::Mov, ty)
                .dst(Operand::Reg(dst))
                .src(Operand::Reg(src)),
        );
        dst
    }
}

// Blanket implementation
impl<T: KernelBuilderCore> PtxControl for T {}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ptx::registers::RegisterAllocator;

    struct MockBuilder {
        registers: RegisterAllocator,
        instructions: Vec<PtxInstruction>,
        labels: Vec<String>,
    }

    impl MockBuilder {
        fn new() -> Self {
            Self {
                registers: RegisterAllocator::new(),
                instructions: Vec::new(),
                labels: Vec::new(),
            }
        }
    }

    impl KernelBuilderCore for MockBuilder {
        fn registers_mut(&mut self) -> &mut RegisterAllocator {
            &mut self.registers
        }
        fn instructions_mut(&mut self) -> &mut Vec<PtxInstruction> {
            &mut self.instructions
        }
        fn labels_mut(&mut self) -> &mut Vec<String> {
            &mut self.labels
        }
    }

    #[test]
    fn test_label_and_branch() {
        let mut builder = MockBuilder::new();

        builder.label("loop_start");
        builder.branch("loop_start");

        assert_eq!(builder.labels.len(), 1);
        assert_eq!(builder.labels[0], "loop_start");
        assert_eq!(builder.instructions.len(), 2);
    }

    #[test]
    fn test_conditional_branch() {
        let mut builder = MockBuilder::new();
        let pred = builder.registers.allocate_virtual(PtxType::Pred);

        builder.branch_if(pred, "target");
        builder.branch_if_not(pred, "other");

        assert_eq!(builder.instructions.len(), 2);
        assert!(builder.instructions[0].predicate.is_some());
        assert!(builder.instructions[1].predicate.is_some());
        // First one not negated
        assert!(!builder.instructions[0].predicate.as_ref().unwrap().negated);
        // Second one negated
        assert!(builder.instructions[1].predicate.as_ref().unwrap().negated);
    }

    #[test]
    fn test_mov_immediates() {
        let mut builder = MockBuilder::new();

        let _a = builder.mov_u32_imm(42);
        let _b = builder.mov_u64_imm(12345);
        let _c = builder.mov_f32_imm(3.14);

        assert_eq!(builder.instructions.len(), 3);
        for instr in &builder.instructions {
            assert_eq!(instr.op, PtxOp::Mov);
        }
    }

    #[test]
    fn test_ret() {
        let mut builder = MockBuilder::new();

        builder.ret();

        assert_eq!(builder.instructions.len(), 1);
        assert_eq!(builder.instructions[0].op, PtxOp::Ret);
    }

    #[test]
    fn test_mov_reg() {
        let mut builder = MockBuilder::new();

        // First create a source register with a value
        let src = builder.mov_u32_imm(42);

        // Then copy it to another register
        let dst = builder.mov_reg(src, PtxType::U32);

        // Should have 2 instructions: original mov_imm and the reg-to-reg mov
        assert_eq!(builder.instructions.len(), 2);

        // Both should be Mov operations
        assert_eq!(builder.instructions[0].op, PtxOp::Mov);
        assert_eq!(builder.instructions[1].op, PtxOp::Mov);

        // The source and destination should be different registers
        assert_ne!(src, dst);

        // Check that the second instruction has the src register as source operand
        assert!(!builder.instructions[1].srcs.is_empty());
        match &builder.instructions[1].srcs[0] {
            Operand::Reg(r) => assert_eq!(*r, src),
            _ => panic!("Expected register source operand"),
        }

        // Check that the second instruction has the dst register as destination operand
        match &builder.instructions[1].dst {
            Some(Operand::Reg(r)) => assert_eq!(*r, dst),
            _ => panic!("Expected register destination operand"),
        }
    }

    #[test]
    fn test_mov_reg_f32() {
        let mut builder = MockBuilder::new();

        // Create f32 source register
        let src = builder.mov_f32_imm(3.14);

        // Copy to another f32 register
        let dst = builder.mov_reg(src, PtxType::F32);

        assert_eq!(builder.instructions.len(), 2);
        assert_eq!(builder.instructions[1].ty, PtxType::F32);
        assert_ne!(src, dst);
    }

    #[test]
    fn test_multiple_labels() {
        let mut builder = MockBuilder::new();

        builder.label("start");
        builder.label("middle");
        builder.label("end");

        assert_eq!(builder.labels.len(), 3);
        assert_eq!(builder.labels[0], "start");
        assert_eq!(builder.labels[1], "middle");
        assert_eq!(builder.labels[2], "end");

        // Verify label instructions are created
        assert_eq!(builder.instructions.len(), 3);
        for instr in &builder.instructions {
            assert!(instr.label.is_some());
        }
    }

    #[test]
    fn test_label_format() {
        let mut builder = MockBuilder::new();

        builder.label("my_loop");

        let instr = &builder.instructions[0];
        assert_eq!(instr.label, Some("my_loop:".to_string()));
    }

    #[test]
    fn test_branch_creates_label_target() {
        let mut builder = MockBuilder::new();

        builder.branch("exit");

        let instr = &builder.instructions[0];
        assert_eq!(instr.op, PtxOp::Bra);
        assert_eq!(instr.label, Some("exit".to_string()));
        assert!(instr.predicate.is_none());
    }

    #[test]
    fn test_branch_if_predicate_structure() {
        let mut builder = MockBuilder::new();
        let pred = builder.registers.allocate_virtual(PtxType::Pred);

        builder.branch_if(pred, "target_label");

        let instr = &builder.instructions[0];
        let predicate = instr.predicate.as_ref().unwrap();

        assert_eq!(predicate.reg, pred);
        assert!(!predicate.negated);
    }

    #[test]
    fn test_branch_if_not_predicate_structure() {
        let mut builder = MockBuilder::new();
        let pred = builder.registers.allocate_virtual(PtxType::Pred);

        builder.branch_if_not(pred, "other_label");

        let instr = &builder.instructions[0];
        let predicate = instr.predicate.as_ref().unwrap();

        assert_eq!(predicate.reg, pred);
        assert!(predicate.negated);
    }

    #[test]
    fn test_mov_u64_imm_value() {
        let mut builder = MockBuilder::new();

        let reg = builder.mov_u64_imm(0xDEADBEEFCAFEBABE);

        assert_eq!(builder.instructions.len(), 1);
        let instr = &builder.instructions[0];

        assert_eq!(instr.op, PtxOp::Mov);
        assert_eq!(instr.ty, PtxType::U64);

        // Verify destination is the returned register
        match &instr.dst {
            Some(Operand::Reg(r)) => assert_eq!(*r, reg),
            _ => panic!("Expected register destination"),
        }

        // Verify source is the immediate value
        assert!(!instr.srcs.is_empty());
        match &instr.srcs[0] {
            Operand::ImmU64(v) => assert_eq!(*v, 0xDEADBEEFCAFEBABE),
            _ => panic!("Expected ImmU64 source"),
        }
    }

    #[test]
    fn test_mov_u32_imm_value() {
        let mut builder = MockBuilder::new();

        let reg = builder.mov_u32_imm(0xCAFEBABE);

        let instr = &builder.instructions[0];
        assert_eq!(instr.ty, PtxType::U32);

        // Verify destination
        match &instr.dst {
            Some(Operand::Reg(r)) => assert_eq!(*r, reg),
            _ => panic!("Expected register destination"),
        }

        // Verify source (stored as i64)
        assert!(!instr.srcs.is_empty());
        match &instr.srcs[0] {
            Operand::ImmI64(v) => assert_eq!(*v, 0xCAFEBABE_i64),
            _ => panic!("Expected ImmI64 source"),
        }
    }

    #[test]
    fn test_mov_f32_imm_value() {
        let mut builder = MockBuilder::new();

        let reg = builder.mov_f32_imm(2.71828);

        let instr = &builder.instructions[0];
        assert_eq!(instr.ty, PtxType::F32);

        // Verify destination
        match &instr.dst {
            Some(Operand::Reg(r)) => assert_eq!(*r, reg),
            _ => panic!("Expected register destination"),
        }

        // Verify source
        assert!(!instr.srcs.is_empty());
        match &instr.srcs[0] {
            Operand::ImmF32(v) => assert!((v - 2.71828).abs() < 1e-5),
            _ => panic!("Expected ImmF32 source"),
        }
    }

    #[test]
    fn test_ret_instruction_type() {
        let mut builder = MockBuilder::new();

        builder.ret();

        let instr = &builder.instructions[0];
        assert_eq!(instr.op, PtxOp::Ret);
        assert_eq!(instr.ty, PtxType::Pred);
    }
}