llvm-native-core 0.1.5

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
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
//! LLVM Target Machine — top-level compilation driver dispatching
//! to the appropriate backend for code generation.
//!
//! The `TargetMachine` is the central compilation entry point. It owns
//! the target description (TargetInfo), data layout, and all target-
//! specific configuration. It dispatches compilation requests to the
//! correct backend based on the target triple.
//!
//! Clean-room behavioral reconstruction. No LLVM source consulted.

use crate::codegen::{AsmPrinter, InstructionSelector, MachineFunction, RegisterAllocator};
use crate::data_layout::DataLayout;
use crate::target_info::{TargetInfo, TargetRegistry};
use crate::triple::{Arch, Triple};
use crate::value::ValueRef;

// ═══════════════════════════════════════════════════════════════════════════
// Optimization levels
// ═══════════════════════════════════════════════════════════════════════════

/// Code generation optimization level.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum CodeGenOptLevel {
    None = 0,
    Less = 1,
    Default = 2,
    Aggressive = 3,
}

impl CodeGenOptLevel {
    pub fn should_optimize(&self) -> bool {
        *self > CodeGenOptLevel::None
    }
}

impl Default for CodeGenOptLevel {
    fn default() -> Self {
        Self::Default
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Relocation model
// ═══════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RelocModel {
    Static,
    PIC,          // Position-Independent Code
    DynamicNoPic, // Dynamic linker, non-PIC (rare)
    ROPI,         // Read-Only Position Independence
    RWPI,         // Read-Write Position Independence
    ROPIRWPI,     // Both ROPI and RWPI
}

impl RelocModel {
    pub fn is_pic(&self) -> bool {
        matches!(
            self,
            RelocModel::PIC | RelocModel::ROPI | RelocModel::ROPIRWPI
        )
    }
}

impl Default for RelocModel {
    fn default() -> Self {
        Self::Static
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Code model
// ═══════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodeModel {
    Tiny,
    Small,
    Kernel,
    Medium,
    Large,
}

impl Default for CodeModel {
    fn default() -> Self {
        Self::Small
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Float ABI
// ═══════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FloatABI {
    Default,
    Soft, // Software floating-point
    Hard, // Hardware floating-point
}

impl Default for FloatABI {
    fn default() -> Self {
        FloatABI::Default
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Target options
// ═══════════════════════════════════════════════════════════════════════════

/// Per-target configuration knobs that control code generation behavior.
#[derive(Debug, Clone)]
pub struct TargetOptions {
    /// Target triple string.
    pub triple: String,
    /// CPU name (e.g., "skylake", "cortex-a53", "generic").
    pub cpu: String,
    /// Comma-separated target feature string (+sse2,-avx).
    pub features: String,
    /// ABI name (e.g., "gnu", "msvc", "eabi").
    pub abi: String,
    /// Code generation optimization level.
    pub opt_level: CodeGenOptLevel,
    /// Relocation model.
    pub reloc_model: RelocModel,
    /// Code model.
    pub code_model: CodeModel,
    /// Floating-point ABI.
    pub float_abi: FloatABI,
    /// Emit position-independent code.
    pub position_independent: bool,
    /// Emit thread-local storage in local-exec model.
    pub use_local_exec_tls: bool,
    /// Use soft-float (emulate FP operations).
    pub use_soft_float: bool,
    /// Disable frame pointer elimination.
    pub disable_fp_elim: bool,
    /// Emit unwind tables.
    pub emit_unwind_tables: bool,
    /// Stack alignment override (0 = natural).
    pub stack_alignment: u32,
    /// Machine code output path (if writing to file).
    pub output_file: Option<String>,
    /// Assume no signed overflow (enable more optimizations).
    pub no_signed_zeros_fp_math: bool,
    /// Enable approximate reciprocal for FP division.
    pub unsafe_fp_math: bool,
    /// Trap on unaligned memory access.
    pub trap_unaligned: bool,
    /// Function sections: place each function in its own section.
    pub function_sections: bool,
    /// Data sections: place each global in its own section.
    pub data_sections: bool,
    /// Integrated assembler: emit machine code directly.
    pub integrated_as: bool,
    /// Preserve comments in assembly output.
    pub preserve_asm_comments: bool,
    /// Emit compact unwind information (Mach-O/ELF).
    pub emit_compact_unwind: bool,
    /// Thread model (posix, single).
    pub thread_model: String,
}

impl Default for TargetOptions {
    fn default() -> Self {
        Self {
            triple: String::new(),
            cpu: String::from("generic"),
            features: String::new(),
            abi: String::new(),
            opt_level: CodeGenOptLevel::default(),
            reloc_model: RelocModel::default(),
            code_model: CodeModel::default(),
            float_abi: FloatABI::Default,
            position_independent: false,
            use_local_exec_tls: false,
            use_soft_float: false,
            disable_fp_elim: false,
            emit_unwind_tables: true,
            stack_alignment: 0,
            output_file: None,
            no_signed_zeros_fp_math: false,
            unsafe_fp_math: false,
            trap_unaligned: false,
            function_sections: false,
            data_sections: false,
            integrated_as: true,
            preserve_asm_comments: false,
            emit_compact_unwind: false,
            thread_model: String::from("posix"),
        }
    }
}

impl TargetOptions {
    /// Create TargetOptions from a triple string.
    pub fn from_triple(triple: &str) -> Self {
        let t = Triple::parse(triple);
        let mut opts = Self::default();
        opts.triple = triple.to_string();

        // Set platform-appropriate defaults
        match t.arch {
            Arch::X86_64
            | Arch::AArch64
            | Arch::RISCV64
            | Arch::PowerPC64
            | Arch::SystemZ
            | Arch::Sparcv9
            | Arch::Mips64
            | Arch::LoongArch64
            | Arch::NVPTX64
            | Arch::WebAssembly64
            | Arch::AMDGPU
            | Arch::BPF => {
                // 64-bit targets default to small code model
                opts.code_model = CodeModel::Small;
            }
            _ => {
                opts.code_model = CodeModel::Small;
            }
        }

        // Windows targets
        if t.is_windows() {
            opts.abi = String::from("msvc");
        }

        opts
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Target Machine
// ═══════════════════════════════════════════════════════════════════════════

/// Top-level target machine that drives code generation.
pub struct TargetMachine {
    /// Target description and features.
    pub info: TargetInfo,
    /// Target options.
    pub options: TargetOptions,
    /// The registry this machine was created from.
    pub registry: TargetRegistry,
}

impl TargetMachine {
    /// Create a TargetMachine for the given target triple with default options.
    pub fn new(triple_str: &str) -> Self {
        let triple = Triple::parse(triple_str);
        let info = TargetInfo::from_triple(triple.clone());
        let options = TargetOptions::from_triple(triple_str);
        let registry = TargetRegistry::new();
        Self {
            info,
            options,
            registry,
        }
    }

    /// Create a TargetMachine with custom options.
    pub fn with_options(triple_str: &str, options: TargetOptions) -> Self {
        let triple = Triple::parse(triple_str);
        let info = TargetInfo::from_triple(triple);
        let registry = TargetRegistry::new();
        Self {
            info,
            options,
            registry,
        }
    }

    /// Get the target triple string.
    pub fn triple(&self) -> String {
        self.info.triple.to_string()
    }

    /// Get the data layout.
    pub fn data_layout(&self) -> &DataLayout {
        &self.info.data_layout
    }

    /// Get the parsed Triple.
    pub fn get_triple(&self) -> &Triple {
        &self.info.triple
    }

    /// Whether this is a 64-bit target.
    pub fn is_64bit(&self) -> bool {
        self.info.triple.is_64bit()
    }

    /// Whether this is a little-endian target.
    pub fn is_little_endian(&self) -> bool {
        self.data_layout().is_little_endian()
    }

    /// Get the pointer size in bits.
    pub fn pointer_size(&self) -> u32 {
        self.data_layout().pointer_size()
    }

    /// Get the optimization level.
    pub fn opt_level(&self) -> CodeGenOptLevel {
        self.options.opt_level
    }

    /// Check if a CPU feature is enabled.
    pub fn has_feature(&self, feature: &str) -> bool {
        self.info.has_feature(feature)
    }

    /// Enable a CPU feature.
    pub fn enable_feature(&mut self, feature: &str) {
        self.info.enable_feature(feature);
    }

    /// Disable a CPU feature.
    pub fn disable_feature(&mut self, feature: &str) {
        self.info.disable_feature(feature);
    }

    /// Get the ABI name.
    pub fn abi(&self) -> &str {
        &self.options.abi
    }

    /// Check if position-independent code is requested.
    pub fn is_pic(&self) -> bool {
        self.options.position_independent || self.options.reloc_model.is_pic()
    }

    // ═══════════════════════════════════════════════════════════════════
    // Compilation entry points
    // ═══════════════════════════════════════════════════════════════════

    /// Compile a function to assembly, dispatching to the correct backend.
    pub fn compile_function(&self, func: &ValueRef) -> String {
        match self.info.triple.arch {
            Arch::X86_64 | Arch::X86 => self.compile_x86(func),
            Arch::AArch64 | Arch::ARM | Arch::ARMeb | Arch::Thumb => self.compile_arm(func),
            Arch::RISCV64 | Arch::RISCV32 => self.compile_riscv(func),
            Arch::WebAssembly32 | Arch::WebAssembly64 => self.compile_wasm(func),
            Arch::AMDGPU => self.compile_amdgpu(func),
            Arch::NVPTX | Arch::NVPTX64 => self.compile_nvptx(func),
            Arch::Mips | Arch::Mips64 | Arch::Mipsel | Arch::Mips64el => self.compile_mips(func),
            Arch::PowerPC | Arch::PowerPC64 | Arch::PowerPC64le => self.compile_powerpc(func),
            Arch::SystemZ => self.compile_systemz(func),
            Arch::Sparc | Arch::Sparcv9 => self.compile_sparc(func),
            Arch::BPF | Arch::BPFEB | Arch::BPF64 => self.compile_bpf(func),
            Arch::AVR => self.compile_avr(func),
            Arch::MSP430 => self.compile_msp430(func),
            Arch::Hexagon => self.compile_hexagon(func),
            Arch::Lanai => self.compile_lanai(func),
            Arch::ARC => self.compile_arc(func),
            Arch::CSKY => self.compile_csky(func),
            Arch::Xtensa => self.compile_xtensa(func),
            _ => self.compile_generic(func),
        }
    }

    /// Compile a function to machine code bytes.
    pub fn compile_to_object(&self, func: &ValueRef) -> Vec<u8> {
        // Compile to assembly first, then assemble
        let _asm = self.compile_function(func);
        // In a full implementation, invoke MC assembler to produce bytes
        Vec::new()
    }

    /// Compile multiple functions to an object file.
    pub fn compile_module_to_object(&self, funcs: &[&ValueRef]) -> Vec<u8> {
        let mut obj = Vec::new();
        for func in funcs {
            obj.extend(self.compile_to_object(func));
        }
        obj
    }

    // ═══════════════════════════════════════════════════════════════════
    // Backend-specific compilation
    // ═══════════════════════════════════════════════════════════════════

    fn compile_x86(&self, func: &ValueRef) -> String {
        let f = func.borrow();
        let mut mf = MachineFunction::new(&f.name);
        InstructionSelector::select(&mut mf, func);
        let mut ra = RegisterAllocator::new();
        ra.allocate(&mut mf);
        let mut printer = AsmPrinter::new();
        printer.print_function(&mf);
        printer.output
    }

    fn compile_arm(&self, _func: &ValueRef) -> String {
        String::new() // arm_backend disabled
    }

    fn compile_riscv(&self, func: &ValueRef) -> String {
        let f = func.borrow();
        let mut mf = MachineFunction::new(&f.name);
        InstructionSelector::select(&mut mf, func);
        let mut ra = RegisterAllocator::new();
        ra.allocate(&mut mf);
        let mut printer = AsmPrinter::new();
        printer.print_function(&mf);
        printer.output
    }

    fn compile_wasm(&self, _func: &ValueRef) -> String {
        String::from("(module)\n")
    }

    fn compile_amdgpu(&self, _func: &ValueRef) -> String {
        String::from("; AMDGPU kernel\n")
    }

    fn compile_nvptx(&self, _func: &ValueRef) -> String {
        String::from("// NVPTX kernel\n")
    }

    fn compile_mips(&self, func: &ValueRef) -> String {
        self.compile_riscv(func) // temporary fallback
    }

    fn compile_powerpc(&self, func: &ValueRef) -> String {
        self.compile_riscv(func)
    }

    fn compile_systemz(&self, func: &ValueRef) -> String {
        self.compile_riscv(func)
    }

    fn compile_sparc(&self, func: &ValueRef) -> String {
        self.compile_riscv(func)
    }

    fn compile_bpf(&self, _func: &ValueRef) -> String {
        String::from("; BPF bytecode\n")
    }

    fn compile_avr(&self, func: &ValueRef) -> String {
        self.compile_riscv(func)
    }

    fn compile_msp430(&self, func: &ValueRef) -> String {
        self.compile_riscv(func)
    }

    fn compile_hexagon(&self, func: &ValueRef) -> String {
        self.compile_riscv(func)
    }

    fn compile_lanai(&self, func: &ValueRef) -> String {
        self.compile_riscv(func)
    }

    fn compile_arc(&self, func: &ValueRef) -> String {
        self.compile_riscv(func)
    }

    fn compile_csky(&self, func: &ValueRef) -> String {
        self.compile_riscv(func)
    }

    fn compile_xtensa(&self, func: &ValueRef) -> String {
        self.compile_riscv(func)
    }

    fn compile_generic(&self, func: &ValueRef) -> String {
        self.compile_x86(func)
    }
}

impl Default for TargetMachine {
    fn default() -> Self {
        Self::new("x86_64-unknown-linux-gnu")
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// TargetMachine builder
// ═══════════════════════════════════════════════════════════════════════════

/// Builder for constructing a TargetMachine with custom configuration.
pub struct TargetMachineBuilder {
    triple: String,
    cpu: String,
    features: String,
    opt_level: CodeGenOptLevel,
    reloc_model: RelocModel,
    code_model: CodeModel,
    float_abi: FloatABI,
    position_independent: bool,
    function_sections: bool,
    data_sections: bool,
    disable_fp_elim: bool,
    emit_unwind_tables: bool,
}

impl TargetMachineBuilder {
    pub fn new(triple: &str) -> Self {
        Self {
            triple: triple.to_string(),
            cpu: String::from("generic"),
            features: String::new(),
            opt_level: CodeGenOptLevel::Default,
            reloc_model: RelocModel::Static,
            code_model: CodeModel::Small,
            float_abi: FloatABI::Default,
            position_independent: false,
            function_sections: false,
            data_sections: false,
            disable_fp_elim: false,
            emit_unwind_tables: true,
        }
    }

    pub fn cpu(mut self, cpu: &str) -> Self {
        self.cpu = cpu.to_string();
        self
    }

    pub fn features(mut self, features: &str) -> Self {
        self.features = features.to_string();
        self
    }

    pub fn opt_level(mut self, level: CodeGenOptLevel) -> Self {
        self.opt_level = level;
        self
    }

    pub fn reloc_model(mut self, model: RelocModel) -> Self {
        self.reloc_model = model;
        self
    }

    pub fn code_model(mut self, model: CodeModel) -> Self {
        self.code_model = model;
        self
    }

    pub fn pic(mut self, pic: bool) -> Self {
        self.position_independent = pic;
        self
    }

    pub fn function_sections(mut self, fs: bool) -> Self {
        self.function_sections = fs;
        self
    }

    pub fn build(self) -> TargetMachine {
        let opts = TargetOptions {
            triple: self.triple.clone(),
            cpu: self.cpu,
            features: self.features,
            opt_level: self.opt_level,
            reloc_model: self.reloc_model,
            code_model: self.code_model,
            float_abi: self.float_abi,
            position_independent: self.position_independent,
            function_sections: self.function_sections,
            data_sections: self.data_sections,
            disable_fp_elim: self.disable_fp_elim,
            emit_unwind_tables: self.emit_unwind_tables,
            ..Default::default()
        };
        TargetMachine::with_options(&self.triple, opts)
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════

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

    #[test]
    fn test_create_x86_64() {
        let tm = TargetMachine::new("x86_64-unknown-linux-gnu");
        assert!(tm.is_64bit());
        assert!(tm.is_little_endian());
    }

    #[test]
    fn test_create_aarch64() {
        let tm = TargetMachine::new("aarch64-unknown-linux-gnu");
        assert!(tm.is_64bit());
    }

    #[test]
    fn test_create_arm32() {
        let tm = TargetMachine::new("armv7-unknown-linux-gnueabihf");
        assert!(!tm.is_64bit());
    }

    #[test]
    fn test_triple_roundtrip() {
        let tm = TargetMachine::new("x86_64-pc-windows-msvc");
        assert!(tm.triple().contains("x86_64"));
        assert!(tm.triple().contains("windows"));
    }

    #[test]
    fn test_data_layout() {
        let tm = TargetMachine::new("x86_64-unknown-linux-gnu");
        assert!(tm.data_layout().is_little_endian());
        assert_eq!(tm.pointer_size(), 64);
    }

    #[test]
    fn test_builder_defaults() {
        let tm = TargetMachineBuilder::new("aarch64-unknown-linux-gnu").build();
        assert!(tm.is_64bit());
        assert_eq!(tm.opt_level(), CodeGenOptLevel::Default);
    }

    #[test]
    fn test_builder_custom_options() {
        let tm = TargetMachineBuilder::new("x86_64-unknown-linux-gnu")
            .cpu("skylake")
            .opt_level(CodeGenOptLevel::Aggressive)
            .pic(true)
            .function_sections(true)
            .build();
        assert!(tm.is_pic());
        assert!(tm.options.function_sections);
        assert_eq!(tm.options.cpu, "skylake");
    }

    #[test]
    fn test_reloc_model_pic() {
        assert!(RelocModel::PIC.is_pic());
        assert!(RelocModel::ROPI.is_pic());
        assert!(!RelocModel::Static.is_pic());
    }

    #[test]
    fn test_codegen_opt_level() {
        assert!(!CodeGenOptLevel::None.should_optimize());
        assert!(CodeGenOptLevel::Default.should_optimize());
        assert!(CodeGenOptLevel::Aggressive.should_optimize());
    }

    #[test]
    fn test_enable_disable_feature() {
        let mut tm = TargetMachine::new("x86_64-unknown-linux-gnu");
        tm.enable_feature("+sse4.2");
        assert!(tm.has_feature("+sse4.2"));
        tm.disable_feature("+sse4.2");
        assert!(!tm.has_feature("+sse4.2"));
    }

    #[test]
    fn test_default_target_machine() {
        let tm = TargetMachine::default();
        assert!(tm.triple().contains("x86_64"));
    }

    #[test]
    fn test_target_options_default() {
        let opts = TargetOptions::default();
        assert_eq!(opts.cpu, "generic");
        assert_eq!(opts.opt_level, CodeGenOptLevel::Default);
        assert_eq!(opts.thread_model, "posix");
    }
}